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.

296 lines
6.0 KiB

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