integration_client_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fever_test
  4. import (
  5. "encoding/json"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "slices"
  10. "strconv"
  11. "strings"
  12. "testing"
  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 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 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. for key, list := range params {
  77. values[key] = list
  78. }
  79. if client.apiKey != "" {
  80. values.Set("api_key", client.apiKey)
  81. }
  82. return values
  83. }
  84. // selector returns the query parameter that selects a read operation, such as groups or unread_item_ids.
  85. func selector(name string) url.Values {
  86. return url.Values{name: {""}}
  87. }
  88. // parseIDs returns the IDs of a comma-separated list, such as unread_item_ids, in ascending order.
  89. // Fever does not specify the order of these lists, so the tests compare them sorted.
  90. func parseIDs(t *testing.T, list string) []int64 {
  91. t.Helper()
  92. ids := []int64{}
  93. if list == "" {
  94. return ids
  95. }
  96. for value := range strings.SplitSeq(list, ",") {
  97. id, err := strconv.ParseInt(value, 10, 64)
  98. if err != nil {
  99. t.Fatalf(`Invalid ID %q in %q`, value, list)
  100. }
  101. ids = append(ids, id)
  102. }
  103. slices.Sort(ids)
  104. return ids
  105. }
  106. // sortedIDs returns a sorted copy of the IDs, to compare them with the result of parseIDs.
  107. func sortedIDs(ids ...int64) []int64 {
  108. sorted := slices.Clone(ids)
  109. slices.Sort(sorted)
  110. return sorted
  111. }
  112. func send(t *testing.T, request *http.Request) (int, []byte) {
  113. t.Helper()
  114. response, err := http.DefaultClient.Do(request)
  115. if err != nil {
  116. t.Fatal(err)
  117. }
  118. defer response.Body.Close()
  119. body, err := io.ReadAll(response.Body)
  120. if err != nil {
  121. t.Fatal(err)
  122. }
  123. return response.StatusCode, body
  124. }
  125. func decodeJSON(t *testing.T, status int, body []byte, result any) {
  126. t.Helper()
  127. if status != http.StatusOK {
  128. t.Fatalf(`Expected status 200, got %d: %s`, status, body)
  129. }
  130. if err := json.Unmarshal(body, result); err != nil {
  131. t.Fatalf(`Unable to decode %s: %v`, body, err)
  132. }
  133. }
  134. // decodeAuthenticatedJSON decodes a successful response into result, and fails the test
  135. // unless the response reports the Fever API version and a successful authentication.
  136. func decodeAuthenticatedJSON(t *testing.T, status int, body []byte, result any) {
  137. t.Helper()
  138. var base baseResult
  139. decodeJSON(t, status, body, &base)
  140. if base.APIVersion != feverAPIVersion || base.Auth != 1 {
  141. t.Fatalf(`Expected an authenticated response for API version %d, got %s`, feverAPIVersion, body)
  142. }
  143. decodeJSON(t, status, body, result)
  144. }
  145. // requireAuthFailure fails the test unless the response is the Fever authentication failure:
  146. // HTTP 200, because Fever clients only look at the auth member, with auth set to 0.
  147. func requireAuthFailure(t *testing.T, status int, body []byte) {
  148. t.Helper()
  149. var result baseResult
  150. decodeJSON(t, status, body, &result)
  151. if result.APIVersion != feverAPIVersion || result.Auth != 0 {
  152. t.Fatalf(`Expected an authentication failure for API version %d, got %s`, feverAPIVersion, body)
  153. }
  154. }
  155. // The response types below mirror the JSON documents sent to clients. They are not the
  156. // package's own types, so renaming a JSON field fails the tests as it would break clients.
  157. type baseResult struct {
  158. APIVersion int `json:"api_version"`
  159. Auth int `json:"auth"`
  160. LastRefreshedOnTime int64 `json:"last_refreshed_on_time"`
  161. }
  162. type groupResult struct {
  163. ID int64 `json:"id"`
  164. Title string `json:"title"`
  165. }
  166. type feedsGroupResult struct {
  167. GroupID int64 `json:"group_id"`
  168. FeedIDs string `json:"feed_ids"`
  169. }
  170. type groupsResult struct {
  171. Groups []groupResult `json:"groups"`
  172. FeedsGroups []feedsGroupResult `json:"feeds_groups"`
  173. }
  174. type feedResult struct {
  175. ID int64 `json:"id"`
  176. FaviconID int64 `json:"favicon_id"`
  177. Title string `json:"title"`
  178. URL string `json:"url"`
  179. SiteURL string `json:"site_url"`
  180. IsSpark int `json:"is_spark"`
  181. LastUpdatedOnTime int64 `json:"last_updated_on_time"`
  182. }
  183. type feedsResult struct {
  184. Feeds []feedResult `json:"feeds"`
  185. FeedsGroups []feedsGroupResult `json:"feeds_groups"`
  186. }
  187. type faviconResult struct {
  188. ID int64 `json:"id"`
  189. Data string `json:"data"`
  190. }
  191. type faviconsResult struct {
  192. Favicons []faviconResult `json:"favicons"`
  193. }
  194. type unreadItemIDsResult struct {
  195. UnreadItemIDs string `json:"unread_item_ids"`
  196. }
  197. type savedItemIDsResult struct {
  198. SavedItemIDs string `json:"saved_item_ids"`
  199. }
  200. type itemResult struct {
  201. ID int64 `json:"id"`
  202. FeedID int64 `json:"feed_id"`
  203. Title string `json:"title"`
  204. Author string `json:"author"`
  205. HTML string `json:"html"`
  206. URL string `json:"url"`
  207. IsSaved int `json:"is_saved"`
  208. IsRead int `json:"is_read"`
  209. CreatedOnTime int64 `json:"created_on_time"`
  210. }
  211. type itemsResult struct {
  212. Items []itemResult `json:"items"`
  213. TotalItems int `json:"total_items"`
  214. }
  215. // ids returns the item IDs in the order of the response.
  216. func (result itemsResult) ids() []int64 {
  217. ids := make([]int64, 0, len(result.Items))
  218. for _, item := range result.Items {
  219. ids = append(ids, item.ID)
  220. }
  221. return ids
  222. }