pyemoncms 0.1.2__tar.gz → 0.1.4__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/PKG-INFO +21 -1
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/README.md +20 -0
- pyemoncms-0.1.4/pyemoncms/__init__.py +14 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyemoncms/emoncms_client.py +64 -23
- pyemoncms-0.1.4/pyemoncms/py.typed +0 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyemoncms.egg-info/PKG-INFO +21 -1
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyemoncms.egg-info/SOURCES.txt +1 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/setup.py +2 -1
- pyemoncms-0.1.4/tests/test_async_request.py +133 -0
- pyemoncms-0.1.2/pyemoncms/__init__.py +0 -2
- pyemoncms-0.1.2/tests/test_async_request.py +0 -73
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/LICENSE +0 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyemoncms.egg-info/dependency_links.txt +0 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyemoncms.egg-info/requires.txt +0 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyemoncms.egg-info/top_level.txt +0 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/pyproject.toml +0 -0
- {pyemoncms-0.1.2 → pyemoncms-0.1.4}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyemoncms
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: A python library to interrogate emoncms API
|
|
5
5
|
Home-page: https://github.com/Open-Building-Management/pyemoncms
|
|
6
6
|
Author: Alexandre CUER
|
|
@@ -39,6 +39,7 @@ import logging
|
|
|
39
39
|
import asyncio
|
|
40
40
|
from pyemoncms import EmoncmsClient
|
|
41
41
|
|
|
42
|
+
logging.basicConfig()
|
|
42
43
|
key = "your32bitsAPIkey"
|
|
43
44
|
url = "http://url:8081"
|
|
44
45
|
client = EmoncmsClient(url, key, request_timeout=1)
|
|
@@ -82,3 +83,22 @@ async def main():
|
|
|
82
83
|
if __name__ == "__main__":
|
|
83
84
|
asyncio.run(main())
|
|
84
85
|
```
|
|
86
|
+
|
|
87
|
+
## error handling
|
|
88
|
+
|
|
89
|
+
By default, failures are returned as `{"success": False, "message": "..."}`
|
|
90
|
+
(or `None` from the helpers). Pass `raise_errors=True` to get exceptions instead :
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
from pyemoncms import EmoncmsAuthError, EmoncmsClient, EmoncmsConnectionError, EmoncmsError
|
|
94
|
+
|
|
95
|
+
client = EmoncmsClient(url, key, raise_errors=True)
|
|
96
|
+
try:
|
|
97
|
+
feeds = await client.async_list_feeds()
|
|
98
|
+
except EmoncmsAuthError:
|
|
99
|
+
... # invalid API key (HTTP 401)
|
|
100
|
+
except EmoncmsConnectionError:
|
|
101
|
+
... # timeout or server unreachable
|
|
102
|
+
except EmoncmsError:
|
|
103
|
+
... # any other error response
|
|
104
|
+
```
|
|
@@ -12,6 +12,7 @@ import logging
|
|
|
12
12
|
import asyncio
|
|
13
13
|
from pyemoncms import EmoncmsClient
|
|
14
14
|
|
|
15
|
+
logging.basicConfig()
|
|
15
16
|
key = "your32bitsAPIkey"
|
|
16
17
|
url = "http://url:8081"
|
|
17
18
|
client = EmoncmsClient(url, key, request_timeout=1)
|
|
@@ -55,3 +56,22 @@ async def main():
|
|
|
55
56
|
if __name__ == "__main__":
|
|
56
57
|
asyncio.run(main())
|
|
57
58
|
```
|
|
59
|
+
|
|
60
|
+
## error handling
|
|
61
|
+
|
|
62
|
+
By default, failures are returned as `{"success": False, "message": "..."}`
|
|
63
|
+
(or `None` from the helpers). Pass `raise_errors=True` to get exceptions instead :
|
|
64
|
+
|
|
65
|
+
```
|
|
66
|
+
from pyemoncms import EmoncmsAuthError, EmoncmsClient, EmoncmsConnectionError, EmoncmsError
|
|
67
|
+
|
|
68
|
+
client = EmoncmsClient(url, key, raise_errors=True)
|
|
69
|
+
try:
|
|
70
|
+
feeds = await client.async_list_feeds()
|
|
71
|
+
except EmoncmsAuthError:
|
|
72
|
+
... # invalid API key (HTTP 401)
|
|
73
|
+
except EmoncmsConnectionError:
|
|
74
|
+
... # timeout or server unreachable
|
|
75
|
+
except EmoncmsError:
|
|
76
|
+
... # any other error response
|
|
77
|
+
```
|
|
@@ -12,13 +12,15 @@ an inexisting json route responds by false which is not a json object
|
|
|
12
12
|
so there is a type error if you search for a key in the response
|
|
13
13
|
"""
|
|
14
14
|
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
15
17
|
import asyncio
|
|
16
18
|
from dataclasses import dataclass
|
|
17
19
|
import json
|
|
18
20
|
import logging
|
|
19
|
-
from typing import Any, Dict, TypeVar, Optional
|
|
21
|
+
from typing import Any, Dict, TypeVar, Optional, cast
|
|
20
22
|
|
|
21
|
-
from aiohttp import ClientError, ClientSession
|
|
23
|
+
from aiohttp import ClientError, ClientSession, ClientTimeout
|
|
22
24
|
|
|
23
25
|
HTTP_STATUS = {
|
|
24
26
|
400: "invalid request",
|
|
@@ -30,19 +32,31 @@ HTTP_STATUS = {
|
|
|
30
32
|
MESSAGE_KEY = "message"
|
|
31
33
|
SUCCESS_KEY = "success"
|
|
32
34
|
|
|
33
|
-
logging.basicConfig()
|
|
34
|
-
|
|
35
35
|
Self = TypeVar("Self", bound="EmoncmsClient")
|
|
36
36
|
|
|
37
|
+
|
|
38
|
+
class EmoncmsError(Exception):
|
|
39
|
+
"""Generic emoncms error."""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class EmoncmsAuthError(EmoncmsError):
|
|
43
|
+
"""Invalid API key (HTTP 401)."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class EmoncmsConnectionError(EmoncmsError):
|
|
47
|
+
"""Emoncms server unreachable or timed out."""
|
|
48
|
+
|
|
49
|
+
|
|
37
50
|
@dataclass
|
|
38
51
|
class EmoncmsClient:
|
|
39
52
|
"""Emoncms client."""
|
|
40
53
|
|
|
41
|
-
url: str =
|
|
42
|
-
api_key: str = None
|
|
54
|
+
url: str = ""
|
|
55
|
+
api_key: str | None = None
|
|
43
56
|
request_timeout: int = 20
|
|
44
57
|
session: ClientSession | None = None
|
|
45
58
|
_close_session: bool = False
|
|
59
|
+
raise_errors: bool = False
|
|
46
60
|
logger = logging.getLogger(__name__)
|
|
47
61
|
|
|
48
62
|
async def async_request(
|
|
@@ -51,7 +65,7 @@ class EmoncmsClient:
|
|
|
51
65
|
"""Request emoncms server."""
|
|
52
66
|
message = f"requesting emoncms on {path}"
|
|
53
67
|
self.logger.debug(message)
|
|
54
|
-
data = {SUCCESS_KEY: False, MESSAGE_KEY: None}
|
|
68
|
+
data: dict[str, Any] = {SUCCESS_KEY: False, MESSAGE_KEY: None}
|
|
55
69
|
if not params:
|
|
56
70
|
params = {"apikey": self.api_key}
|
|
57
71
|
if self.session is None:
|
|
@@ -61,17 +75,21 @@ class EmoncmsClient:
|
|
|
61
75
|
url= f'{self.url}/{path}'
|
|
62
76
|
try:
|
|
63
77
|
response = await self.session.get(
|
|
64
|
-
url, timeout=self.request_timeout, params=params
|
|
78
|
+
url, timeout=ClientTimeout(total=self.request_timeout), params=params
|
|
65
79
|
)
|
|
66
80
|
except ClientError as er:
|
|
67
81
|
message = f"client error : {er}"
|
|
68
82
|
data[MESSAGE_KEY] = message
|
|
69
|
-
self.
|
|
83
|
+
self._log_error(message)
|
|
84
|
+
if self.raise_errors:
|
|
85
|
+
raise EmoncmsConnectionError(message) from er
|
|
70
86
|
return data
|
|
71
|
-
except asyncio.TimeoutError:
|
|
87
|
+
except asyncio.TimeoutError as er:
|
|
72
88
|
message = "time out error"
|
|
73
89
|
data[MESSAGE_KEY] = message
|
|
74
|
-
self.
|
|
90
|
+
self._log_error(message)
|
|
91
|
+
if self.raise_errors:
|
|
92
|
+
raise EmoncmsConnectionError(message) from er
|
|
75
93
|
return data
|
|
76
94
|
if response.status == 200:
|
|
77
95
|
data[SUCCESS_KEY] = True
|
|
@@ -82,9 +100,22 @@ class EmoncmsClient:
|
|
|
82
100
|
if response.status in HTTP_STATUS:
|
|
83
101
|
message = f"{message} {HTTP_STATUS[response.status]}"
|
|
84
102
|
data[MESSAGE_KEY] = message
|
|
85
|
-
self.
|
|
103
|
+
self._log_error(message)
|
|
104
|
+
self._raise_for_status(response.status, message)
|
|
86
105
|
return data
|
|
87
106
|
|
|
107
|
+
def _log_error(self, message: str) -> None:
|
|
108
|
+
"""Log at debug when raising, the caller decides how to report."""
|
|
109
|
+
self.logger.log(logging.DEBUG if self.raise_errors else logging.ERROR, message)
|
|
110
|
+
|
|
111
|
+
def _raise_for_status(self, status: int, message: str) -> None:
|
|
112
|
+
"""Raise the matching exception when raise_errors is enabled."""
|
|
113
|
+
if not self.raise_errors:
|
|
114
|
+
return
|
|
115
|
+
if status == 401:
|
|
116
|
+
raise EmoncmsAuthError(message)
|
|
117
|
+
raise EmoncmsError(message)
|
|
118
|
+
|
|
88
119
|
async def async_input_post(
|
|
89
120
|
self,
|
|
90
121
|
data: Dict[str, Any],
|
|
@@ -104,17 +135,27 @@ class EmoncmsClient:
|
|
|
104
135
|
if not effective_key:
|
|
105
136
|
raise ValueError("API key must be provided.")
|
|
106
137
|
|
|
107
|
-
params = {"apikey": effective_key, "
|
|
138
|
+
params = {"apikey": effective_key, "fulljson": json_string}
|
|
108
139
|
if node:
|
|
109
140
|
params["node"] = node
|
|
110
141
|
if time is not None:
|
|
111
142
|
params["time"] = str(time)
|
|
112
143
|
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
144
|
+
try:
|
|
145
|
+
async with self.session.post(
|
|
146
|
+
endpoint, params=params, timeout=ClientTimeout(total=self.request_timeout)
|
|
147
|
+
) as resp:
|
|
148
|
+
text = await resp.text()
|
|
149
|
+
status = resp.status
|
|
150
|
+
except (ClientError, asyncio.TimeoutError) as er:
|
|
151
|
+
if self.raise_errors:
|
|
152
|
+
raise EmoncmsConnectionError(f"POST failed : {er!r}") from er
|
|
153
|
+
raise
|
|
154
|
+
if status != 200:
|
|
155
|
+
message = f"POST failed ({status}): {text}"
|
|
156
|
+
self._raise_for_status(status, message)
|
|
157
|
+
raise RuntimeError(message)
|
|
158
|
+
return True
|
|
118
159
|
|
|
119
160
|
async def async_get_uuid(self) -> str | None:
|
|
120
161
|
"""Return the unique identifier or None.
|
|
@@ -127,7 +168,7 @@ class EmoncmsClient:
|
|
|
127
168
|
if json_response is False:
|
|
128
169
|
return None
|
|
129
170
|
if json_response[SUCCESS_KEY]:
|
|
130
|
-
return json_response[MESSAGE_KEY]
|
|
171
|
+
return cast(str, json_response[MESSAGE_KEY])
|
|
131
172
|
message = json_response[MESSAGE_KEY]
|
|
132
173
|
message = f"{message} : {self.url}"
|
|
133
174
|
self.logger.debug(message)
|
|
@@ -137,15 +178,15 @@ class EmoncmsClient:
|
|
|
137
178
|
"""Request emoncms feeds list."""
|
|
138
179
|
feed_data = await self.async_request("/feed/list.json")
|
|
139
180
|
if feed_data[SUCCESS_KEY]:
|
|
140
|
-
return feed_data[MESSAGE_KEY]
|
|
181
|
+
return cast(list[dict[str, Any]], feed_data[MESSAGE_KEY])
|
|
141
182
|
return None
|
|
142
183
|
|
|
143
|
-
async def async_get_feed_fields(self, feed_id: int) ->
|
|
184
|
+
async def async_get_feed_fields(self, feed_id: int) -> dict[str, Any] | None:
|
|
144
185
|
"""Get all fields for a single feed."""
|
|
145
186
|
params = {"apikey": self.api_key, "id": feed_id}
|
|
146
187
|
feed_data = await self.async_request("/feed/aget.json", params=params)
|
|
147
188
|
if feed_data[SUCCESS_KEY]:
|
|
148
|
-
return feed_data[MESSAGE_KEY]
|
|
189
|
+
return cast(dict[str, Any], feed_data[MESSAGE_KEY])
|
|
149
190
|
return None
|
|
150
191
|
|
|
151
192
|
async def close(self) -> None:
|
|
@@ -153,7 +194,7 @@ class EmoncmsClient:
|
|
|
153
194
|
if self.session and self._close_session:
|
|
154
195
|
await self.session.close()
|
|
155
196
|
|
|
156
|
-
async def __aenter__(self) -> Self:
|
|
197
|
+
async def __aenter__(self: Self) -> Self:
|
|
157
198
|
"""Async enter for context manager."""
|
|
158
199
|
return self
|
|
159
200
|
|
|
File without changes
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyemoncms
|
|
3
|
-
Version: 0.1.
|
|
3
|
+
Version: 0.1.4
|
|
4
4
|
Summary: A python library to interrogate emoncms API
|
|
5
5
|
Home-page: https://github.com/Open-Building-Management/pyemoncms
|
|
6
6
|
Author: Alexandre CUER
|
|
@@ -39,6 +39,7 @@ import logging
|
|
|
39
39
|
import asyncio
|
|
40
40
|
from pyemoncms import EmoncmsClient
|
|
41
41
|
|
|
42
|
+
logging.basicConfig()
|
|
42
43
|
key = "your32bitsAPIkey"
|
|
43
44
|
url = "http://url:8081"
|
|
44
45
|
client = EmoncmsClient(url, key, request_timeout=1)
|
|
@@ -82,3 +83,22 @@ async def main():
|
|
|
82
83
|
if __name__ == "__main__":
|
|
83
84
|
asyncio.run(main())
|
|
84
85
|
```
|
|
86
|
+
|
|
87
|
+
## error handling
|
|
88
|
+
|
|
89
|
+
By default, failures are returned as `{"success": False, "message": "..."}`
|
|
90
|
+
(or `None` from the helpers). Pass `raise_errors=True` to get exceptions instead :
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
from pyemoncms import EmoncmsAuthError, EmoncmsClient, EmoncmsConnectionError, EmoncmsError
|
|
94
|
+
|
|
95
|
+
client = EmoncmsClient(url, key, raise_errors=True)
|
|
96
|
+
try:
|
|
97
|
+
feeds = await client.async_list_feeds()
|
|
98
|
+
except EmoncmsAuthError:
|
|
99
|
+
... # invalid API key (HTTP 401)
|
|
100
|
+
except EmoncmsConnectionError:
|
|
101
|
+
... # timeout or server unreachable
|
|
102
|
+
except EmoncmsError:
|
|
103
|
+
... # any other error response
|
|
104
|
+
```
|
|
@@ -6,7 +6,7 @@ with open("README.md", "r", encoding="utf-8") as fh:
|
|
|
6
6
|
|
|
7
7
|
setuptools.setup(
|
|
8
8
|
name="pyemoncms",
|
|
9
|
-
version="0.1.
|
|
9
|
+
version="0.1.4",
|
|
10
10
|
author="Alexandre CUER",
|
|
11
11
|
author_email="alexandre.cuer@wanadoo.fr",
|
|
12
12
|
description="A python library to interrogate emoncms API",
|
|
@@ -22,6 +22,7 @@ setuptools.setup(
|
|
|
22
22
|
"Operating System :: OS Independent",
|
|
23
23
|
],
|
|
24
24
|
packages=setuptools.find_packages(),
|
|
25
|
+
package_data={"pyemoncms": ["py.typed"]},
|
|
25
26
|
install_requires=[
|
|
26
27
|
'aiohttp'
|
|
27
28
|
],
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Tests for async_request method."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from aiohttp import web
|
|
8
|
+
|
|
9
|
+
root_path = os.getcwd()
|
|
10
|
+
sys.path.insert(0, root_path)
|
|
11
|
+
from pyemoncms.emoncms_client import ( # pylint: disable=E0401,C0413
|
|
12
|
+
EmoncmsAuthError,
|
|
13
|
+
EmoncmsClient,
|
|
14
|
+
EmoncmsConnectionError,
|
|
15
|
+
EmoncmsError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
API_KEY = "123"
|
|
19
|
+
|
|
20
|
+
FEED = {
|
|
21
|
+
"id":"1",
|
|
22
|
+
"userid":"1",
|
|
23
|
+
"name":"Cellule_Tcircuit",
|
|
24
|
+
"tag":" sofrel_circuit_Cellule",
|
|
25
|
+
"public":"0",
|
|
26
|
+
"size":"35811340",
|
|
27
|
+
"engine":"5",
|
|
28
|
+
"processList":"",
|
|
29
|
+
"unit":"",
|
|
30
|
+
"time":1665509570,
|
|
31
|
+
"value":17.690000534058
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
FEEDS = [ FEED ]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def feed_list_route(request):
|
|
38
|
+
"""Emoncms feed list route."""
|
|
39
|
+
if "apikey" not in request.query:
|
|
40
|
+
return web.json_response(False)
|
|
41
|
+
if request.query["apikey"] != API_KEY:
|
|
42
|
+
raise web.HTTPUnauthorized(text="Invalid API key")
|
|
43
|
+
return web.json_response(FEEDS)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def input_post_route(request):
|
|
47
|
+
"""Emoncms input post route."""
|
|
48
|
+
if request.query["apikey"] == "500":
|
|
49
|
+
raise web.HTTPInternalServerError(text="boom")
|
|
50
|
+
if request.query["apikey"] != API_KEY:
|
|
51
|
+
raise web.HTTPUnauthorized(text="Invalid API key")
|
|
52
|
+
return web.Response(text="ok")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def create_feed_api():
|
|
56
|
+
"""Emoncms server."""
|
|
57
|
+
app = web.Application()
|
|
58
|
+
app.router.add_route("GET", "/feed/list.json", feed_list_route)
|
|
59
|
+
app.router.add_route("GET", "/user/getuuid.json", feed_list_route)
|
|
60
|
+
app.router.add_route("POST", "/input/post", input_post_route)
|
|
61
|
+
return app
|
|
62
|
+
|
|
63
|
+
async def test_response_ok(aiohttp_server):
|
|
64
|
+
"""Test correct response."""
|
|
65
|
+
await aiohttp_server(create_feed_api(), port=8080)
|
|
66
|
+
client = EmoncmsClient("http://127.0.0.1:8080", API_KEY)
|
|
67
|
+
datas = await client.async_request("/feed/list.json")
|
|
68
|
+
assert FEEDS == datas["message"]
|
|
69
|
+
|
|
70
|
+
async def test_no_api_auth(aiohttp_server):
|
|
71
|
+
"""Test incorrect API key."""
|
|
72
|
+
await aiohttp_server(create_feed_api(), port=8080)
|
|
73
|
+
client = EmoncmsClient("http://127.0.0.1:8080", "666")
|
|
74
|
+
datas = await client.async_request("/feed/list.json")
|
|
75
|
+
assert not datas["success"]
|
|
76
|
+
assert "401" in datas["message"]
|
|
77
|
+
|
|
78
|
+
async def test_timeout():
|
|
79
|
+
"""Test when IP does not exist."""
|
|
80
|
+
client = EmoncmsClient("http://192.16.1.32:8080", API_KEY, request_timeout=1)
|
|
81
|
+
datas = await client.async_request("/feed/list.json")
|
|
82
|
+
assert not datas["success"]
|
|
83
|
+
assert "time out" in datas["message"]
|
|
84
|
+
|
|
85
|
+
async def test_client_error():
|
|
86
|
+
"""Test when IP exists but client not running."""
|
|
87
|
+
client = EmoncmsClient("http://127.0.0.1:8087", API_KEY)
|
|
88
|
+
datas = await client.async_request("/feed/list.json")
|
|
89
|
+
assert not datas["success"]
|
|
90
|
+
assert "client error" in datas["message"]
|
|
91
|
+
|
|
92
|
+
async def test_raise_auth_error(aiohttp_server):
|
|
93
|
+
"""Test incorrect API key raises with raise_errors."""
|
|
94
|
+
await aiohttp_server(create_feed_api(), port=8080)
|
|
95
|
+
client = EmoncmsClient("http://127.0.0.1:8080", "666", raise_errors=True)
|
|
96
|
+
with pytest.raises(EmoncmsAuthError):
|
|
97
|
+
await client.async_list_feeds()
|
|
98
|
+
with pytest.raises(EmoncmsAuthError):
|
|
99
|
+
await client.async_get_uuid()
|
|
100
|
+
await client.close()
|
|
101
|
+
|
|
102
|
+
async def test_raise_timeout():
|
|
103
|
+
"""Test timeout raises with raise_errors."""
|
|
104
|
+
client = EmoncmsClient(
|
|
105
|
+
"http://192.16.1.32:8080", API_KEY, request_timeout=1, raise_errors=True
|
|
106
|
+
)
|
|
107
|
+
with pytest.raises(EmoncmsConnectionError):
|
|
108
|
+
await client.async_request("/feed/list.json")
|
|
109
|
+
await client.close()
|
|
110
|
+
|
|
111
|
+
async def test_raise_client_error(caplog):
|
|
112
|
+
"""Test refused connection raises with raise_errors, without error logs."""
|
|
113
|
+
client = EmoncmsClient("http://127.0.0.1:8087", API_KEY, raise_errors=True)
|
|
114
|
+
with pytest.raises(EmoncmsConnectionError):
|
|
115
|
+
await client.async_request("/feed/list.json")
|
|
116
|
+
with pytest.raises(EmoncmsConnectionError):
|
|
117
|
+
await client.async_input_post({"a": 1})
|
|
118
|
+
await client.close()
|
|
119
|
+
assert not [r for r in caplog.records if r.levelname == "ERROR"]
|
|
120
|
+
|
|
121
|
+
async def test_input_post(aiohttp_server):
|
|
122
|
+
"""Test input post success and errors."""
|
|
123
|
+
await aiohttp_server(create_feed_api(), port=8080)
|
|
124
|
+
url = "http://127.0.0.1:8080"
|
|
125
|
+
async with EmoncmsClient(url, API_KEY, raise_errors=True) as client:
|
|
126
|
+
assert await client.async_input_post({"a": 1})
|
|
127
|
+
with pytest.raises(EmoncmsAuthError):
|
|
128
|
+
await client.async_input_post({"a": 1}, apikey="666")
|
|
129
|
+
with pytest.raises(EmoncmsError):
|
|
130
|
+
await client.async_input_post({"a": 1}, apikey="500")
|
|
131
|
+
async with EmoncmsClient(url, API_KEY) as client:
|
|
132
|
+
with pytest.raises(RuntimeError):
|
|
133
|
+
await client.async_input_post({"a": 1}, apikey="666")
|
|
@@ -1,73 +0,0 @@
|
|
|
1
|
-
"""Tests for async_request method."""
|
|
2
|
-
|
|
3
|
-
import os
|
|
4
|
-
import sys
|
|
5
|
-
|
|
6
|
-
from aiohttp import web
|
|
7
|
-
|
|
8
|
-
root_path = os.getcwd()
|
|
9
|
-
sys.path.insert(0, root_path)
|
|
10
|
-
from pyemoncms.emoncms_client import EmoncmsClient # pylint: disable=E0401,C0413
|
|
11
|
-
|
|
12
|
-
API_KEY = "123"
|
|
13
|
-
|
|
14
|
-
FEED = {
|
|
15
|
-
"id":"1",
|
|
16
|
-
"userid":"1",
|
|
17
|
-
"name":"Cellule_Tcircuit",
|
|
18
|
-
"tag":" sofrel_circuit_Cellule",
|
|
19
|
-
"public":"0",
|
|
20
|
-
"size":"35811340",
|
|
21
|
-
"engine":"5",
|
|
22
|
-
"processList":"",
|
|
23
|
-
"unit":"",
|
|
24
|
-
"time":1665509570,
|
|
25
|
-
"value":17.690000534058
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
FEEDS = [ FEED ]
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
async def feed_list_route(request):
|
|
32
|
-
"""Emoncms feed list route."""
|
|
33
|
-
if "apikey" not in request.query:
|
|
34
|
-
return web.json_response(False)
|
|
35
|
-
if request.query["apikey"] != API_KEY:
|
|
36
|
-
raise web.HTTPUnauthorized(text="Invalid API key")
|
|
37
|
-
return web.json_response(FEEDS)
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
def create_feed_api():
|
|
41
|
-
"""Emoncms server."""
|
|
42
|
-
app = web.Application()
|
|
43
|
-
app.router.add_route("GET", "/feed/list.json", feed_list_route)
|
|
44
|
-
return app
|
|
45
|
-
|
|
46
|
-
async def test_response_ok(aiohttp_server):
|
|
47
|
-
"""Test correct response."""
|
|
48
|
-
await aiohttp_server(create_feed_api(), port=8080)
|
|
49
|
-
client = EmoncmsClient("http://127.0.0.1:8080", API_KEY)
|
|
50
|
-
datas = await client.async_request("/feed/list.json")
|
|
51
|
-
assert FEEDS == datas["message"]
|
|
52
|
-
|
|
53
|
-
async def test_no_api_auth(aiohttp_server):
|
|
54
|
-
"""Test incorrect API key."""
|
|
55
|
-
await aiohttp_server(create_feed_api(), port=8080)
|
|
56
|
-
client = EmoncmsClient("http://127.0.0.1:8080", "666")
|
|
57
|
-
datas = await client.async_request("/feed/list.json")
|
|
58
|
-
assert not datas["success"]
|
|
59
|
-
assert "401" in datas["message"]
|
|
60
|
-
|
|
61
|
-
async def test_timeout():
|
|
62
|
-
"""Test when IP does not exist."""
|
|
63
|
-
client = EmoncmsClient("http://192.16.1.32:8080", API_KEY, request_timeout=1)
|
|
64
|
-
datas = await client.async_request("/feed/list.json")
|
|
65
|
-
assert not datas["success"]
|
|
66
|
-
assert "time out" in datas["message"]
|
|
67
|
-
|
|
68
|
-
async def test_client_error():
|
|
69
|
-
"""Test when IP exists but client not running."""
|
|
70
|
-
client = EmoncmsClient("http://127.0.0.1:8087", API_KEY)
|
|
71
|
-
datas = await client.async_request("/feed/list.json")
|
|
72
|
-
assert not datas["success"]
|
|
73
|
-
assert "client error" in datas["message"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|