user_handler_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753
  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. sessionstore "github.com/porter-dev/porter/internal/auth"
  18. lr "github.com/porter-dev/porter/internal/logger"
  19. vr "github.com/porter-dev/porter/internal/validator"
  20. )
  21. type tester struct {
  22. app *api.App
  23. repo *repository.Repository
  24. store *sessionstore.PGStore
  25. router *chi.Mux
  26. req *http.Request
  27. rr *httptest.ResponseRecorder
  28. cookie *http.Cookie
  29. }
  30. type userTest struct {
  31. initializers []func(t *tester)
  32. msg string
  33. method string
  34. endpoint string
  35. body string
  36. expStatus int
  37. expBody string
  38. useCookie bool
  39. validators []func(c *userTest, tester *tester, t *testing.T)
  40. }
  41. func (t *tester) execute() {
  42. t.router.ServeHTTP(t.rr, t.req)
  43. }
  44. func (t *tester) reset() {
  45. t.rr = httptest.NewRecorder()
  46. t.req = nil
  47. }
  48. func (t *tester) createUserSession(email string, pw string) {
  49. req, _ := http.NewRequest(
  50. "POST",
  51. "/api/users",
  52. strings.NewReader(`{"email":"`+email+`","password":"`+pw+`"}`),
  53. )
  54. t.req = req
  55. t.execute()
  56. if cookies := t.rr.Result().Cookies(); len(cookies) > 0 {
  57. t.cookie = cookies[0]
  58. }
  59. t.reset()
  60. }
  61. func initUserDefault(tester *tester) {
  62. tester.createUserSession("belanger@getporter.dev", "hello")
  63. }
  64. func initUserWithContexts(tester *tester) {
  65. initUserDefault(tester)
  66. user, _ := tester.repo.User.ReadUserByEmail("belanger@getporter.dev")
  67. user.Contexts = []string{"context-test"}
  68. user.RawKubeConfig = []byte("apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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")
  69. tester.repo.User.UpdateUser(user)
  70. }
  71. func newTester(canQuery bool) *tester {
  72. appConf := config.Conf{
  73. Debug: true,
  74. Server: config.ServerConf{
  75. Port: 8080,
  76. CookieName: "porter",
  77. CookieSecret: []byte("secret"),
  78. TimeoutRead: time.Second * 5,
  79. TimeoutWrite: time.Second * 10,
  80. TimeoutIdle: time.Second * 15,
  81. },
  82. // unimportant here
  83. Db: config.DBConf{},
  84. }
  85. logger := lr.NewConsole(appConf.Debug)
  86. validator := vr.New()
  87. repo := test.NewRepository(canQuery)
  88. store, _ := sessionstore.NewStore(repo, appConf.Server)
  89. app := api.New(logger, repo, validator, store, appConf.Server.CookieName)
  90. r := router.New(app, store, appConf.Server.CookieName)
  91. return &tester{
  92. app: app,
  93. repo: repo,
  94. store: store,
  95. router: r,
  96. req: nil,
  97. rr: httptest.NewRecorder(),
  98. cookie: nil,
  99. }
  100. }
  101. func testUserRequests(t *testing.T, tests []*userTest, canQuery bool) {
  102. for _, c := range tests {
  103. // create a new tester
  104. tester := newTester(canQuery)
  105. // if there's an initializer, call it
  106. for _, init := range c.initializers {
  107. init(tester)
  108. }
  109. req, err := http.NewRequest(
  110. c.method,
  111. c.endpoint,
  112. strings.NewReader(c.body),
  113. )
  114. tester.req = req
  115. if c.useCookie {
  116. req.AddCookie(tester.cookie)
  117. }
  118. if err != nil {
  119. t.Fatal(err)
  120. }
  121. tester.execute()
  122. rr := tester.rr
  123. // first, check that the status matches
  124. if status := rr.Code; status != c.expStatus {
  125. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  126. c.msg, status, c.expStatus)
  127. }
  128. // if there's a validator, call it
  129. for _, validate := range c.validators {
  130. validate(c, tester, t)
  131. }
  132. }
  133. }
  134. var createUserTests = []*userTest{
  135. &userTest{
  136. msg: "Create user",
  137. method: "POST",
  138. endpoint: "/api/users",
  139. body: `{
  140. "email": "belanger@getporter.dev",
  141. "password": "hello"
  142. }`,
  143. expStatus: http.StatusCreated,
  144. expBody: "",
  145. },
  146. &userTest{
  147. msg: "Create user invalid email",
  148. method: "POST",
  149. endpoint: "/api/users",
  150. body: `{
  151. "email": "notanemail",
  152. "password": "hello"
  153. }`,
  154. expStatus: http.StatusUnprocessableEntity,
  155. expBody: `{"code":601,"errors":["email validation failed"]}`,
  156. validators: []func(c *userTest, tester *tester, t *testing.T){
  157. BasicBodyValidator,
  158. },
  159. },
  160. &userTest{
  161. msg: "Create user missing field",
  162. method: "POST",
  163. endpoint: "/api/users",
  164. body: `{
  165. "password": "hello"
  166. }`,
  167. expStatus: http.StatusUnprocessableEntity,
  168. expBody: `{"code":601,"errors":["required validation failed"]}`,
  169. validators: []func(c *userTest, tester *tester, t *testing.T){
  170. BasicBodyValidator,
  171. },
  172. },
  173. &userTest{
  174. initializers: []func(tester *tester){
  175. initUserDefault,
  176. },
  177. msg: "Create user same email",
  178. method: "POST",
  179. endpoint: "/api/users",
  180. body: `{
  181. "email": "belanger@getporter.dev",
  182. "password": "hello"
  183. }`,
  184. expStatus: http.StatusUnprocessableEntity,
  185. expBody: `{"code":601,"errors":["email already taken"]}`,
  186. validators: []func(c *userTest, tester *tester, t *testing.T){
  187. BasicBodyValidator,
  188. },
  189. },
  190. &userTest{
  191. msg: "Create user invalid field type",
  192. method: "POST",
  193. endpoint: "/api/users",
  194. body: `{
  195. "email": "belanger@getporter.dev",
  196. "password": 0
  197. }`,
  198. expStatus: http.StatusBadRequest,
  199. expBody: `{"code":600,"errors":["could not process request"]}`,
  200. validators: []func(c *userTest, tester *tester, t *testing.T){
  201. BasicBodyValidator,
  202. },
  203. },
  204. }
  205. func TestHandleCreateUser(t *testing.T) {
  206. testUserRequests(t, createUserTests, true)
  207. }
  208. var createUserTestsWriteFail = []*userTest{
  209. &userTest{
  210. msg: "Create user db connection down",
  211. method: "POST",
  212. endpoint: "/api/users",
  213. body: `{
  214. "email": "belanger@getporter.dev",
  215. "password": "hello"
  216. }`,
  217. expStatus: http.StatusInternalServerError,
  218. expBody: `{"code":500,"errors":["could not read from database"]}`,
  219. validators: []func(c *userTest, tester *tester, t *testing.T){
  220. BasicBodyValidator,
  221. },
  222. },
  223. }
  224. func TestHandleCreateUserWriteFail(t *testing.T) {
  225. testUserRequests(t, createUserTestsWriteFail, false)
  226. }
  227. var loginUserTests = []*userTest{
  228. &userTest{
  229. initializers: []func(tester *tester){
  230. initUserDefault,
  231. },
  232. msg: "Login user successful",
  233. method: "POST",
  234. endpoint: "/api/login",
  235. body: `{
  236. "email": "belanger@getporter.dev",
  237. "password": "hello"
  238. }`,
  239. expStatus: http.StatusOK,
  240. expBody: ``,
  241. validators: []func(c *userTest, tester *tester, t *testing.T){
  242. BasicBodyValidator,
  243. },
  244. },
  245. &userTest{
  246. initializers: []func(tester *tester){
  247. initUserDefault,
  248. },
  249. msg: "Login user already logged in",
  250. method: "POST",
  251. endpoint: "/api/login",
  252. body: `{
  253. "email": "belanger@getporter.dev",
  254. "password": "hello"
  255. }`,
  256. expStatus: http.StatusOK,
  257. expBody: ``,
  258. useCookie: true,
  259. validators: []func(c *userTest, tester *tester, t *testing.T){
  260. BasicBodyValidator,
  261. },
  262. },
  263. &userTest{
  264. msg: "Login user unregistered email",
  265. method: "POST",
  266. endpoint: "/api/login",
  267. body: `{
  268. "email": "belanger@getporter.dev",
  269. "password": "hello"
  270. }`,
  271. expStatus: http.StatusUnauthorized,
  272. expBody: `{"code":401,"errors":["email not registered"]}`,
  273. validators: []func(c *userTest, tester *tester, t *testing.T){
  274. BasicBodyValidator,
  275. },
  276. },
  277. &userTest{
  278. initializers: []func(tester *tester){
  279. initUserDefault,
  280. },
  281. msg: "Login user incorrect password",
  282. method: "POST",
  283. endpoint: "/api/login",
  284. body: `{
  285. "email": "belanger@getporter.dev",
  286. "password": "notthepassword"
  287. }`,
  288. expStatus: http.StatusUnauthorized,
  289. expBody: `{"code":401,"errors":["incorrect password"]}`,
  290. useCookie: true,
  291. validators: []func(c *userTest, tester *tester, t *testing.T){
  292. BasicBodyValidator,
  293. },
  294. },
  295. }
  296. func TestHandleLoginUser(t *testing.T) {
  297. testUserRequests(t, loginUserTests, true)
  298. }
  299. var logoutUserTests = []*userTest{
  300. &userTest{
  301. initializers: []func(tester *tester){
  302. initUserDefault,
  303. },
  304. msg: "Logout user successful",
  305. method: "POST",
  306. endpoint: "/api/logout",
  307. body: `{
  308. "email": "belanger@getporter.dev",
  309. "password": "hello"
  310. }`,
  311. expStatus: http.StatusOK,
  312. expBody: ``,
  313. useCookie: true,
  314. validators: []func(c *userTest, tester *tester, t *testing.T){
  315. func(c *userTest, tester *tester, t *testing.T) {
  316. req, err := http.NewRequest(
  317. "GET",
  318. "/api/users/1",
  319. strings.NewReader(""),
  320. )
  321. req.AddCookie(tester.cookie)
  322. if err != nil {
  323. t.Fatal(err)
  324. }
  325. rr2 := httptest.NewRecorder()
  326. tester.router.ServeHTTP(rr2, req)
  327. if status := rr2.Code; status != http.StatusForbidden {
  328. t.Errorf("%s, handler returned wrong status: got %v want %v",
  329. "validator failed", status, http.StatusForbidden)
  330. }
  331. },
  332. },
  333. },
  334. }
  335. func TestHandleLogoutUser(t *testing.T) {
  336. testUserRequests(t, logoutUserTests, true)
  337. }
  338. var readUserTests = []*userTest{
  339. &userTest{
  340. initializers: []func(tester *tester){
  341. initUserWithContexts,
  342. },
  343. msg: "Read user successful",
  344. method: "GET",
  345. endpoint: "/api/users/1",
  346. body: "",
  347. expStatus: http.StatusOK,
  348. expBody: `{"id":1,"email":"belanger@getporter.dev","contexts":["context-test"],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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"}`,
  349. useCookie: true,
  350. validators: []func(c *userTest, tester *tester, t *testing.T){
  351. UserModelBodyValidator,
  352. },
  353. },
  354. &userTest{
  355. initializers: []func(tester *tester){
  356. initUserDefault,
  357. },
  358. msg: "Read user unauthorized",
  359. method: "GET",
  360. endpoint: "/api/users/2",
  361. body: "",
  362. expStatus: http.StatusForbidden,
  363. expBody: http.StatusText(http.StatusForbidden) + "\n",
  364. validators: []func(c *userTest, tester *tester, t *testing.T){
  365. BasicBodyValidator,
  366. },
  367. },
  368. }
  369. func TestHandleReadUser(t *testing.T) {
  370. testUserRequests(t, readUserTests, true)
  371. }
  372. var readUserClustersTests = []*userTest{
  373. &userTest{
  374. initializers: []func(tester *tester){
  375. initUserWithContexts,
  376. },
  377. msg: "Read user successful",
  378. method: "GET",
  379. endpoint: "/api/users/1/contexts",
  380. body: "",
  381. expStatus: http.StatusOK,
  382. useCookie: true,
  383. expBody: `[{"name":"context-test","server":"https://localhost","cluster":"cluster-test","user":"test-admin","selected":true}]`,
  384. validators: []func(c *userTest, tester *tester, t *testing.T){
  385. ContextBodyValidator,
  386. },
  387. },
  388. }
  389. func TestHandleReadUserClusters(t *testing.T) {
  390. testUserRequests(t, readUserClustersTests, true)
  391. }
  392. var updateUserTests = []*userTest{
  393. &userTest{
  394. initializers: []func(tester *tester){
  395. initUserDefault,
  396. },
  397. msg: "Update user successful",
  398. method: "PUT",
  399. endpoint: "/api/users/1",
  400. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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", "allowedContexts":[]}`,
  401. expStatus: http.StatusNoContent,
  402. expBody: "",
  403. useCookie: true,
  404. validators: []func(c *userTest, tester *tester, t *testing.T){
  405. func(c *userTest, tester *tester, t *testing.T) {
  406. req, err := http.NewRequest(
  407. "GET",
  408. "/api/users/1",
  409. strings.NewReader(""),
  410. )
  411. req.AddCookie(tester.cookie)
  412. if err != nil {
  413. t.Fatal(err)
  414. }
  415. rr2 := httptest.NewRecorder()
  416. tester.router.ServeHTTP(rr2, req)
  417. gotBody := &models.UserExternal{}
  418. expBody := &models.UserExternal{}
  419. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  420. json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev","contexts":[],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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)
  421. if !reflect.DeepEqual(gotBody, expBody) {
  422. t.Errorf("%s, handler returned wrong body: got %v want %v",
  423. "validator failed", gotBody, expBody)
  424. }
  425. },
  426. },
  427. },
  428. &userTest{
  429. initializers: []func(tester *tester){
  430. initUserDefault,
  431. },
  432. msg: "Update user successful without allowedContexts parameter",
  433. method: "PUT",
  434. endpoint: "/api/users/1",
  435. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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"}`,
  436. expStatus: http.StatusNoContent,
  437. expBody: "",
  438. useCookie: true,
  439. validators: []func(c *userTest, tester *tester, t *testing.T){
  440. func(c *userTest, tester *tester, t *testing.T) {
  441. req, err := http.NewRequest(
  442. "GET",
  443. "/api/users/1",
  444. strings.NewReader(""),
  445. )
  446. req.AddCookie(tester.cookie)
  447. if err != nil {
  448. t.Fatal(err)
  449. }
  450. rr2 := httptest.NewRecorder()
  451. tester.router.ServeHTTP(rr2, req)
  452. gotBody := &models.UserExternal{}
  453. expBody := &models.UserExternal{}
  454. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  455. json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev","contexts":[],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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)
  456. if !reflect.DeepEqual(gotBody, expBody) {
  457. t.Errorf("%s, handler returned wrong body: got %v want %v",
  458. "validator failed", gotBody, expBody)
  459. }
  460. },
  461. },
  462. },
  463. &userTest{
  464. initializers: []func(tester *tester){
  465. initUserDefault,
  466. },
  467. msg: "Update user successful with allowedContexts",
  468. method: "PUT",
  469. endpoint: "/api/users/1",
  470. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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", "allowedContexts":["context-test"]}`,
  471. expStatus: http.StatusNoContent,
  472. expBody: "",
  473. useCookie: true,
  474. validators: []func(c *userTest, tester *tester, t *testing.T){
  475. func(c *userTest, tester *tester, t *testing.T) {
  476. req, err := http.NewRequest(
  477. "GET",
  478. "/api/users/1",
  479. strings.NewReader(""),
  480. )
  481. req.AddCookie(tester.cookie)
  482. if err != nil {
  483. t.Fatal(err)
  484. }
  485. rr2 := httptest.NewRecorder()
  486. tester.router.ServeHTTP(rr2, req)
  487. gotBody := &models.UserExternal{}
  488. expBody := &models.UserExternal{}
  489. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  490. json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev","contexts":["context-test"],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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)
  491. if !reflect.DeepEqual(gotBody, expBody) {
  492. t.Errorf("%s, handler returned wrong body: got %v want %v",
  493. "validator failed", gotBody, expBody)
  494. }
  495. },
  496. },
  497. },
  498. &userTest{
  499. initializers: []func(tester *tester){
  500. initUserWithContexts,
  501. },
  502. msg: "Update user successful without rawKubeConfig",
  503. method: "PUT",
  504. endpoint: "/api/users/1",
  505. body: `{"allowedContexts":[]}`,
  506. expStatus: http.StatusNoContent,
  507. expBody: "",
  508. useCookie: true,
  509. validators: []func(c *userTest, tester *tester, t *testing.T){
  510. func(c *userTest, tester *tester, t *testing.T) {
  511. req, err := http.NewRequest(
  512. "GET",
  513. "/api/users/1",
  514. strings.NewReader(""),
  515. )
  516. req.AddCookie(tester.cookie)
  517. if err != nil {
  518. t.Fatal(err)
  519. }
  520. rr2 := httptest.NewRecorder()
  521. tester.router.ServeHTTP(rr2, req)
  522. gotBody := &models.UserExternal{}
  523. expBody := &models.UserExternal{}
  524. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  525. json.Unmarshal([]byte(`{"id":1,"email":"belanger@getporter.dev","contexts":[],"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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)
  526. if !reflect.DeepEqual(gotBody, expBody) {
  527. t.Errorf("%s, handler returned wrong body: got %v want %v",
  528. "validator failed", gotBody, expBody)
  529. }
  530. },
  531. },
  532. },
  533. &userTest{
  534. initializers: []func(tester *tester){
  535. initUserDefault,
  536. },
  537. msg: "Update user invalid id",
  538. method: "PUT",
  539. endpoint: "/api/users/alsdfjk",
  540. body: `{"rawKubeConfig":"apiVersion: v1\nkind: Config\npreferences: {}\ncurrent-context: context-test\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", "allowedContexts":[]}`,
  541. expStatus: http.StatusForbidden,
  542. expBody: http.StatusText(http.StatusForbidden) + "\n",
  543. validators: []func(c *userTest, tester *tester, t *testing.T){
  544. BasicBodyValidator,
  545. },
  546. },
  547. &userTest{
  548. initializers: []func(tester *tester){
  549. initUserDefault,
  550. },
  551. msg: "Update user bad kubeconfig",
  552. method: "PUT",
  553. endpoint: "/api/users/1",
  554. body: `{"rawKubeConfig":"notvalidyaml", "allowedContexts":[]}`,
  555. expStatus: http.StatusBadRequest,
  556. expBody: `{"code":600,"errors":["could not process request"]}`,
  557. useCookie: true,
  558. validators: []func(c *userTest, tester *tester, t *testing.T){
  559. BasicBodyValidator,
  560. },
  561. },
  562. }
  563. func TestHandleUpdateUser(t *testing.T) {
  564. testUserRequests(t, updateUserTests, true)
  565. }
  566. var deleteUserTests = []*userTest{
  567. &userTest{
  568. initializers: []func(tester *tester){
  569. initUserDefault,
  570. },
  571. msg: "Delete user successful",
  572. method: "DELETE",
  573. endpoint: "/api/users/1",
  574. body: `{"password":"hello"}`,
  575. expStatus: http.StatusNoContent,
  576. expBody: "",
  577. useCookie: true,
  578. validators: []func(c *userTest, tester *tester, t *testing.T){
  579. func(c *userTest, tester *tester, t *testing.T) {
  580. req, err := http.NewRequest(
  581. "GET",
  582. "/api/users/1",
  583. strings.NewReader(""),
  584. )
  585. req.AddCookie(tester.cookie)
  586. if err != nil {
  587. t.Fatal(err)
  588. }
  589. rr2 := httptest.NewRecorder()
  590. tester.router.ServeHTTP(rr2, req)
  591. gotBody := &models.UserExternal{}
  592. expBody := &models.UserExternal{}
  593. if status := rr2.Code; status != 404 {
  594. t.Errorf("DELETE user validation, handler returned wrong status code: got %v want %v",
  595. status, 404)
  596. }
  597. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  598. json.Unmarshal([]byte(`{"code":602,"errors":["could not find requested object"]}`), expBody)
  599. if !reflect.DeepEqual(gotBody, expBody) {
  600. t.Errorf("%s, handler returned wrong body: got %v want %v",
  601. "validator failed", gotBody, expBody)
  602. }
  603. },
  604. },
  605. },
  606. &userTest{
  607. initializers: []func(tester *tester){
  608. initUserDefault,
  609. },
  610. msg: "Delete user invalid id",
  611. method: "DELETE",
  612. endpoint: "/api/users/aldkjf",
  613. body: `{"password":"hello"}`,
  614. expStatus: http.StatusForbidden,
  615. expBody: http.StatusText(http.StatusForbidden) + "\n",
  616. validators: []func(c *userTest, tester *tester, t *testing.T){
  617. BasicBodyValidator,
  618. },
  619. },
  620. &userTest{
  621. initializers: []func(tester *tester){
  622. initUserDefault,
  623. },
  624. msg: "Delete user missing password",
  625. method: "DELETE",
  626. endpoint: "/api/users/1",
  627. body: `{}`,
  628. expStatus: http.StatusUnprocessableEntity,
  629. expBody: `{"code":601,"errors":["required validation failed"]}`,
  630. useCookie: true,
  631. validators: []func(c *userTest, tester *tester, t *testing.T){
  632. BasicBodyValidator,
  633. },
  634. },
  635. }
  636. func TestHandleDeleteUser(t *testing.T) {
  637. testUserRequests(t, deleteUserTests, true)
  638. }
  639. func BasicBodyValidator(c *userTest, tester *tester, t *testing.T) {
  640. if body := tester.rr.Body.String(); body != c.expBody {
  641. t.Errorf("%s, handler returned wrong body: got %v want %v",
  642. c.msg, body, c.expBody)
  643. }
  644. }
  645. func UserModelBodyValidator(c *userTest, tester *tester, t *testing.T) {
  646. gotBody := &models.UserExternal{}
  647. expBody := &models.UserExternal{}
  648. json.Unmarshal(tester.rr.Body.Bytes(), gotBody)
  649. json.Unmarshal([]byte(c.expBody), expBody)
  650. if !reflect.DeepEqual(gotBody, expBody) {
  651. t.Errorf("%s, handler returned wrong body: got %v want %v",
  652. c.msg, gotBody, expBody)
  653. }
  654. }
  655. func ContextBodyValidator(c *userTest, tester *tester, t *testing.T) {
  656. gotBody := &[]models.Context{}
  657. expBody := &[]models.Context{}
  658. json.Unmarshal(tester.rr.Body.Bytes(), gotBody)
  659. json.Unmarshal([]byte(c.expBody), expBody)
  660. if !reflect.DeepEqual(gotBody, expBody) {
  661. t.Errorf("%s, handler returned wrong body: got %v want %v",
  662. c.msg, gotBody, expBody)
  663. }
  664. }