|
| 1 | +import json |
| 2 | +import types |
| 3 | +import pytest |
| 4 | + |
| 5 | +import ckan_client |
| 6 | + |
| 7 | + |
| 8 | +class _FakeResponse: |
| 9 | + def __init__(self, data: dict, status_code: int = 200): |
| 10 | + self._data = data |
| 11 | + self.status_code = status_code |
| 12 | + self.text = json.dumps(data) |
| 13 | + |
| 14 | + def json(self): |
| 15 | + return self._data |
| 16 | + |
| 17 | + def raise_for_status(self): |
| 18 | + # Simulate httpx behavior: raise for 4xx/5xx |
| 19 | + if self.status_code >= 400: |
| 20 | + raise ckan_client.httpx.HTTPStatusError( |
| 21 | + "error", request=None, response=self |
| 22 | + ) |
| 23 | + |
| 24 | + |
| 25 | +class _FakeHttpxClientOK: |
| 26 | + """httpx.Client mock that returns success=true with one org.""" |
| 27 | + |
| 28 | + def __init__(self, **kwargs): |
| 29 | + pass |
| 30 | + |
| 31 | + def post(self, url, json=None): |
| 32 | + # Ensure we're calling the expected CKAN action path |
| 33 | + assert url.endswith(ckan_client.CKANClient.ACTION_AUTOREGISTER_ORGS) |
| 34 | + return _FakeResponse( |
| 35 | + { |
| 36 | + "success": True, |
| 37 | + "result": [{"id": "1", "name": "bpa", "title": "Bioplatforms Australia"}], |
| 38 | + } |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +class _FakeHttpxClientSuccessFalse: |
| 43 | + """httpx.Client mock that returns success=false (CKAN action error).""" |
| 44 | + |
| 45 | + def __init__(self, **kwargs): |
| 46 | + pass |
| 47 | + |
| 48 | + def post(self, url, json=None): |
| 49 | + return _FakeResponse({"success": False, "error": {"message": "boom"}}) |
| 50 | + |
| 51 | + |
| 52 | +def test_ckan_client_success(monkeypatch): |
| 53 | + # Replace httpx.Client with our fake |
| 54 | + monkeypatch.setattr( |
| 55 | + ckan_client, "httpx", types.SimpleNamespace(Client=_FakeHttpxClientOK) |
| 56 | + ) |
| 57 | + cli = ckan_client.CKANClient( |
| 58 | + base_url="https://ckan.example.org", |
| 59 | + api_key=None, |
| 60 | + timeout_s=5, |
| 61 | + verify_ssl=True, |
| 62 | + ) |
| 63 | + |
| 64 | + orgs = cli.get_autoregister_organizations() |
| 65 | + assert len(orgs) == 1 |
| 66 | + assert orgs[0].id == "1" |
| 67 | + assert orgs[0].name == "bpa" |
| 68 | + assert orgs[0].title == "Bioplatforms Australia" |
| 69 | + |
| 70 | + |
| 71 | +def test_ckan_client_success_false_raises(monkeypatch): |
| 72 | + monkeypatch.setattr( |
| 73 | + ckan_client, "httpx", types.SimpleNamespace(Client=_FakeHttpxClientSuccessFalse) |
| 74 | + ) |
| 75 | + cli = ckan_client.CKANClient( |
| 76 | + base_url="https://ckan.example.org", |
| 77 | + api_key="secret", |
| 78 | + timeout_s=5, |
| 79 | + verify_ssl=True, |
| 80 | + ) |
| 81 | + |
| 82 | + with pytest.raises(ValueError): |
| 83 | + _ = cli.get_autoregister_organizations() |
0 commit comments