103 lines
2.2 KiB
Go
103 lines
2.2 KiB
Go
package controllers_test
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/url"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.1248.nz/1248/Otfe/controllers"
|
|
"git.1248.nz/1248/Otfe/misc/b64"
|
|
"git.1248.nz/1248/Otfe/misc/helpers"
|
|
"git.1248.nz/1248/Otfe/models"
|
|
)
|
|
|
|
func TestSessionNew(t *testing.T) {
|
|
var s controllers.Session
|
|
handler := http.HandlerFunc(s.New)
|
|
req, err := http.NewRequest("GET", "/login", nil)
|
|
w := httptest.NewRecorder()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
handler(w, req)
|
|
body := w.Body.String()
|
|
if !strings.Contains(body, "<title>Login</title>") {
|
|
t.Fail()
|
|
}
|
|
}
|
|
|
|
func TestSessionCreate(t *testing.T) {
|
|
//Create test user
|
|
|
|
var s controllers.Session
|
|
handler := http.HandlerFunc(s.Create)
|
|
req, w := setup(t, "POST", "/login")
|
|
|
|
addTofForm(req, "email=test", "password=test")
|
|
handler(w, req)
|
|
|
|
errorMessage := getCookie("error", w.Header()["Set-Cookie"])
|
|
t.Log(errorMessage)
|
|
t.Log(b64.Decode(errorMessage))
|
|
|
|
header := w.Header()
|
|
sessionid := getCookie("session", header["Set-Cookie"])
|
|
var session models.Session
|
|
if session.Read(sessionid) != nil {
|
|
t.Fatal("Could not find session")
|
|
}
|
|
|
|
}
|
|
|
|
/*func testloginFail(t *testing.T) {
|
|
|
|
}*/
|
|
|
|
func setup(t *testing.T, method string, url string) (*http.Request, *httptest.ResponseRecorder) {
|
|
req, err := http.NewRequest("POST", "/login", nil)
|
|
w := httptest.NewRecorder()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return req, w
|
|
|
|
}
|
|
|
|
func createUser(t *testing.T, email string, password string) models.User {
|
|
|
|
password, err := helpers.HashPassword(password)
|
|
if err != nil {
|
|
t.Fatal("Failed to create password")
|
|
}
|
|
user := models.User{Email: email, Password: password}
|
|
if user.Create() != nil {
|
|
t.Fatal("failed to create user")
|
|
}
|
|
|
|
return user
|
|
}
|
|
|
|
func getCookie(name string, cookies []string) string {
|
|
for _, cookie := range cookies {
|
|
a := strings.Split(cookie, "=")
|
|
if a[0] == name {
|
|
return a[1]
|
|
|
|
}
|
|
|
|
}
|
|
return "Cookie not found"
|
|
}
|
|
|
|
func addTofForm(r *http.Request, values ...string) {
|
|
form, _ := url.ParseQuery(r.URL.RawQuery)
|
|
for _, value := range values {
|
|
v := strings.Split(value, "=")
|
|
form.Add(v[0], v[1])
|
|
}
|
|
r.URL.RawQuery = form.Encode()
|
|
r.Form.Encode()
|
|
}
|