user_handler_test.go 20 KB

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