-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #16 from City-of-Helsinki/feature/add-cesvanoise
Feature/add cesvanoise
- Loading branch information
Showing
6 changed files
with
182 additions
and
74 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
import logging | ||
import os | ||
from typing import Tuple, Union | ||
import json | ||
|
||
from .. import AsyncRequestHandler | ||
|
||
|
||
class RequestHandler(AsyncRequestHandler): | ||
async def validate( | ||
self, request_data: dict, endpoint_data: dict | ||
) -> Tuple[bool, Union[str, None], Union[int, None]]: | ||
""" | ||
Use Starlette request_data here to determine should we accept or reject | ||
this request | ||
:param request_data: deserialized (FastAPI) Starlette Request | ||
:param endpoint_data: endpoint data from device registry | ||
:return: (bool ok, str error text, int status code) | ||
""" | ||
[status_ok, response_message, status_code] = await super().validate(request_data, endpoint_data) | ||
|
||
if status_ok is False: | ||
return False, response_message, status_code | ||
|
||
try: | ||
# check if device id can be extracted | ||
json.loads(request_data["request"]["body"].decode("utf-8"))["sensors"][0]["sensor"][0:-2] | ||
return True, "Request accepted", 202 | ||
except Exception: | ||
logging.warning("unable to retreive device_id from request body") | ||
return False, "Invalid request, see logs for error", 400 | ||
|
||
async def process_request( | ||
self, | ||
request_data: dict, | ||
endpoint_data: dict, | ||
) -> Tuple[bool, str, Union[str, None], Union[str, dict, list], int]: | ||
auth_ok, response_message, status_code = await self.validate(request_data, endpoint_data) | ||
|
||
logging.info("Validation: {}, {}, {}".format(auth_ok, response_message, status_code)) | ||
if auth_ok: | ||
device_id = json.loads(request_data["request"]["body"].decode("utf-8"))["sensors"][0]["sensor"][0:-2] | ||
topic_name = endpoint_data["kafka_raw_data_topic"] | ||
else: | ||
device_id = None | ||
topic_name = None | ||
return auth_ok, device_id, topic_name, response_message, status_code | ||
|
||
async def get_metadata(self, request_data: dict, device_id: str) -> str: | ||
# TODO: put this function to BaseRequestHandler or remove from endpoint | ||
# (and add to parser) | ||
metadata = "{}" | ||
redis_url = os.getenv("REDIS_URL") | ||
if redis_url is None: | ||
logging.info("No REDIS_URL defined, querying device metadata failed") | ||
return metadata | ||
if device_id is None: | ||
logging.info("No device_id available, querying device metadata failed") | ||
return metadata | ||
if metadata is None: | ||
return "{}" | ||
return metadata |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
import logging | ||
import os | ||
import json | ||
import httpx | ||
|
||
logging.basicConfig(level=logging.INFO) | ||
|
||
API_BASE_URL = os.getenv("API_BASE_URL", "http://localhost:8001") | ||
API_TOKEN = os.getenv("API_TOKEN", "abc123") | ||
|
||
|
||
# query params | ||
PARAMS = {"x-api-key": API_TOKEN} | ||
|
||
# Body | ||
PAYLOAD = { | ||
"sensors": [ | ||
{"sensor": "TA120-T246187-N", "observations": [{"value": "61.2", "timestamp": "24/02/2022T17:45:15UTC"}]}, | ||
{"sensor": "TA120-T246187-O", "observations": [{"value": "false", "timestamp": "24/02/2022T17:45:15UTC"}]}, | ||
{"sensor": "TA120-T246187-U", "observations": [{"value": "false", "timestamp": "24/02/2022T17:45:15UTC"}]}, | ||
{"sensor": "TA120-T246187-M", "observations": [{"value": "77", "timestamp": "24/02/2022T17:45:15UTC"}]}, | ||
{ | ||
"sensor": "TA120-T246187-S", | ||
"observations": [ | ||
{ | ||
"value": "060.6,0,0;060.8,0,0;060.4,0,0;059.9,0,0;059.9,0,0;060.6,0,0; \ | ||
060.7,0,0;060.4,0,0;059.9,0,0;059.9,0,0;060.2,0,0;060.4,0,0;", | ||
"timestamp": "24/02/2022T17:45:15UTC", | ||
} | ||
], | ||
}, | ||
] | ||
} | ||
|
||
|
||
def test_service_up(): | ||
url = API_BASE_URL | ||
resp = httpx.get(url) | ||
assert resp.status_code == 200, "service is up" | ||
assert resp.json()["message"] == "Test ok", "service is up" | ||
|
||
|
||
def test_cesva_endpoint_up(): | ||
url = f"{API_BASE_URL}/api/v1/cesva" | ||
resp = httpx.put(url) | ||
assert resp.status_code == 401, "error: /api/v1/cesva accessible without token" | ||
assert resp.text.startswith( | ||
"Missing or invalid authentication token" | ||
), "error: /api/v1/cesva accessible without token" | ||
|
||
|
||
def test_cesva_endppoint_authenticated_access(): | ||
url = f"{API_BASE_URL}/api/v1/cesva" | ||
payload = PAYLOAD.copy() | ||
params = PARAMS.copy() | ||
|
||
resp = httpx.put(url, params=params, data=json.dumps(payload)) | ||
logging.info(resp.text) | ||
assert resp.status_code in [200, 201, 202], "message forwarded" | ||
params["x-api-key"] = "wrong" | ||
resp = httpx.put(url, params=params, data=payload) | ||
logging.info(resp.text) | ||
assert resp.status_code == 401, "failed as intended" | ||
|
||
|
||
def main(): | ||
# test_service_up() | ||
# test_cesva_endpoint_up() | ||
test_cesva_endppoint_authenticated_access() | ||
|
||
|
||
if __name__ == "__main__": | ||
main() |