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.

132 lines
2.6 KiB

package Api
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"path"
"runtime"
"strings"
"testing"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
"github.com/gorilla/mux"
"gorm.io/gorm"
)
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)
}
log.SetOutput(ioutil.Discard)
Database.Init()
r = mux.NewRouter()
}
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func RandStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func Test_getUsers(t *testing.T) {
t.Log("Testing getUsers...")
r.HandleFunc("/user", getUsers).Methods("GET")
ts := httptest.NewServer(r)
defer ts.Close()
var err error
for i := 0; i < 20; i++ {
userData := Models.User{
Email: fmt.Sprintf(
"%s@email.com",
RandStringRunes(16),
),
Password: "password",
ConfirmPassword: "password",
}
err = Database.CreateUser(&userData)
if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error())
}
defer Database.DB.
Session(&gorm.Session{FullSaveAssociations: true}).
Unscoped().
Delete(&userData)
}
res, err := http.Get(ts.URL + "/user?page=1&pageSize=10")
if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error())
}
if res.StatusCode != http.StatusOK {
t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
}
getUsersData := new([]Models.User)
err = json.NewDecoder(res.Body).Decode(getUsersData)
if err != nil {
t.Errorf("Expected nil, recieved %s", err.Error())
}
if len(*getUsersData) != 10 {
t.Errorf("Expected 10, recieved %d", len(*getUsersData))
}
}
func Test_createUser(t *testing.T) {
t.Log("Testing createUser...")
r.HandleFunc("/user", createUser).Methods("POST")
ts := httptest.NewServer(r)
defer ts.Close()
postJson := `
{
"email": "email@email.com",
"password": "password",
"confirm_password": "password",
"first_name": "Hugh",
"last_name": "Mann"
}
`
res, err := http.Post(ts.URL+"/user", "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
}
Database.DB.Model(Models.User{}).
Select("count(*) > 0").
Where("email = ?", "email@email.com").
Delete(Models.User{})
}