user_handler_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. package api_test
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "reflect"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/go-chi/chi"
  11. "github.com/porter-dev/porter/internal/config"
  12. "github.com/porter-dev/porter/internal/models"
  13. "github.com/porter-dev/porter/internal/repository"
  14. "github.com/porter-dev/porter/internal/repository/test"
  15. "github.com/porter-dev/porter/server/api"
  16. "github.com/porter-dev/porter/server/router"
  17. lr "github.com/porter-dev/porter/internal/logger"
  18. vr "github.com/porter-dev/porter/internal/validator"
  19. )
  20. func initApi(canQuery bool) (*api.App, *repository.Repository) {
  21. appConf := config.Conf{
  22. Debug: true,
  23. Server: config.ServerConf{
  24. Port: 8080,
  25. TimeoutRead: time.Second * 5,
  26. TimeoutWrite: time.Second * 10,
  27. TimeoutIdle: time.Second * 15,
  28. },
  29. // unimportant
  30. Db: config.DBConf{},
  31. }
  32. logger := lr.NewConsole(appConf.Debug)
  33. validator := vr.New()
  34. repo := test.NewRepository(canQuery)
  35. return api.New(logger, repo, validator), repo
  36. }
  37. type userTest struct {
  38. init func(repo *repository.Repository)
  39. msg,
  40. method,
  41. endpoint,
  42. body string
  43. expStatus int
  44. expBody string
  45. canQuery bool
  46. validate func(r *chi.Mux, t *testing.T)
  47. }
  48. var createUserTests = []userTest{
  49. userTest{
  50. msg: "Create user",
  51. method: "POST",
  52. endpoint: "/api/users",
  53. body: `{
  54. "email": "belanger@getporter.dev",
  55. "password": "hello"
  56. }`,
  57. expStatus: http.StatusCreated,
  58. expBody: "",
  59. canQuery: true,
  60. },
  61. userTest{
  62. msg: "Create user invalid email",
  63. method: "POST",
  64. endpoint: "/api/users",
  65. body: `{
  66. "email": "notanemail",
  67. "password": "hello"
  68. }`,
  69. expStatus: http.StatusUnprocessableEntity,
  70. expBody: `{"code":601,"errors":["email validation failed"]}`,
  71. canQuery: true,
  72. },
  73. userTest{
  74. msg: "Create user missing field",
  75. method: "POST",
  76. endpoint: "/api/users",
  77. body: `{
  78. "password": "hello"
  79. }`,
  80. expStatus: http.StatusUnprocessableEntity,
  81. expBody: `{"code":601,"errors":["required validation failed"]}`,
  82. canQuery: true,
  83. },
  84. userTest{
  85. msg: "Create user cannot write to db",
  86. method: "POST",
  87. endpoint: "/api/users",
  88. body: `{
  89. "email": "belanger@getporter.dev",
  90. "password": "hello"
  91. }`,
  92. expStatus: http.StatusInternalServerError,
  93. expBody: `{"code":500,"errors":["Could not read from database"]}`,
  94. canQuery: false,
  95. },
  96. userTest{
  97. init: func(repo *repository.Repository) {
  98. repo.User.CreateUser(&models.User{
  99. Email: "belanger@getporter.dev",
  100. Password: "hello",
  101. })
  102. },
  103. msg: "Create user same email",
  104. method: "POST",
  105. endpoint: "/api/users",
  106. body: `{
  107. "email": "belanger@getporter.dev",
  108. "password": "hello"
  109. }`,
  110. expStatus: http.StatusUnprocessableEntity,
  111. expBody: `{"code":601,"errors":["Email already taken"]}`,
  112. canQuery: true,
  113. },
  114. }
  115. func TestHandleCreateUser(t *testing.T) {
  116. for _, c := range createUserTests {
  117. // create a mock API
  118. api, repo := initApi(c.canQuery)
  119. r := router.New(api)
  120. if c.init != nil {
  121. c.init(repo)
  122. }
  123. req, err := http.NewRequest(
  124. c.method,
  125. c.endpoint,
  126. strings.NewReader(c.body),
  127. )
  128. if err != nil {
  129. t.Fatal(err)
  130. }
  131. rr := httptest.NewRecorder()
  132. r.ServeHTTP(rr, req)
  133. if status := rr.Code; status != c.expStatus {
  134. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  135. c.msg, status, c.expStatus)
  136. }
  137. if body := rr.Body.String(); body != c.expBody {
  138. t.Errorf("%s, handler returned wrong body: got %v want %v",
  139. c.msg, body, c.expBody)
  140. }
  141. }
  142. }
  143. var readUserTests = []userTest{
  144. userTest{
  145. init: func(repo *repository.Repository) {
  146. repo.User.CreateUser(&models.User{
  147. Email: "belanger@getporter.dev",
  148. Password: "hello",
  149. })
  150. },
  151. msg: "Read user successful",
  152. method: "GET",
  153. endpoint: "/api/users/1",
  154. body: "",
  155. expStatus: http.StatusOK,
  156. expBody: `{"id":1,"email":"belanger@getporter.dev","clusters":[],"rawKubeConfig":""}`,
  157. canQuery: true,
  158. },
  159. userTest{
  160. init: func(repo *repository.Repository) {
  161. repo.User.CreateUser(&models.User{
  162. Email: "belanger@getporter.dev",
  163. Password: "hello",
  164. })
  165. },
  166. msg: "Read user bad id field",
  167. method: "GET",
  168. endpoint: "/api/users/aldkfjas",
  169. body: "",
  170. expStatus: http.StatusBadRequest,
  171. expBody: `{"code":600,"errors":["Could not process JSON body"]}`,
  172. canQuery: true,
  173. },
  174. userTest{
  175. init: func(repo *repository.Repository) {
  176. repo.User.CreateUser(&models.User{
  177. Email: "belanger@getporter.dev",
  178. Password: "hello",
  179. })
  180. },
  181. msg: "Read user not found",
  182. method: "GET",
  183. endpoint: "/api/users/2",
  184. body: "",
  185. expStatus: http.StatusNotFound,
  186. expBody: `{"code":603,"errors":["Could not find requested object"]}`,
  187. canQuery: true,
  188. },
  189. }
  190. func TestHandleReadUser(t *testing.T) {
  191. for _, c := range readUserTests {
  192. // create a mock API
  193. api, repo := initApi(c.canQuery)
  194. r := router.New(api)
  195. if c.init != nil {
  196. c.init(repo)
  197. }
  198. req, err := http.NewRequest(
  199. c.method,
  200. c.endpoint,
  201. strings.NewReader(c.body),
  202. )
  203. if err != nil {
  204. t.Fatal(err)
  205. }
  206. rr := httptest.NewRecorder()
  207. r.ServeHTTP(rr, req)
  208. if status := rr.Code; status != c.expStatus {
  209. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  210. c.msg, status, c.expStatus)
  211. }
  212. if status := rr.Code; status == 200 {
  213. // if status is expected to be 200, parse the body for UserExternal
  214. gotBody := &models.UserExternal{}
  215. expBody := &models.UserExternal{}
  216. json.Unmarshal(rr.Body.Bytes(), gotBody)
  217. json.Unmarshal([]byte(c.expBody), expBody)
  218. if !reflect.DeepEqual(gotBody, expBody) {
  219. t.Errorf("%s, handler returned wrong body: got %v want %v",
  220. c.msg, gotBody, expBody)
  221. }
  222. } else {
  223. // if status is expected to not be 200, look for error
  224. if body := rr.Body.String(); body != c.expBody {
  225. t.Errorf("%s, handler returned wrong body: got %v want %v",
  226. c.msg, body, c.expBody)
  227. }
  228. }
  229. }
  230. }
  231. var updateUserTests = []userTest{
  232. userTest{
  233. init: func(repo *repository.Repository) {
  234. repo.User.CreateUser(&models.User{
  235. Email: "belanger@getporter.dev",
  236. Password: "hello",
  237. })
  238. },
  239. msg: "Update user successful",
  240. method: "PUT",
  241. endpoint: "/api/users/1",
  242. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin", "allowedClusters":[]}`,
  243. expStatus: http.StatusAccepted,
  244. expBody: "",
  245. canQuery: true,
  246. validate: func(r *chi.Mux, t *testing.T) {
  247. req, err := http.NewRequest(
  248. "GET",
  249. "/api/users/1",
  250. strings.NewReader(""),
  251. )
  252. if err != nil {
  253. t.Fatal(err)
  254. }
  255. rr := httptest.NewRecorder()
  256. r.ServeHTTP(rr, req)
  257. gotBody := &models.UserExternal{}
  258. expBody := &models.UserExternal{}
  259. json.Unmarshal(rr.Body.Bytes(), gotBody)
  260. json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev","clusters":[],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: default\nclusters:\n- cluster:\n server: https://localhost\n name: cluster-test\ncontexts:\n- context:\n cluster: cluster-test\n user: test-admin\n name: context-test\nusers:\n- name: test-admin"}`), expBody)
  261. if !reflect.DeepEqual(gotBody, expBody) {
  262. t.Errorf("%s, handler returned wrong body: got %v want %v",
  263. "validator failed", gotBody, expBody)
  264. }
  265. },
  266. },
  267. }
  268. func TestHandleUpdateUser(t *testing.T) {
  269. for _, c := range updateUserTests {
  270. // create a mock API
  271. api, repo := initApi(c.canQuery)
  272. r := router.New(api)
  273. if c.init != nil {
  274. c.init(repo)
  275. }
  276. req, err := http.NewRequest(
  277. c.method,
  278. c.endpoint,
  279. strings.NewReader(c.body),
  280. )
  281. if err != nil {
  282. t.Fatal(err)
  283. }
  284. rr := httptest.NewRecorder()
  285. r.ServeHTTP(rr, req)
  286. if status := rr.Code; status != c.expStatus {
  287. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  288. c.msg, status, c.expStatus)
  289. }
  290. if body := rr.Body.String(); body != c.expBody {
  291. t.Errorf("%s, handler returned wrong body: got %v want %v",
  292. c.msg, body, c.expBody)
  293. }
  294. c.validate(r, t)
  295. }
  296. }