| 1 | import json |
| 2 | |
| 3 | from mficlient import client, fake_data |
| 4 | |
| 5 | |
| 6 | class FakeResponse: |
| 7 | def __init__(self, code, data): |
| 8 | self.status_code = code |
| 9 | self._data = data |
| 10 | |
| 11 | def json(self): |
| 12 | return {"data": self._data} |
| 13 | |
| 14 | @property |
| 15 | def text(self): |
| 16 | return self._data |
| 17 | |
| 18 | |
| 19 | class FakeSession: |
| 20 | def __init__(self): |
| 21 | self._status = json.loads(fake_data.FAKE_STATUS) |
| 22 | self._sensors = json.loads(fake_data.FAKE_SENSORS) |
| 23 | |
| 24 | def get(self, url, headers=None, verify=True): |
| 25 | if url.endswith("stat/device"): |
| 26 | return FakeResponse(200, self._status) |
| 27 | elif url.endswith("list/sensors"): |
| 28 | return FakeResponse(200, self._sensors) |
| 29 | else: |
| 30 | raise Exception("Unsupported fake path %s" % url) |
| 31 | |
| 32 | def _do_device(self, data): |
| 33 | cmd = json.loads(data["json"]) |
| 34 | updates = dict(cmd) |
| 35 | ident = updates.pop("sId") |
| 36 | for sensor in self._sensors: |
| 37 | if sensor["_id"] == ident: |
| 38 | sensor.update(updates) |
| 39 | sensor["output"] = float(sensor["val"] > 0) |
| 40 | return FakeResponse(200, self._sensors) |
| 41 | |
| 42 | def post(self, url, data=None, headers=None, verify=True): |
| 43 | if url.endswith("list/sensors"): |
| 44 | return FakeResponse(200, self._sensors) |
| 45 | elif url.endswith("cmd/devmgr"): |
| 46 | return self._do_device(data) |
| 47 | |
| 48 | |
| 49 | class FakeMFiClient(client.MFiClient): |
| 50 | def __init__(self, *args, **kwargs): |
| 51 | if not args: |
| 52 | args = ("fakehost", "fakeuser", "fakepass") |
| 53 | super().__init__(*args, **kwargs) |
| 54 | self._session = FakeSession() |
| 55 | |
| 56 | def _login(self): |
| 57 | pass |