integration_client_test.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fever_test
  4. import (
  5. "maps"
  6. "net/http"
  7. "net/url"
  8. "slices"
  9. "strconv"
  10. "strings"
  11. "testing"
  12. "miniflux.app/v2/internal/http/server/servertest"
  13. )
  14. // feverAPIVersion is the API version that every Fever response reports.
  15. const feverAPIVersion = 3
  16. // feverClient calls the Fever API. It sends no API key when apiKey is empty.
  17. //
  18. // Like Fever clients, it always calls the endpoint with the api parameter, which has no value.
  19. type feverClient struct {
  20. baseURL string
  21. apiKey string
  22. }
  23. // get sends a GET request with the API key and the parameters in the query string.
  24. func (client *feverClient) get(t *testing.T, query url.Values) (int, []byte) {
  25. t.Helper()
  26. return client.getRawQuery(t, client.withAPIKey(query).Encode())
  27. }
  28. // getRawQuery sends a GET request with the given query string, without adding the API key.
  29. // It sends selectors without a value, such as "groups" rather than "groups=", as Fever clients do.
  30. func (client *feverClient) getRawQuery(t *testing.T, rawQuery string) (int, []byte) {
  31. t.Helper()
  32. request, err := http.NewRequest(http.MethodGet, client.endpoint(rawQuery), nil)
  33. if err != nil {
  34. t.Fatal(err)
  35. }
  36. return servertest.Send(t, request)
  37. }
  38. // post sends a form with the API key and the parameters in the request body.
  39. func (client *feverClient) post(t *testing.T, form url.Values) (int, []byte) {
  40. t.Helper()
  41. return client.postWithQuery(t, nil, form)
  42. }
  43. // postWithQuery sends a form with the API key in the request body and the query parameters in the URL.
  44. // Fever clients send read requests this way: the selector in the URL, the API key as POST data.
  45. func (client *feverClient) postWithQuery(t *testing.T, query, form url.Values) (int, []byte) {
  46. t.Helper()
  47. body := strings.NewReader(client.withAPIKey(form).Encode())
  48. request, err := http.NewRequest(http.MethodPost, client.endpoint(query.Encode()), body)
  49. if err != nil {
  50. t.Fatal(err)
  51. }
  52. request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  53. return servertest.Send(t, request)
  54. }
  55. // getJSON sends a GET request and decodes the authenticated response into result.
  56. func (client *feverClient) getJSON(t *testing.T, query url.Values, result any) {
  57. t.Helper()
  58. status, body := client.get(t, query)
  59. decodeAuthenticatedJSON(t, status, body, result)
  60. }
  61. // postJSON sends a form and decodes the authenticated response into result.
  62. func (client *feverClient) postJSON(t *testing.T, form url.Values, result any) {
  63. t.Helper()
  64. status, body := client.post(t, form)
  65. decodeAuthenticatedJSON(t, status, body, result)
  66. }
  67. func (client *feverClient) endpoint(rawQuery string) string {
  68. if rawQuery == "" {
  69. return client.baseURL + "/fever/?api"
  70. }
  71. return client.baseURL + "/fever/?api&" + rawQuery
  72. }
  73. // withAPIKey returns a copy of the parameters with the API key of the client, when it has one.
  74. func (client *feverClient) withAPIKey(params url.Values) url.Values {
  75. values := url.Values{}
  76. maps.Copy(values, params)
  77. if client.apiKey != "" {
  78. values.Set("api_key", client.apiKey)
  79. }
  80. return values
  81. }
  82. // selector returns the query parameter that selects a read operation, such as groups or unread_item_ids.
  83. func selector(name string) url.Values {
  84. return url.Values{name: {""}}
  85. }
  86. // parseIDs returns the IDs of a comma-separated list, such as unread_item_ids, in ascending order.
  87. // Fever does not specify the order of these lists, so the tests compare them sorted.
  88. func parseIDs(t *testing.T, list string) []int64 {
  89. t.Helper()
  90. ids := []int64{}
  91. if list == "" {
  92. return ids
  93. }
  94. for value := range strings.SplitSeq(list, ",") {
  95. id, err := strconv.ParseInt(value, 10, 64)
  96. if err != nil {
  97. t.Fatalf(`Invalid ID %q in %q`, value, list)
  98. }
  99. ids = append(ids, id)
  100. }
  101. slices.Sort(ids)
  102. return ids
  103. }
  104. // sortedIDs returns a sorted copy of the IDs, to compare them with the result of parseIDs.
  105. func sortedIDs(ids ...int64) []int64 {
  106. sorted := slices.Clone(ids)
  107. slices.Sort(sorted)
  108. return sorted
  109. }
  110. // decodeAuthenticatedJSON decodes a successful response into result, and fails the test
  111. // unless the response reports the Fever API version and a successful authentication.
  112. func decodeAuthenticatedJSON(t *testing.T, status int, body []byte, result any) {
  113. t.Helper()
  114. var base baseResult
  115. servertest.DecodeJSON(t, status, body, &base)
  116. if base.APIVersion != feverAPIVersion || base.Auth != 1 {
  117. t.Fatalf(`Expected an authenticated response for API version %d, got %s`, feverAPIVersion, body)
  118. }
  119. servertest.DecodeJSON(t, status, body, result)
  120. }
  121. // requireAuthFailure fails the test unless the response is the Fever authentication failure:
  122. // HTTP 200, because Fever clients only look at the auth member, with auth set to 0.
  123. func requireAuthFailure(t *testing.T, status int, body []byte) {
  124. t.Helper()
  125. var result baseResult
  126. servertest.DecodeJSON(t, status, body, &result)
  127. if result.APIVersion != feverAPIVersion || result.Auth != 0 {
  128. t.Fatalf(`Expected an authentication failure for API version %d, got %s`, feverAPIVersion, body)
  129. }
  130. }
  131. // The response types below mirror the JSON documents sent to clients. They are not the
  132. // package's own types, so renaming a JSON field fails the tests as it would break clients.
  133. type baseResult struct {
  134. APIVersion int `json:"api_version"`
  135. Auth int `json:"auth"`
  136. LastRefreshedOnTime int64 `json:"last_refreshed_on_time"`
  137. }
  138. type groupResult struct {
  139. ID int64 `json:"id"`
  140. Title string `json:"title"`
  141. }
  142. type feedsGroupResult struct {
  143. GroupID int64 `json:"group_id"`
  144. FeedIDs string `json:"feed_ids"`
  145. }
  146. type groupsResult struct {
  147. Groups []groupResult `json:"groups"`
  148. FeedsGroups []feedsGroupResult `json:"feeds_groups"`
  149. }
  150. type feedResult struct {
  151. ID int64 `json:"id"`
  152. FaviconID int64 `json:"favicon_id"`
  153. Title string `json:"title"`
  154. URL string `json:"url"`
  155. SiteURL string `json:"site_url"`
  156. IsSpark int `json:"is_spark"`
  157. LastUpdatedOnTime int64 `json:"last_updated_on_time"`
  158. }
  159. type feedsResult struct {
  160. Feeds []feedResult `json:"feeds"`
  161. FeedsGroups []feedsGroupResult `json:"feeds_groups"`
  162. }
  163. type faviconResult struct {
  164. ID int64 `json:"id"`
  165. Data string `json:"data"`
  166. }
  167. type faviconsResult struct {
  168. Favicons []faviconResult `json:"favicons"`
  169. }
  170. type unreadItemIDsResult struct {
  171. UnreadItemIDs string `json:"unread_item_ids"`
  172. }
  173. type savedItemIDsResult struct {
  174. SavedItemIDs string `json:"saved_item_ids"`
  175. }
  176. type itemResult struct {
  177. ID int64 `json:"id"`
  178. FeedID int64 `json:"feed_id"`
  179. Title string `json:"title"`
  180. Author string `json:"author"`
  181. HTML string `json:"html"`
  182. URL string `json:"url"`
  183. IsSaved int `json:"is_saved"`
  184. IsRead int `json:"is_read"`
  185. CreatedOnTime int64 `json:"created_on_time"`
  186. }
  187. type itemsResult struct {
  188. Items []itemResult `json:"items"`
  189. TotalItems int `json:"total_items"`
  190. }
  191. // ids returns the item IDs in the order of the response.
  192. func (result itemsResult) ids() []int64 {
  193. ids := make([]int64, 0, len(result.Items))
  194. for _, item := range result.Items {
  195. ids = append(ids, item.ID)
  196. }
  197. return ids
  198. }