You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

100 lines
1.9 KiB

  1. package Auth
  2. import (
  3. "fmt"
  4. "net/http"
  5. "net/http/httptest"
  6. "os"
  7. "path"
  8. "runtime"
  9. "strings"
  10. "testing"
  11. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
  12. "github.com/gorilla/mux"
  13. )
  14. func init() {
  15. // Fix working directory for tests
  16. _, filename, _, _ := runtime.Caller(0)
  17. dir := path.Join(path.Dir(filename), "..")
  18. err := os.Chdir(dir)
  19. if err != nil {
  20. panic(err)
  21. }
  22. Database.InitTest()
  23. r = mux.NewRouter()
  24. }
  25. func Test_UpdatePassword(t *testing.T) {
  26. t.Log("Testing UpdatePassword...")
  27. r.HandleFunc("/admin/login", Logout).Methods("POST")
  28. r.HandleFunc("/admin/user/{userID}/update-password", UpdatePassword).Methods("PUT")
  29. ts := httptest.NewServer(r)
  30. defer ts.Close()
  31. userData, err := createTestUser(true)
  32. if err != nil {
  33. t.Errorf("Expected nil, recieved %s", err.Error())
  34. t.FailNow()
  35. }
  36. postJson := `
  37. {
  38. "email": "%s",
  39. "password": "password"
  40. }
  41. `
  42. postJson = fmt.Sprintf(postJson, userData.Email)
  43. res, err := http.Post(ts.URL+"/admin/login", "application/json", strings.NewReader(postJson))
  44. if err != nil {
  45. t.Errorf("Expected nil, recieved %s", err.Error())
  46. return
  47. }
  48. if res.StatusCode != http.StatusOK {
  49. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  50. return
  51. }
  52. if len(res.Cookies()) != 1 {
  53. t.Errorf("Expected cookies len 1, recieved %d", len(res.Cookies()))
  54. return
  55. }
  56. postJson = `
  57. {
  58. "password": "new_password",
  59. "confirm_password": "new_password"
  60. }
  61. `
  62. req, err := http.NewRequest("PUT", fmt.Sprintf(
  63. "%s/admin/user/%s/update-password",
  64. ts.URL,
  65. userData.ID,
  66. ), strings.NewReader(postJson))
  67. if err != nil {
  68. t.Errorf("Expected nil, recieved %s", err.Error())
  69. return
  70. }
  71. req.AddCookie(res.Cookies()[0])
  72. res, err = http.DefaultClient.Do(req)
  73. if err != nil {
  74. t.Errorf("Expected nil, recieved %s", err.Error())
  75. return
  76. }
  77. if res.StatusCode != http.StatusOK {
  78. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  79. return
  80. }
  81. }