Sfoglia il codice sorgente

add test for client rest and initialization module

Khanh Nguyen 5 mesi fa
parent
commit
4e757205c2
2 ha cambiato i file con 283 aggiunte e 0 eliminazioni
  1. 211 0
      tests/test_client_rest.py
  2. 72 0
      tests/test_initialization.py

+ 211 - 0
tests/test_client_rest.py

@@ -0,0 +1,211 @@
+"""Tests pour src.services.client_rest."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import httpx
+import pytest
+
+from src.config.initialization import Settings
+from src.services.client_rest import ClientRest, HTTPMethod
+
+
+@pytest.fixture
+def settings() -> Settings:
+    return Settings(
+        base_url="https://api.example.com",
+        lwe_token="lwe_tok_test",
+        phpsessid="sess_test",
+        timeout_seconds=5.0,
+    )
+
+
+@pytest.fixture
+def client(settings: Settings) -> ClientRest:
+    return ClientRest(settings=settings)
+
+
+@pytest.fixture
+def mock_httpx_client() -> tuple[MagicMock, MagicMock]:
+    mock_client = MagicMock()
+    mock_response = MagicMock()
+    mock_response.json.return_value = {"code": "200", "data": {"ok": True}}
+    mock_response.raise_for_status.return_value = None
+
+    mock_client.get.return_value = mock_response
+    mock_client.post.return_value = mock_response
+    mock_client.put.return_value = mock_response
+    mock_client.delete.return_value = mock_response
+
+    with patch("src.services.client_rest.httpx.Client") as client_cls:
+        client_cls.return_value.__enter__.return_value = mock_client
+        yield mock_client, mock_response
+
+
+class TestClientRestInit:
+    def test_init_uses_provided_settings(self, settings: Settings) -> None:
+        client = ClientRest(settings=settings)
+
+        assert client.settings is settings
+
+    def test_init_loads_settings_when_not_provided(self, settings: Settings) -> None:
+        with patch(
+            "src.services.client_rest.get_settings",
+            return_value=settings,
+        ) as get_settings_mock:
+            client = ClientRest()
+
+        get_settings_mock.assert_called_once()
+        assert client.settings is settings
+
+    def test_init_builds_read_headers_without_content_type(
+        self, client: ClientRest
+    ) -> None:
+        assert client.headers == {
+            "Authorization": "lwe_tok_test",
+            "Cookie": "PHPSESSID=sess_test",
+            "Accept": "application/json",
+        }
+
+
+class TestBuildUrl:
+    def test_build_url_adds_leading_slash(self, client: ClientRest) -> None:
+        assert client._build_url("rest/tools/resource") == (
+            "https://api.example.com/rest/tools/resource"
+        )
+
+    def test_build_url_preserves_leading_slash(self, client: ClientRest) -> None:
+        assert client._build_url("/rest/tools/resource") == (
+            "https://api.example.com/rest/tools/resource"
+        )
+
+
+class TestExecuteSuccess:
+    def test_execute_get(
+        self,
+        client: ClientRest,
+        mock_httpx_client: tuple[MagicMock, MagicMock],
+    ) -> None:
+        mock_client, mock_response = mock_httpx_client
+        params = {"showUnpublished": 1}
+
+        result = client.execute(
+            HTTPMethod.GET,
+            "/rest/tools/resource/10000",
+            params=params,
+        )
+
+        mock_client.get.assert_called_once_with(
+            "https://api.example.com/rest/tools/resource/10000",
+            headers=client.headers,
+            params=params,
+        )
+        mock_response.raise_for_status.assert_called_once()
+        assert result == {"code": "200", "data": {"ok": True}}
+
+    def test_execute_post_adds_content_type_when_json_provided(
+        self,
+        client: ClientRest,
+        mock_httpx_client: tuple[MagicMock, MagicMock],
+    ) -> None:
+        mock_client, _ = mock_httpx_client
+        payload = {"pagetitle": "Ma page"}
+
+        client.execute(
+            HTTPMethod.POST,
+            "/rest/tools/resource",
+            json=payload,
+        )
+
+        expected_headers = {
+            **client.headers,
+            "Content-Type": "application/json",
+        }
+        mock_client.post.assert_called_once_with(
+            "https://api.example.com/rest/tools/resource",
+            headers=expected_headers,
+            json=payload,
+        )
+
+    def test_execute_put(
+        self,
+        client: ClientRest,
+        mock_httpx_client: tuple[MagicMock, MagicMock],
+    ) -> None:
+        mock_client, _ = mock_httpx_client
+        payload = {"id": 10000, "pagetitle": "Updated"}
+
+        client.execute(
+            HTTPMethod.PUT,
+            "/rest/tools/resource",
+            json=payload,
+        )
+
+        expected_headers = {
+            **client.headers,
+            "Content-Type": "application/json",
+        }
+        mock_client.put.assert_called_once_with(
+            "https://api.example.com/rest/tools/resource",
+            headers=expected_headers,
+            json=payload,
+        )
+
+    def test_execute_delete(
+        self,
+        client: ClientRest,
+        mock_httpx_client: tuple[MagicMock, MagicMock],
+    ) -> None:
+        mock_client, _ = mock_httpx_client
+
+        client.execute(HTTPMethod.DELETE, "/rest/tools/resource")
+
+        mock_client.delete.assert_called_once_with(
+            "https://api.example.com/rest/tools/resource",
+            headers=client.headers,
+        )
+
+
+class TestExecuteErrors:
+    def test_execute_raises_on_server_http_error(
+        self,
+        client: ClientRest,
+        mock_httpx_client: tuple[MagicMock, MagicMock],
+    ) -> None:
+        _, mock_response = mock_httpx_client
+        mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
+            "Server Error",
+            request=httpx.Request("GET", "https://api.example.com/rest/tools/resource"),
+            response=httpx.Response(500, request=httpx.Request("GET", "https://example.com")),
+        )
+
+        with pytest.raises(httpx.HTTPStatusError):
+            client.execute(HTTPMethod.GET, "/rest/tools/resource")
+
+    def test_execute_raises_timeout_error(
+        self,
+        client: ClientRest,
+    ) -> None:
+        with patch("src.services.client_rest.httpx.Client") as client_cls:
+            mock_client = MagicMock()
+            mock_client.get.side_effect = httpx.TimeoutException("timed out")
+            client_cls.return_value.__enter__.return_value = mock_client
+
+            with pytest.raises(TimeoutError, match="Timeout lors de l'exécution"):
+                client.execute(HTTPMethod.GET, "/rest/tools/resource")
+
+    def test_execute_raises_on_invalid_http_method(
+        self,
+        client: ClientRest,
+        mock_httpx_client: tuple[MagicMock, MagicMock],
+    ) -> None:
+        mock_client, _ = mock_httpx_client
+
+        with pytest.raises(ValueError, match="Methode HTTP non supportee: PATCH"):
+            client.execute("PATCH", "/rest/tools/resource")  # type: ignore[arg-type]
+
+        mock_client.get.assert_not_called()
+        mock_client.post.assert_not_called()
+        mock_client.put.assert_not_called()
+        mock_client.delete.assert_not_called()

+ 72 - 0
tests/test_initialization.py

@@ -0,0 +1,72 @@
+"""Tests pour src.config.initialization."""
+
+from __future__ import annotations
+
+import pytest
+
+from src.config.initialization import InitializationError, Settings, get_settings
+
+_ENV_KEYS = ("BASE_URL", "LWE_TOKEN", "PHPSESSID")
+
+
+@pytest.fixture(autouse=True)
+def _reset_settings_cache() -> None:
+    get_settings.cache_clear()
+    yield
+    get_settings.cache_clear()
+
+
+@pytest.fixture
+def isolated_env(monkeypatch: pytest.MonkeyPatch) -> None:
+    """Empeche le chargement du .env local et nettoie les variables."""
+    for key in _ENV_KEYS:
+        monkeypatch.delenv(key, raising=False)
+    monkeypatch.setattr(
+        "src.config.initialization.load_dotenv",
+        lambda *_args, **_kwargs: False,
+    )
+
+
+def test_get_settings_with_all_environment_variables(
+    isolated_env: None,
+    monkeypatch: pytest.MonkeyPatch,
+) -> None:
+    monkeypatch.setenv("BASE_URL", "https://api.example.com/")
+    monkeypatch.setenv("LWE_TOKEN", "lwe_tok_abc123")
+    monkeypatch.setenv("PHPSESSID", "sess_xyz789")
+
+    settings = get_settings()
+
+    assert settings == Settings(
+        base_url="https://api.example.com",
+        lwe_token="lwe_tok_abc123",
+        phpsessid="sess_xyz789",
+    )
+
+
+def test_get_settings_raises_when_environment_variables_are_missing(
+    isolated_env: None,
+    monkeypatch: pytest.MonkeyPatch,
+) -> None:
+    monkeypatch.setenv("BASE_URL", "https://api.example.com")
+
+    with pytest.raises(InitializationError) as exc_info:
+        get_settings()
+
+    message = str(exc_info.value)
+    assert "Variables d'environnement manquantes" in message
+    assert "LWE_TOKEN" in message
+    assert "PHPSESSID" in message
+
+
+def test_get_settings_raises_when_env_file_is_missing(
+    isolated_env: None,
+) -> None:
+    with pytest.raises(InitializationError) as exc_info:
+        get_settings()
+
+    message = str(exc_info.value)
+    assert "Variables d'environnement manquantes" in message
+    assert "BASE_URL" in message
+    assert "LWE_TOKEN" in message
+    assert "PHPSESSID" in message