package Auth import ( "fmt" "math/rand" "net/http" "net/http/httptest" "os" "path" "runtime" "strings" "testing" "time" "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database" "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models" "github.com/gorilla/mux" ) var ( r *mux.Router letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") ) func init() { // Fix working directory for tests _, filename, _, _ := runtime.Caller(0) dir := path.Join(path.Dir(filename), "..") err := os.Chdir(dir) if err != nil { panic(err) } Database.InitTest() r = mux.NewRouter() } func randString(n int) string { b := make([]rune, n) for i := range b { b[i] = letterRunes[rand.Intn(len(letterRunes))] } return string(b) } func createTestUser(random bool) (Models.User, error) { now := time.Now() email := "email@email.com" if random { email = fmt.Sprintf("%s@email.com", randString(16)) } password, err := HashPassword("password") if err != nil { return Models.User{}, err } userData := Models.User{ Email: email, Password: password, LastLogin: &now, FirstName: "Hugh", LastName: "Mann", } err = Database.CreateUser(&userData) return userData, err } func Test_Login(t *testing.T) { t.Log("Testing Login...") r.HandleFunc("/admin/login", Login).Methods("POST") ts := httptest.NewServer(r) defer ts.Close() userData, err := createTestUser(true) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) t.FailNow() } postJson := ` { "email": "%s", "password": "password" } ` postJson = fmt.Sprintf(postJson, userData.Email) res, err := http.Post(ts.URL+"/admin/login", "application/json", strings.NewReader(postJson)) if err != nil { t.Errorf("Expected nil, recieved %s", err.Error()) return } if res.StatusCode != http.StatusOK { t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode) return } if len(res.Cookies()) != 1 { t.Errorf("Expected cookies len 1, recieved %d", len(res.Cookies())) return } }