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.

372 lines
7.3 KiB

  1. package Api
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "math/rand"
  7. "net/http"
  8. "net/http/httptest"
  9. "os"
  10. "path"
  11. "runtime"
  12. "strings"
  13. "testing"
  14. "time"
  15. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Api/Auth"
  16. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
  17. "git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
  18. "github.com/gorilla/mux"
  19. )
  20. func init() {
  21. // Fix working directory for tests
  22. _, filename, _, _ := runtime.Caller(0)
  23. dir := path.Join(path.Dir(filename), "..")
  24. err := os.Chdir(dir)
  25. if err != nil {
  26. panic(err)
  27. }
  28. Database.InitTest()
  29. r = mux.NewRouter()
  30. }
  31. var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
  32. func randString(n int) string {
  33. b := make([]rune, n)
  34. for i := range b {
  35. b[i] = letterRunes[rand.Intn(len(letterRunes))]
  36. }
  37. return string(b)
  38. }
  39. func createTestUser(random bool) (Models.User, error) {
  40. now := time.Now()
  41. email := "email@email.com"
  42. if random {
  43. email = fmt.Sprintf("%s@email.com", randString(16))
  44. }
  45. password, err := Auth.HashPassword("password")
  46. if err != nil {
  47. return Models.User{}, err
  48. }
  49. userData := Models.User{
  50. Email: email,
  51. Password: password,
  52. LastLogin: &now,
  53. FirstName: "Hugh",
  54. LastName: "Mann",
  55. }
  56. err = Database.CreateUser(&userData)
  57. return userData, err
  58. }
  59. func login() (*http.Cookie, Models.User, error) {
  60. var (
  61. c *http.Cookie
  62. u Models.User
  63. )
  64. r.HandleFunc("/admin/login", Auth.Login).Methods("POST")
  65. ts := httptest.NewServer(r)
  66. defer ts.Close()
  67. u, err := createTestUser(true)
  68. if err != nil {
  69. return c, u, err
  70. }
  71. postJson := `
  72. {
  73. "email": "%s",
  74. "password": "password"
  75. }
  76. `
  77. postJson = fmt.Sprintf(postJson, u.Email)
  78. res, err := http.Post(ts.URL+"/admin/login", "application/json", strings.NewReader(postJson))
  79. if err != nil {
  80. return c, u, err
  81. }
  82. if res.StatusCode != http.StatusOK {
  83. return c, u, errors.New("Invalid res.StatusCode")
  84. }
  85. if len(res.Cookies()) != 1 {
  86. return c, u, errors.New("Invalid cookies length")
  87. }
  88. return res.Cookies()[0], u, nil
  89. }
  90. func Test_getUser(t *testing.T) {
  91. t.Log("Testing getUser...")
  92. r.HandleFunc("/user/{userID}", getUser).Methods("GET")
  93. ts := httptest.NewServer(r)
  94. defer ts.Close()
  95. c, u, err := login()
  96. if err != nil {
  97. t.Errorf("Expected nil, recieved %s", err.Error())
  98. t.FailNow()
  99. }
  100. req, err := http.NewRequest("GET", fmt.Sprintf(
  101. "%s/user/%s",
  102. ts.URL,
  103. u.ID,
  104. ), nil)
  105. if err != nil {
  106. t.Errorf("Expected nil, recieved %s", err.Error())
  107. t.FailNow()
  108. }
  109. req.AddCookie(c)
  110. res, err := http.DefaultClient.Do(req)
  111. if err != nil {
  112. t.Errorf("Expected nil, recieved %s", err.Error())
  113. t.FailNow()
  114. }
  115. if res.StatusCode != http.StatusOK {
  116. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  117. t.FailNow()
  118. }
  119. getUserData := new(Models.User)
  120. err = json.NewDecoder(res.Body).Decode(getUserData)
  121. if err != nil {
  122. t.Errorf("Expected nil, recieved %s", err.Error())
  123. t.FailNow()
  124. }
  125. if getUserData.Email != u.Email {
  126. t.Errorf("Expected email \"%s\", recieved %s", u.Email, getUserData.Email)
  127. t.FailNow()
  128. }
  129. if getUserData.FirstName != u.FirstName {
  130. t.Errorf("Expected email \"%s\", recieved %s", u.FirstName, getUserData.FirstName)
  131. t.FailNow()
  132. }
  133. if getUserData.LastName != u.LastName {
  134. t.Errorf("Expected email \"%s\", recieved %s", u.LastName, getUserData.LastName)
  135. t.FailNow()
  136. }
  137. }
  138. func Test_getUsers(t *testing.T) {
  139. t.Log("Testing getUsers...")
  140. r.HandleFunc("/user", getUsers).Methods("GET")
  141. ts := httptest.NewServer(r)
  142. defer ts.Close()
  143. c, _, err := login()
  144. if err != nil {
  145. t.Errorf("Expected nil, recieved %s", err.Error())
  146. t.FailNow()
  147. }
  148. for i := 0; i < 20; i++ {
  149. createTestUser(true)
  150. }
  151. req, err := http.NewRequest("GET", ts.URL+"/user?page=0&pageSize=10", nil)
  152. if err != nil {
  153. t.Errorf("Expected nil, recieved %s", err.Error())
  154. t.FailNow()
  155. }
  156. req.AddCookie(c)
  157. res, err := http.DefaultClient.Do(req)
  158. if err != nil {
  159. t.Errorf("Expected nil, recieved %s", err.Error())
  160. t.FailNow()
  161. }
  162. if res.StatusCode != http.StatusOK {
  163. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  164. t.FailNow()
  165. }
  166. getUsersData := new([]Models.User)
  167. err = json.NewDecoder(res.Body).Decode(getUsersData)
  168. if err != nil {
  169. t.Errorf("Expected nil, recieved %s", err.Error())
  170. t.FailNow()
  171. }
  172. if len(*getUsersData) != 10 {
  173. t.Errorf("Expected 10, recieved %d", len(*getUsersData))
  174. t.FailNow()
  175. }
  176. }
  177. func Test_createUser(t *testing.T) {
  178. t.Log("Testing createUser...")
  179. r.HandleFunc("/user", createUser).Methods("POST")
  180. ts := httptest.NewServer(r)
  181. defer ts.Close()
  182. email := fmt.Sprintf("%s@email.com", randString(16))
  183. postJson := `
  184. {
  185. "email": "%s",
  186. "password": "password",
  187. "confirm_password": "password",
  188. "first_name": "Hugh",
  189. "last_name": "Mann"
  190. }
  191. `
  192. postJson = fmt.Sprintf(postJson, email)
  193. res, err := http.Post(ts.URL+"/user", "application/json", strings.NewReader(postJson))
  194. if err != nil {
  195. t.Errorf("Expected nil, recieved %s", err.Error())
  196. return
  197. }
  198. if res.StatusCode != http.StatusOK {
  199. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  200. return
  201. }
  202. }
  203. func Test_updateUser(t *testing.T) {
  204. t.Log("Testing updateUser...")
  205. r.HandleFunc("/user/{userID}", updateUser).Methods("PUT")
  206. ts := httptest.NewServer(r)
  207. defer ts.Close()
  208. c, u, err := login()
  209. if err != nil {
  210. t.Errorf("Expected nil, recieved %s", err.Error())
  211. t.FailNow()
  212. }
  213. email := fmt.Sprintf("%s@email.com", randString(16))
  214. postJson := `
  215. {
  216. "email": "%s",
  217. "first_name": "first",
  218. "last_name": "last"
  219. }
  220. `
  221. postJson = fmt.Sprintf(postJson, email)
  222. req, err := http.NewRequest("PUT", fmt.Sprintf(
  223. "%s/user/%s",
  224. ts.URL,
  225. u.ID,
  226. ), strings.NewReader(postJson))
  227. if err != nil {
  228. t.Errorf("Expected nil, recieved %s", err.Error())
  229. }
  230. req.AddCookie(c)
  231. // Fetch Request
  232. res, err := http.DefaultClient.Do(req)
  233. if err != nil {
  234. t.Errorf("Expected nil, recieved %s", err.Error())
  235. }
  236. defer res.Body.Close()
  237. if res.StatusCode != http.StatusOK {
  238. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  239. }
  240. updateUserData := new(Models.User)
  241. err = json.NewDecoder(res.Body).Decode(updateUserData)
  242. if err != nil {
  243. t.Errorf("Expected nil, recieved %s", err.Error())
  244. }
  245. if updateUserData.Email != email {
  246. t.Errorf("Expected email \"%s\", recieved %s", email, updateUserData.Email)
  247. }
  248. if updateUserData.FirstName != "first" {
  249. t.Errorf("Expected FirstName \"first\", recieved %s", updateUserData.FirstName)
  250. }
  251. if updateUserData.LastName != "last" {
  252. t.Errorf("Expected LastName \"last\", recieved %s", updateUserData.LastName)
  253. }
  254. }
  255. func Test_deleteUser(t *testing.T) {
  256. t.Log("Testing deleteUser...")
  257. r.HandleFunc("/user/{userID}", deleteUser).Methods("DELETE")
  258. ts := httptest.NewServer(r)
  259. defer ts.Close()
  260. c, _, err := login()
  261. if err != nil {
  262. t.Errorf("Expected nil, recieved %s", err.Error())
  263. t.FailNow()
  264. }
  265. userData, err := createTestUser(true)
  266. if err != nil {
  267. t.Errorf("Expected nil, recieved %s", err.Error())
  268. t.FailNow()
  269. }
  270. req, err := http.NewRequest("DELETE", fmt.Sprintf(
  271. "%s/user/%s",
  272. ts.URL,
  273. userData.ID,
  274. ), nil)
  275. if err != nil {
  276. t.Errorf("Expected nil, recieved %s", err.Error())
  277. }
  278. req.AddCookie(c)
  279. // Fetch Request
  280. res, err := http.DefaultClient.Do(req)
  281. if err != nil {
  282. t.Errorf("Expected nil, recieved %s", err.Error())
  283. return
  284. }
  285. defer res.Body.Close()
  286. if res.StatusCode != http.StatusOK {
  287. t.Errorf("Expected %d, recieved %d", http.StatusOK, res.StatusCode)
  288. }
  289. }