test_client_rest.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. """Tests pour src.services.client_rest."""
  2. from __future__ import annotations
  3. from unittest.mock import MagicMock, patch
  4. import httpx
  5. import pytest
  6. from src.config.initialization import Settings
  7. from src.services.client_rest import ClientRest, HTTPMethod
  8. @pytest.fixture
  9. def settings() -> Settings:
  10. return Settings(
  11. base_url="https://api.example.com",
  12. phpsessid="sess_test",
  13. authorization="",
  14. timeout_seconds=5.0,
  15. )
  16. @pytest.fixture
  17. def settings_with_authorization() -> Settings:
  18. return Settings(
  19. base_url="https://api.example.com",
  20. phpsessid="sess_test",
  21. authorization="Basic dXNlcjpwYXNz",
  22. timeout_seconds=5.0,
  23. )
  24. @pytest.fixture
  25. def client(settings: Settings) -> ClientRest:
  26. return ClientRest(settings=settings)
  27. @pytest.fixture
  28. def mock_httpx_client() -> tuple[MagicMock, MagicMock]:
  29. mock_client = MagicMock()
  30. mock_response = MagicMock()
  31. mock_response.json.return_value = {"code": "200", "data": {"ok": True}}
  32. mock_response.raise_for_status.return_value = None
  33. mock_client.get.return_value = mock_response
  34. mock_client.post.return_value = mock_response
  35. mock_client.put.return_value = mock_response
  36. mock_client.delete.return_value = mock_response
  37. with patch("src.services.client_rest.httpx.Client") as client_cls:
  38. client_cls.return_value.__enter__.return_value = mock_client
  39. yield mock_client, mock_response
  40. class TestClientRestInit:
  41. def test_init_uses_provided_settings(self, settings: Settings) -> None:
  42. client = ClientRest(settings=settings)
  43. assert client.settings is settings
  44. def test_init_loads_settings_when_not_provided(self, settings: Settings) -> None:
  45. with patch(
  46. "src.services.client_rest.get_settings",
  47. return_value=settings,
  48. ) as get_settings_mock:
  49. client = ClientRest()
  50. get_settings_mock.assert_called_once()
  51. assert client.settings is settings
  52. def test_init_builds_read_headers_without_content_type(
  53. self, client: ClientRest
  54. ) -> None:
  55. assert client.headers == {
  56. "Cookie": "PHPSESSID=sess_test",
  57. "Accept": "application/json",
  58. }
  59. def test_init_adds_authorization_header_when_configured(
  60. self, settings_with_authorization: Settings
  61. ) -> None:
  62. client = ClientRest(settings=settings_with_authorization)
  63. assert client.headers == {
  64. "Cookie": "PHPSESSID=sess_test",
  65. "Accept": "application/json",
  66. "Authorization": "Basic dXNlcjpwYXNz",
  67. }
  68. class TestBuildUrl:
  69. def test_build_url_adds_leading_slash(self, client: ClientRest) -> None:
  70. assert client._build_url("rest/tools/resource") == (
  71. "https://api.example.com/rest/tools/resource"
  72. )
  73. def test_build_url_preserves_leading_slash(self, client: ClientRest) -> None:
  74. assert client._build_url("/rest/tools/resource") == (
  75. "https://api.example.com/rest/tools/resource"
  76. )
  77. class TestExecuteSuccess:
  78. def test_execute_get(
  79. self,
  80. client: ClientRest,
  81. mock_httpx_client: tuple[MagicMock, MagicMock],
  82. ) -> None:
  83. mock_client, mock_response = mock_httpx_client
  84. params = {"showUnpublished": 1}
  85. result = client.execute(
  86. HTTPMethod.GET,
  87. "/rest/tools/resource/10000",
  88. params=params,
  89. )
  90. mock_client.get.assert_called_once_with(
  91. "https://api.example.com/rest/tools/resource/10000",
  92. headers=client.headers,
  93. params=params,
  94. )
  95. mock_response.raise_for_status.assert_called_once()
  96. assert result == {"code": "200", "data": {"ok": True}}
  97. def test_execute_post_adds_content_type_when_json_provided(
  98. self,
  99. client: ClientRest,
  100. mock_httpx_client: tuple[MagicMock, MagicMock],
  101. ) -> None:
  102. mock_client, _ = mock_httpx_client
  103. payload = {"pagetitle": "Ma page"}
  104. client.execute(
  105. HTTPMethod.POST,
  106. "/rest/tools/resource",
  107. json=payload,
  108. )
  109. expected_headers = {
  110. **client.headers,
  111. "Content-Type": "application/json",
  112. }
  113. mock_client.post.assert_called_once_with(
  114. "https://api.example.com/rest/tools/resource",
  115. headers=expected_headers,
  116. json=payload,
  117. )
  118. def test_execute_put(
  119. self,
  120. client: ClientRest,
  121. mock_httpx_client: tuple[MagicMock, MagicMock],
  122. ) -> None:
  123. mock_client, _ = mock_httpx_client
  124. payload = {"id": 10000, "pagetitle": "Updated"}
  125. client.execute(
  126. HTTPMethod.PUT,
  127. "/rest/tools/resource",
  128. json=payload,
  129. )
  130. expected_headers = {
  131. **client.headers,
  132. "Content-Type": "application/json",
  133. }
  134. mock_client.put.assert_called_once_with(
  135. "https://api.example.com/rest/tools/resource",
  136. headers=expected_headers,
  137. json=payload,
  138. )
  139. def test_execute_delete(
  140. self,
  141. client: ClientRest,
  142. mock_httpx_client: tuple[MagicMock, MagicMock],
  143. ) -> None:
  144. mock_client, _ = mock_httpx_client
  145. client.execute(HTTPMethod.DELETE, "/rest/tools/resource/10000", params={
  146. "mandatoryParent": 10000,
  147. })
  148. mock_client.delete.assert_called_once_with(
  149. "https://api.example.com/rest/tools/resource/10000",
  150. headers=client.headers,
  151. params={"mandatoryParent": 10000},
  152. )
  153. class TestExecuteErrors:
  154. def test_execute_raises_on_server_http_error(
  155. self,
  156. client: ClientRest,
  157. mock_httpx_client: tuple[MagicMock, MagicMock],
  158. ) -> None:
  159. _, mock_response = mock_httpx_client
  160. mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
  161. "Server Error",
  162. request=httpx.Request("GET", "https://api.example.com/rest/tools/resource"),
  163. response=httpx.Response(500, request=httpx.Request("GET", "https://example.com")),
  164. )
  165. with pytest.raises(httpx.HTTPStatusError):
  166. client.execute(HTTPMethod.GET, "/rest/tools/resource")
  167. def test_execute_raises_timeout_error(
  168. self,
  169. client: ClientRest,
  170. ) -> None:
  171. with patch("src.services.client_rest.httpx.Client") as client_cls:
  172. mock_client = MagicMock()
  173. mock_client.get.side_effect = httpx.TimeoutException("timed out")
  174. client_cls.return_value.__enter__.return_value = mock_client
  175. with pytest.raises(TimeoutError, match="Timeout lors de l'exécution"):
  176. client.execute(HTTPMethod.GET, "/rest/tools/resource")
  177. def test_execute_raises_on_invalid_http_method(
  178. self,
  179. client: ClientRest,
  180. mock_httpx_client: tuple[MagicMock, MagicMock],
  181. ) -> None:
  182. mock_client, _ = mock_httpx_client
  183. with pytest.raises(ValueError, match="Methode HTTP non supportee: PATCH"):
  184. client.execute("PATCH", "/rest/tools/resource") # type: ignore[arg-type]
  185. mock_client.get.assert_not_called()
  186. mock_client.post.assert_not_called()
  187. mock_client.put.assert_not_called()
  188. mock_client.delete.assert_not_called()