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
110 lines
2.2 KiB
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type handlerStruct struct{}
|
|
|
|
func (hs *handlerStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
req.ParseForm() // Router does this in non-tests
|
|
|
|
if strings.HasPrefix(req.URL.Path, "/auth") {
|
|
Handler.Handle("/auth", w, req, nil)
|
|
return
|
|
}
|
|
}
|
|
|
|
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()
|
|
}
|
|
})
|
|
}
|