Core functionality for new aiterp.net servers
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.

110 lines
2.2 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package auth
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/url"
  7. "strings"
  8. "testing"
  9. "time"
  10. )
  11. type handlerStruct struct{}
  12. func (hs *handlerStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  13. req.ParseForm() // Router does this in non-tests
  14. if strings.HasPrefix(req.URL.Path, "/auth") {
  15. Handler.Handle("/auth", w, req, nil)
  16. return
  17. }
  18. }
  19. func TestHandler(t *testing.T) {
  20. server := httptest.NewServer(&handlerStruct{})
  21. auther := testAuther{FullName: "Test"}
  22. Register(&auther)
  23. form := url.Values{}
  24. form.Set("method", "test")
  25. form.Set("username", "Test")
  26. form.Set("password", "stuff'nthings")
  27. form2 := url.Values{}
  28. form2.Set("method", "test")
  29. form3 := url.Values{}
  30. form3.Set("method", "test")
  31. form3.Set("username", "Test2")
  32. form3.Set("password", "stuff'nthings")
  33. t.Run("Register", func(t *testing.T) {
  34. resp, err := http.PostForm(server.URL+"/auth/register", form)
  35. if err != nil {
  36. t.Error("Request:", err)
  37. t.Fail()
  38. }
  39. if resp.StatusCode != 200 {
  40. t.Error("Expected 200, got", resp.Status)
  41. t.Fail()
  42. }
  43. respSession := Session{}
  44. json.NewDecoder(resp.Body).Decode(&respSession)
  45. if respSession.UserID == "" {
  46. t.Errorf("No user ID in session")
  47. t.Fail()
  48. }
  49. if time.Since(respSession.Time) > time.Second {
  50. t.Error("Session time is too low", time.Since(respSession.Time))
  51. t.Fail()
  52. }
  53. })
  54. t.Run("Login", func(t *testing.T) {
  55. resp, err := http.PostForm(server.URL+"/auth/login", form)
  56. if err != nil {
  57. t.Error("Request:", err)
  58. t.Fail()
  59. }
  60. if resp.StatusCode != 200 {
  61. t.Error("Expected 200, got", resp.Status)
  62. t.Fail()
  63. }
  64. respSession := Session{}
  65. json.NewDecoder(resp.Body).Decode(&respSession)
  66. if respSession.UserID == "" {
  67. t.Errorf("No user ID in session")
  68. t.Fail()
  69. }
  70. })
  71. t.Run("Login_Fail", func(t *testing.T) {
  72. resp, err := http.PostForm(server.URL+"/auth/login", form3)
  73. if err != nil {
  74. t.Error("Request:", err)
  75. t.Fail()
  76. }
  77. if resp.StatusCode != 401 {
  78. t.Error("Expected 401, got", resp.Status)
  79. t.Fail()
  80. }
  81. respSession := Session{}
  82. json.NewDecoder(resp.Body).Decode(&respSession)
  83. if respSession.UserID != "" {
  84. t.Errorf("A user ID in supposedly empty session")
  85. t.Fail()
  86. }
  87. })
  88. }