|
|
@ -1,10 +1,13 @@ |
|
|
|
package auth |
|
|
|
|
|
|
|
import ( |
|
|
|
"encoding/json" |
|
|
|
"net/http" |
|
|
|
"net/http/httptest" |
|
|
|
"net/url" |
|
|
|
"strings" |
|
|
|
"testing" |
|
|
|
"time" |
|
|
|
) |
|
|
|
|
|
|
|
type handlerStruct struct{} |
|
|
@ -19,14 +22,89 @@ func (hs *handlerStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { |
|
|
|
} |
|
|
|
|
|
|
|
func TestHandler(t *testing.T) { |
|
|
|
server := httptest.NewServer(&handlerStruct{}) |
|
|
|
|
|
|
|
auther := testAuther{FullName: "Test"} |
|
|
|
Register(&auther) |
|
|
|
|
|
|
|
form := url.Values{} |
|
|
|
form.Set("method", "test") |
|
|
|
form.Set("username", "Test") |
|
|
|
form.Set("password", "stuff'nthings") |
|
|
|
|
|
|
|
form2 := url.Values{} |
|
|
|
form2.Set("method", "test") |
|
|
|
|
|
|
|
form3 := url.Values{} |
|
|
|
form3.Set("method", "test") |
|
|
|
form3.Set("username", "Test2") |
|
|
|
form3.Set("password", "stuff'nthings") |
|
|
|
|
|
|
|
t.Run("Register", func(t *testing.T) { |
|
|
|
resp, err := http.PostForm(server.URL+"/auth/register", form) |
|
|
|
if err != nil { |
|
|
|
t.Error("Request:", err) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
if resp.StatusCode != 200 { |
|
|
|
t.Error("Expected 200, got", resp.Status) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
respSession := Session{} |
|
|
|
json.NewDecoder(resp.Body).Decode(&respSession) |
|
|
|
|
|
|
|
if respSession.UserID == "" { |
|
|
|
t.Errorf("No user ID in session") |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
if time.Since(respSession.Time) > time.Second { |
|
|
|
t.Error("Session time is too low", time.Since(respSession.Time)) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
}) |
|
|
|
|
|
|
|
t.Run("Login", func(t *testing.T) { |
|
|
|
resp, err := http.PostForm(server.URL+"/auth/login", form) |
|
|
|
if err != nil { |
|
|
|
t.Error("Request:", err) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
if resp.StatusCode != 200 { |
|
|
|
t.Error("Expected 200, got", resp.Status) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
respSession := Session{} |
|
|
|
json.NewDecoder(resp.Body).Decode(&respSession) |
|
|
|
|
|
|
|
if respSession.UserID == "" { |
|
|
|
t.Errorf("No user ID in session") |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
}) |
|
|
|
|
|
|
|
t.Run("Login_Fail", func(t *testing.T) { |
|
|
|
resp, err := http.PostForm(server.URL+"/auth/login", form3) |
|
|
|
if err != nil { |
|
|
|
t.Error("Request:", err) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
if resp.StatusCode != 401 { |
|
|
|
t.Error("Expected 401, got", resp.Status) |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
|
|
|
|
respSession := Session{} |
|
|
|
json.NewDecoder(resp.Body).Decode(&respSession) |
|
|
|
|
|
|
|
if respSession.UserID != "" { |
|
|
|
t.Errorf("A user ID in supposedly empty session") |
|
|
|
t.Fail() |
|
|
|
} |
|
|
|
}) |
|
|
|
} |