user_handler_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. Clusters: []models.ClusterConfig{
  150. models.ClusterConfig{
  151. Name: "cluster-test",
  152. Server: "https://localhost",
  153. Context: "context-test",
  154. User: "test-admin",
  155. },
  156. },
  157. RawKubeConfig: []byte("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"),
  158. })
  159. },
  160. msg: "Read user successful",
  161. method: "GET",
  162. endpoint: "/api/users/1",
  163. body: "",
  164. expStatus: http.StatusOK,
  165. expBody: `{"id":1,"email":"belanger@getporter.dev","clusters":[{"name":"cluster-test","server":"https://localhost","context":"context-test","user":"test-admin"}],"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"}`,
  166. canQuery: true,
  167. },
  168. userTest{
  169. init: func(repo *repository.Repository) {
  170. repo.User.CreateUser(&models.User{
  171. Email: "belanger@getporter.dev",
  172. Password: "hello",
  173. })
  174. },
  175. msg: "Read user bad id field",
  176. method: "GET",
  177. endpoint: "/api/users/aldkfjas",
  178. body: "",
  179. expStatus: http.StatusBadRequest,
  180. expBody: `{"code":600,"errors":["could not process request"]}`,
  181. canQuery: true,
  182. },
  183. userTest{
  184. init: func(repo *repository.Repository) {
  185. repo.User.CreateUser(&models.User{
  186. Email: "belanger@getporter.dev",
  187. Password: "hello",
  188. })
  189. },
  190. msg: "Read user not found",
  191. method: "GET",
  192. endpoint: "/api/users/2",
  193. body: "",
  194. expStatus: http.StatusNotFound,
  195. expBody: `{"code":602,"errors":["could not find requested object"]}`,
  196. canQuery: true,
  197. },
  198. }
  199. func TestHandleReadUser(t *testing.T) {
  200. for _, c := range readUserTests {
  201. // create a mock API
  202. api, repo := initApi(c.canQuery)
  203. r := router.New(api)
  204. if c.init != nil {
  205. c.init(repo)
  206. }
  207. req, err := http.NewRequest(
  208. c.method,
  209. c.endpoint,
  210. strings.NewReader(c.body),
  211. )
  212. if err != nil {
  213. t.Fatal(err)
  214. }
  215. rr := httptest.NewRecorder()
  216. r.ServeHTTP(rr, req)
  217. if status := rr.Code; status != c.expStatus {
  218. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  219. c.msg, status, c.expStatus)
  220. }
  221. if status := rr.Code; status == 200 {
  222. // if status is expected to be 200, parse the body for UserExternal
  223. gotBody := &models.UserExternal{}
  224. expBody := &models.UserExternal{}
  225. json.Unmarshal(rr.Body.Bytes(), gotBody)
  226. json.Unmarshal([]byte(c.expBody), expBody)
  227. if !reflect.DeepEqual(gotBody, expBody) {
  228. t.Errorf("%s, handler returned wrong body: got %v want %v",
  229. c.msg, gotBody, expBody)
  230. }
  231. } else {
  232. // if status is expected to not be 200, look for error
  233. if body := rr.Body.String(); body != c.expBody {
  234. t.Errorf("%s, handler returned wrong body: got %v want %v",
  235. c.msg, body, c.expBody)
  236. }
  237. }
  238. }
  239. }
  240. var updateUserTests = []userTest{
  241. userTest{
  242. init: func(repo *repository.Repository) {
  243. repo.User.CreateUser(&models.User{
  244. Email: "belanger@getporter.dev",
  245. Password: "hello",
  246. })
  247. },
  248. msg: "Update user successful",
  249. method: "PUT",
  250. endpoint: "/api/users/1",
  251. 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":[]}`,
  252. expStatus: http.StatusNoContent,
  253. expBody: "",
  254. canQuery: true,
  255. validate: func(r *chi.Mux, t *testing.T) {
  256. req, err := http.NewRequest(
  257. "GET",
  258. "/api/users/1",
  259. strings.NewReader(""),
  260. )
  261. if err != nil {
  262. t.Fatal(err)
  263. }
  264. rr := httptest.NewRecorder()
  265. r.ServeHTTP(rr, req)
  266. gotBody := &models.UserExternal{}
  267. expBody := &models.UserExternal{}
  268. json.Unmarshal(rr.Body.Bytes(), gotBody)
  269. 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)
  270. if !reflect.DeepEqual(gotBody, expBody) {
  271. t.Errorf("%s, handler returned wrong body: got %v want %v",
  272. "validator failed", gotBody, expBody)
  273. }
  274. },
  275. },
  276. userTest{
  277. init: func(repo *repository.Repository) {
  278. repo.User.CreateUser(&models.User{
  279. Email: "belanger@getporter.dev",
  280. Password: "hello",
  281. })
  282. },
  283. msg: "Update user invalid id",
  284. method: "PUT",
  285. endpoint: "/api/users/alsdfjk",
  286. 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":[]}`,
  287. expStatus: http.StatusBadRequest,
  288. expBody: `{"code":600,"errors":["could not process request"]}`,
  289. canQuery: true,
  290. },
  291. }
  292. func TestHandleUpdateUser(t *testing.T) {
  293. for _, c := range updateUserTests {
  294. // create a mock API
  295. api, repo := initApi(c.canQuery)
  296. r := router.New(api)
  297. if c.init != nil {
  298. c.init(repo)
  299. }
  300. req, err := http.NewRequest(
  301. c.method,
  302. c.endpoint,
  303. strings.NewReader(c.body),
  304. )
  305. if err != nil {
  306. t.Fatal(err)
  307. }
  308. rr := httptest.NewRecorder()
  309. r.ServeHTTP(rr, req)
  310. if status := rr.Code; status != c.expStatus {
  311. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  312. c.msg, status, c.expStatus)
  313. }
  314. if body := rr.Body.String(); body != c.expBody {
  315. t.Errorf("%s, handler returned wrong body: got %v want %v",
  316. c.msg, body, c.expBody)
  317. }
  318. if c.validate != nil {
  319. c.validate(r, t)
  320. }
  321. }
  322. }
  323. var deleteUserTests = []userTest{
  324. userTest{
  325. init: func(repo *repository.Repository) {
  326. repo.User.CreateUser(&models.User{
  327. Email: "belanger@getporter.dev",
  328. Password: "hello",
  329. })
  330. },
  331. msg: "Delete user successful",
  332. method: "DELETE",
  333. endpoint: "/api/users/1",
  334. body: `{"password":"hello"}`,
  335. expStatus: http.StatusNoContent,
  336. expBody: "",
  337. canQuery: true,
  338. validate: func(r *chi.Mux, t *testing.T) {
  339. req, err := http.NewRequest(
  340. "GET",
  341. "/api/users/1",
  342. strings.NewReader(""),
  343. )
  344. if err != nil {
  345. t.Fatal(err)
  346. }
  347. rr := httptest.NewRecorder()
  348. r.ServeHTTP(rr, req)
  349. gotBody := &models.UserExternal{}
  350. expBody := &models.UserExternal{}
  351. if status := rr.Code; status != 404 {
  352. t.Errorf("DELETE user validation, handler returned wrong status code: got %v want %v",
  353. status, 404)
  354. }
  355. json.Unmarshal(rr.Body.Bytes(), gotBody)
  356. json.Unmarshal([]byte(`{"code":602,"errors":["could not find requested object"]}`), expBody)
  357. if !reflect.DeepEqual(gotBody, expBody) {
  358. t.Errorf("%s, handler returned wrong body: got %v want %v",
  359. "validator failed", gotBody, expBody)
  360. }
  361. },
  362. },
  363. }
  364. func TestHandleDeleteUser(t *testing.T) {
  365. for _, c := range deleteUserTests {
  366. // create a mock API
  367. api, repo := initApi(c.canQuery)
  368. r := router.New(api)
  369. if c.init != nil {
  370. c.init(repo)
  371. }
  372. req, err := http.NewRequest(
  373. c.method,
  374. c.endpoint,
  375. strings.NewReader(c.body),
  376. )
  377. if err != nil {
  378. t.Fatal(err)
  379. }
  380. rr := httptest.NewRecorder()
  381. r.ServeHTTP(rr, req)
  382. if status := rr.Code; status != c.expStatus {
  383. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  384. c.msg, status, c.expStatus)
  385. }
  386. if body := rr.Body.String(); body != c.expBody {
  387. t.Errorf("%s, handler returned wrong body: got %v want %v",
  388. c.msg, body, c.expBody)
  389. }
  390. if c.validate != nil {
  391. c.validate(r, t)
  392. }
  393. }
  394. }