chart_handler_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. package api_test
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. "net/http/httptest"
  7. "net/url"
  8. "reflect"
  9. "strings"
  10. "testing"
  11. "github.com/porter-dev/porter/internal/helm"
  12. "helm.sh/helm/v3/pkg/chart"
  13. "helm.sh/helm/v3/pkg/release"
  14. "helm.sh/helm/v3/pkg/storage/driver"
  15. )
  16. type releaseStub struct {
  17. name string
  18. namespace string
  19. version int
  20. chartVersion string
  21. status release.Status
  22. }
  23. // ------------------------- TEST TYPES AND MAIN LOOP ------------------------- //
  24. type chartTest struct {
  25. initializers []func(tester *tester)
  26. namespace string
  27. msg string
  28. method string
  29. endpoint string
  30. body string
  31. expStatus int
  32. expBody string
  33. useCookie bool
  34. validators []func(c *chartTest, tester *tester, t *testing.T)
  35. }
  36. func testChartRequests(t *testing.T, tests []*chartTest, canQuery bool) {
  37. for _, c := range tests {
  38. // create a new tester
  39. tester := newTester(canQuery)
  40. // if there's an initializer, call it
  41. for _, init := range c.initializers {
  42. init(tester)
  43. }
  44. tester.app.TestAgents.HelmAgent.ActionConfig.Releases.Driver.(*driver.Memory).SetNamespace(c.namespace)
  45. req, err := http.NewRequest(
  46. c.method,
  47. c.endpoint,
  48. strings.NewReader(c.body),
  49. )
  50. tester.req = req
  51. if c.useCookie {
  52. req.AddCookie(tester.cookie)
  53. }
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. tester.execute()
  58. rr := tester.rr
  59. // first, check that the status matches
  60. if status := rr.Code; status != c.expStatus {
  61. t.Errorf("%s, handler returned wrong status code: got %v want %v",
  62. c.msg, status, c.expStatus)
  63. }
  64. // if there's a validator, call it
  65. for _, validate := range c.validators {
  66. validate(c, tester, t)
  67. }
  68. }
  69. }
  70. // ------------------------- TEST FIXTURES AND FUNCTIONS ------------------------- //
  71. var listChartsTests = []*chartTest{
  72. &chartTest{
  73. initializers: []func(tester *tester){
  74. initDefaultCharts,
  75. },
  76. msg: "List charts",
  77. method: "GET",
  78. endpoint: "/api/charts?" + url.Values{
  79. "namespace": []string{""},
  80. "context": []string{"context-test"},
  81. "storage": []string{"memory"},
  82. "limit": []string{"20"},
  83. "skip": []string{"0"},
  84. "byDate": []string{"false"},
  85. "statusFilter": []string{"deployed"},
  86. }.Encode(),
  87. body: "",
  88. expStatus: http.StatusOK,
  89. expBody: releaseStubsToChartJSON(sampleReleaseStubs),
  90. useCookie: true,
  91. validators: []func(c *chartTest, tester *tester, t *testing.T){
  92. chartReleaseArrBodyValidator,
  93. },
  94. },
  95. &chartTest{
  96. initializers: []func(tester *tester){
  97. initDefaultCharts,
  98. },
  99. msg: "List charts",
  100. method: "GET",
  101. namespace: "default",
  102. endpoint: "/api/charts?" + url.Values{
  103. "namespace": []string{"default"},
  104. "context": []string{"context-test"},
  105. "storage": []string{"memory"},
  106. "limit": []string{"20"},
  107. "skip": []string{"0"},
  108. "byDate": []string{"false"},
  109. "statusFilter": []string{"deployed"},
  110. }.Encode(),
  111. body: "",
  112. expStatus: http.StatusOK,
  113. expBody: releaseStubsToChartJSON([]releaseStub{
  114. sampleReleaseStubs[0],
  115. sampleReleaseStubs[2],
  116. }),
  117. useCookie: true,
  118. validators: []func(c *chartTest, tester *tester, t *testing.T){
  119. chartReleaseArrBodyValidator,
  120. },
  121. },
  122. }
  123. func TestHandleListCharts(t *testing.T) {
  124. testChartRequests(t, listChartsTests, true)
  125. }
  126. var getChartTests = []*chartTest{
  127. &chartTest{
  128. initializers: []func(tester *tester){
  129. initDefaultCharts,
  130. },
  131. msg: "Get charts",
  132. method: "GET",
  133. namespace: "default",
  134. endpoint: "/api/charts/airwatch/1?" + url.Values{
  135. "namespace": []string{""},
  136. "context": []string{"context-test"},
  137. "storage": []string{"memory"},
  138. }.Encode(),
  139. body: "",
  140. expStatus: http.StatusOK,
  141. expBody: releaseStubToChartJSON(sampleReleaseStubs[0]),
  142. useCookie: true,
  143. validators: []func(c *chartTest, tester *tester, t *testing.T){
  144. chartReleaseBodyValidator,
  145. },
  146. },
  147. }
  148. func TestHandleGetChart(t *testing.T) {
  149. testChartRequests(t, getChartTests, true)
  150. }
  151. var listChartHistoryTests = []*chartTest{
  152. &chartTest{
  153. initializers: []func(tester *tester){
  154. initHistoryCharts,
  155. },
  156. msg: "List chart history",
  157. method: "GET",
  158. namespace: "default",
  159. endpoint: "/api/charts/wordpress/history?" + url.Values{
  160. "namespace": []string{""},
  161. "context": []string{"context-test"},
  162. "storage": []string{"memory"},
  163. }.Encode(),
  164. body: "",
  165. expStatus: http.StatusOK,
  166. expBody: releaseStubsToChartJSON(historyReleaseStubs),
  167. useCookie: true,
  168. validators: []func(c *chartTest, tester *tester, t *testing.T){
  169. chartReleaseArrBodyValidator,
  170. },
  171. },
  172. }
  173. func TestHandleListChartHistory(t *testing.T) {
  174. testChartRequests(t, listChartHistoryTests, true)
  175. }
  176. var upgradeChartTests = []*chartTest{
  177. &chartTest{
  178. initializers: []func(tester *tester){
  179. initHistoryCharts,
  180. },
  181. msg: "Upgrade relase",
  182. method: "POST",
  183. namespace: "default",
  184. endpoint: "/api/charts/wordpress/upgrade",
  185. body: `
  186. {
  187. "namespace": "default",
  188. "context": "context-test",
  189. "storage": "memory",
  190. "values": "\nfoo: bar\n"
  191. }
  192. `,
  193. expStatus: http.StatusOK,
  194. expBody: ``,
  195. useCookie: true,
  196. validators: []func(c *chartTest, tester *tester, t *testing.T){
  197. func(c *chartTest, tester *tester, t *testing.T) {
  198. req, err := http.NewRequest(
  199. "GET",
  200. "/api/charts/wordpress/3?"+url.Values{
  201. "namespace": []string{"default"},
  202. "context": []string{"context-test"},
  203. "storage": []string{"memory"},
  204. }.Encode(),
  205. strings.NewReader(""),
  206. )
  207. req.AddCookie(tester.cookie)
  208. if err != nil {
  209. t.Fatal(err)
  210. }
  211. rr2 := httptest.NewRecorder()
  212. tester.router.ServeHTTP(rr2, req)
  213. gotBody := &release.Release{}
  214. expBody := &release.Release{}
  215. expBodyJSON := releaseStubToChartJSON(releaseStub{"wordpress", "default", 3, "1.0.2", release.StatusDeployed})
  216. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  217. json.Unmarshal([]byte(expBodyJSON), expBody)
  218. // just check name and version match, other items will be different
  219. if gotBody.Name != expBody.Name {
  220. t.Errorf("%s, validation wrong body: got %v want %v",
  221. c.msg, gotBody.Name, expBody.Name)
  222. }
  223. if gotBody.Version != expBody.Version {
  224. t.Errorf("%s, validation wrong body: got %v want %v",
  225. c.msg, gotBody.Version, expBody.Version)
  226. }
  227. expConfig := map[string]interface{}{
  228. "foo": "bar",
  229. }
  230. if !reflect.DeepEqual(gotBody.Config, expConfig) {
  231. t.Errorf("%s, validation wrong config: got %v want %v",
  232. c.msg, gotBody.Config, expConfig)
  233. }
  234. },
  235. },
  236. },
  237. }
  238. func TestUpgradeChart(t *testing.T) {
  239. testChartRequests(t, upgradeChartTests, true)
  240. }
  241. var rollbackChartTests = []*chartTest{
  242. &chartTest{
  243. initializers: []func(tester *tester){
  244. initHistoryCharts,
  245. },
  246. msg: "Rollback relase",
  247. method: "POST",
  248. namespace: "default",
  249. endpoint: "/api/charts/rollback/wordpress/1",
  250. body: `
  251. {
  252. "namespace": "default",
  253. "context": "context-test",
  254. "storage": "memory"
  255. }
  256. `,
  257. expStatus: http.StatusOK,
  258. expBody: ``,
  259. useCookie: true,
  260. validators: []func(c *chartTest, tester *tester, t *testing.T){
  261. func(c *chartTest, tester *tester, t *testing.T) {
  262. req, err := http.NewRequest(
  263. "GET",
  264. "/api/charts/wordpress/3?"+url.Values{
  265. "namespace": []string{"default"},
  266. "context": []string{"context-test"},
  267. "storage": []string{"memory"},
  268. }.Encode(),
  269. strings.NewReader(""),
  270. )
  271. req.AddCookie(tester.cookie)
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. rr2 := httptest.NewRecorder()
  276. tester.router.ServeHTTP(rr2, req)
  277. gotBody := &release.Release{}
  278. expBody := &release.Release{}
  279. expBodyJSON := releaseStubToChartJSON(releaseStub{"wordpress", "default", 3, "1.0.1", release.StatusDeployed})
  280. fmt.Println(rr2.Body.String())
  281. json.Unmarshal(rr2.Body.Bytes(), gotBody)
  282. json.Unmarshal([]byte(expBodyJSON), expBody)
  283. // just check name and version match, other items will be different
  284. if gotBody.Name != expBody.Name {
  285. t.Errorf("%s, validation wrong body: got %v want %v",
  286. c.msg, gotBody.Name, expBody.Name)
  287. }
  288. if gotBody.Version != expBody.Version {
  289. t.Errorf("%s, validation wrong body: got %v want %v",
  290. c.msg, gotBody.Version, expBody.Version)
  291. }
  292. },
  293. },
  294. },
  295. }
  296. func TestRollbackChart(t *testing.T) {
  297. testChartRequests(t, rollbackChartTests, true)
  298. }
  299. // ------------------------- INITIALIZERS AND VALIDATORS ------------------------- //
  300. func initDefaultCharts(tester *tester) {
  301. initUserDefault(tester)
  302. agent := tester.app.TestAgents.HelmAgent
  303. makeReleases(agent, sampleReleaseStubs)
  304. // calling agent.ActionConfig.Releases.Create in makeReleases will automatically set the
  305. // namespace, so we have to reset the namespace of the storage driver
  306. agent.ActionConfig.Releases.Driver.(*driver.Memory).SetNamespace("")
  307. }
  308. func initHistoryCharts(tester *tester) {
  309. initUserDefault(tester)
  310. agent := tester.app.TestAgents.HelmAgent
  311. makeReleases(agent, historyReleaseStubs)
  312. // calling agent.ActionConfig.Releases.Create in makeReleases will automatically set the
  313. // namespace, so we have to reset the namespace of the storage driver
  314. agent.ActionConfig.Releases.Driver.(*driver.Memory).SetNamespace("")
  315. }
  316. var sampleReleaseStubs = []releaseStub{
  317. releaseStub{"airwatch", "default", 1, "1.0.0", release.StatusDeployed},
  318. releaseStub{"not-in-default-namespace", "other", 1, "1.0.1", release.StatusDeployed},
  319. releaseStub{"wordpress", "default", 1, "1.0.2", release.StatusDeployed},
  320. }
  321. var historyReleaseStubs = []releaseStub{
  322. releaseStub{"wordpress", "default", 1, "1.0.1", release.StatusSuperseded},
  323. releaseStub{"wordpress", "default", 2, "1.0.2", release.StatusDeployed},
  324. }
  325. func releaseStubsToChartJSON(rels []releaseStub) string {
  326. releases := make([]*release.Release, 0)
  327. for _, r := range rels {
  328. rel := releaseStubToRelease(r)
  329. releases = append(releases, rel)
  330. }
  331. str, _ := json.Marshal(releases)
  332. return string(str)
  333. }
  334. func releaseStubToChartJSON(r releaseStub) string {
  335. rel := releaseStubToRelease(r)
  336. str, _ := json.Marshal(rel)
  337. return string(str)
  338. }
  339. func releaseStubToRelease(r releaseStub) *release.Release {
  340. return &release.Release{
  341. Name: r.name,
  342. Namespace: r.namespace,
  343. Version: r.version,
  344. Info: &release.Info{
  345. Status: r.status,
  346. },
  347. Chart: &chart.Chart{
  348. Metadata: &chart.Metadata{
  349. Version: r.chartVersion,
  350. Icon: "https://example.com/icon.png",
  351. },
  352. },
  353. }
  354. }
  355. func makeReleases(agent *helm.Agent, rels []releaseStub) {
  356. storage := agent.ActionConfig.Releases
  357. for _, r := range rels {
  358. rel := releaseStubToRelease(r)
  359. storage.Create(rel)
  360. }
  361. }
  362. func chartReleaseBodyValidator(c *chartTest, tester *tester, t *testing.T) {
  363. gotBody := &release.Release{}
  364. expBody := &release.Release{}
  365. json.Unmarshal(tester.rr.Body.Bytes(), gotBody)
  366. json.Unmarshal([]byte(c.expBody), expBody)
  367. if !reflect.DeepEqual(gotBody, expBody) {
  368. t.Errorf("%s, handler returned wrong body: got %v want %v",
  369. c.msg, gotBody, expBody)
  370. }
  371. }
  372. func chartReleaseArrBodyValidator(c *chartTest, tester *tester, t *testing.T) {
  373. gotBody := &[]release.Release{}
  374. expBody := &[]release.Release{}
  375. json.Unmarshal(tester.rr.Body.Bytes(), gotBody)
  376. json.Unmarshal([]byte(c.expBody), expBody)
  377. if !reflect.DeepEqual(gotBody, expBody) {
  378. t.Errorf("%s, handler returned wrong body: got %v want %v",
  379. c.msg, gotBody, expBody)
  380. }
  381. }