|
| 1 | +import pytest |
| 2 | +import requests |
| 3 | +from frost_sta_client.service.sensorthingsservice import SensorThingsService |
| 4 | +from frost_sta_client.model.thing import Thing |
| 5 | + |
| 6 | + |
| 7 | +class MockResponse: |
| 8 | + def __init__(self, status_code=200, json_data=None, headers=None): |
| 9 | + self.status_code = status_code |
| 10 | + self._json = json_data if json_data is not None else {} |
| 11 | + self.headers = headers or {} |
| 12 | + |
| 13 | + def json(self): |
| 14 | + return self._json |
| 15 | + |
| 16 | + def raise_for_status(self): |
| 17 | + if self.status_code >= 400: |
| 18 | + raise requests.exceptions.HTTPError(response=self) |
| 19 | + |
| 20 | + |
| 21 | +class DummyService(SensorThingsService): |
| 22 | + def __init__(self): |
| 23 | + super().__init__('http://example.org/FROST-Server/v1.1') |
| 24 | + self.calls = [] |
| 25 | + |
| 26 | + def execute(self, method, url, **kwargs): |
| 27 | + self.calls.append((method, str(url), kwargs)) |
| 28 | + if method == 'post': |
| 29 | + return MockResponse(201, {}, headers={'location': 'Things(42)'}) |
| 30 | + if method == 'get': |
| 31 | + return MockResponse(200, {"@iot.id": 5, "name": "MyThing"}) |
| 32 | + return MockResponse(200, {}) |
| 33 | + |
| 34 | + |
| 35 | +def test_base_dao_create_sets_id_and_service(): |
| 36 | + svc = DummyService() |
| 37 | + t = Thing(name='X') |
| 38 | + svc.create(t) |
| 39 | + assert t.id == 42 |
| 40 | + assert t.service is svc |
| 41 | + |
| 42 | + |
| 43 | +def test_base_dao_find_returns_entity(): |
| 44 | + svc = DummyService() |
| 45 | + found = svc.things().find(5) |
| 46 | + assert found.id == 5 |
| 47 | + assert found.name == 'MyThing' |
| 48 | + assert found.service is svc |
| 49 | + |
| 50 | + |
| 51 | +def test_base_dao_update_without_id_raises(): |
| 52 | + svc = DummyService() |
| 53 | + t = Thing(name='noid') |
| 54 | + with pytest.raises(AttributeError): |
| 55 | + svc.update(t) |
| 56 | + |
| 57 | + |
| 58 | +def test_base_dao_patch_validates_and_sends_headers(): |
| 59 | + svc = DummyService() |
| 60 | + t = Thing(id=7) |
| 61 | + patches = [{"op": "replace", "path": "/name", "value": "new"}] |
| 62 | + svc.patch(t, patches) |
| 63 | + method, url, kwargs = svc.calls[-1] |
| 64 | + assert method == 'patch' |
| 65 | + assert kwargs['headers']['Content-type'] == 'application/json-patch+json' |
| 66 | + |
| 67 | + |
| 68 | +def test_entity_path_formats_string_and_int(): |
| 69 | + svc = DummyService() |
| 70 | + assert svc.things().entity_path(1) == 'Things(1)' |
| 71 | + assert svc.things().entity_path('abc') == "Things('abc')" |
0 commit comments