diff --git a/synse_server/api/http.py b/synse_server/api/http.py index 8de73fa5..e057156f 100644 --- a/synse_server/api/http.py +++ b/synse_server/api/http.py @@ -611,7 +611,39 @@ async def device(request: Request, device_id: str) -> HTTPResponse: * 500: Catchall processing error """ if request.method == 'GET': - return await read_device(request, device_id) + try: + return utils.http_json_response( + await cmd.read_device(device_id), + ) + except Exception: + logger.exception('failed to read device', id=device_id) + raise else: - return await sync_write(request, device_id) + try: + data = request.json + except Exception as e: + raise errors.InvalidUsage( + 'invalid json: unable to parse POSTed body as JSON' + ) from e + + # Validate that the incoming payload has an 'action' field defined. This + # field is required. All other fields are optional. + if isinstance(data, dict): + data = [data] + for item in data: + if 'action' not in item: + raise errors.InvalidUsage( + 'invalid json: key "action" is required in payload, but not found' + ) + + try: + return utils.http_json_response( + await cmd.write_sync( + device_id=device_id, + payload=data, + ), + ) + except Exception: + logger.exception('failed to write synchronously', id=device_id, payload=data) + raise diff --git a/synse_server/app.py b/synse_server/app.py index 1bb53e96..ab46988c 100644 --- a/synse_server/app.py +++ b/synse_server/app.py @@ -58,18 +58,6 @@ def on_response(request: Request, response: HTTPResponse) -> None: ) - -# def new_app(name=None) -> Sanic: -# """Create a new instance of the Synse Server Sanic application. -# -# Args: -# name: Name of the application. This allows tests to create application -# instances with different names. -# -# Returns: -# A Sanic application for Synse Server. -# """ - app = Sanic( name='synse-server', error_handler=errors.SynseErrorHandler(), @@ -91,7 +79,3 @@ def on_response(request: Request, response: HTTPResponse) -> None: # Register middleware with the application. app.register_middleware(on_request, 'request') app.register_middleware(on_response, 'response') - - # return app - - diff --git a/tests/unit/api/test_http.py b/tests/unit/api/test_http.py index ed117750..a6ab4640 100644 --- a/tests/unit/api/test_http.py +++ b/tests/unit/api/test_http.py @@ -1160,7 +1160,8 @@ def test_invalid_multiple_end(self, synse_app): with asynctest.patch('synse_server.cmd.read_cache') as mock_cmd: mock_cmd.side_effect = errors.InvalidUsage('invalid: end') - _, resp = synse_app.test_client.get('/v3/readcache?end=123&end=321', gather_request=False) + _, resp = synse_app.test_client.get( + '/v3/readcache?end=123&end=321', gather_request=False) assert resp.status == 400 assert resp.headers['Content-Type'] == 'application/json' @@ -1940,7 +1941,8 @@ def test_enumerate_invalid_multiple_ns(self, synse_app): def test_enumerate_invalid_multiple_sort(self, synse_app): with asynctest.patch('synse_server.cmd.scan') as mock_cmd: - _, resp = synse_app.test_client.get('/v3/device?sort=id&sort=type', gather_request=False) + _, resp = synse_app.test_client.get( + '/v3/device?sort=id&sort=type', gather_request=False) assert resp.status == 400 assert resp.headers['Content-Type'] == 'application/json' @@ -2247,7 +2249,7 @@ def test_write_ok(self, synse_app): data=ujson.dumps({'action': 'foo', 'data': 'bar'}), gather_request=False, ) - assert resp.status == 200 + assert resp.status == 200, resp.body assert resp.headers['Content-Type'] == 'application/json' body = ujson.loads(resp.body) diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index ae6f070e..ac6301c3 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -1,12 +1,11 @@ """Fixture definitions for Synse Server unit tests.""" - import datetime import logging import asynctest import pytest -from synse_grpc import api, client from sanic_testing import TestManager +from synse_grpc import api, client from synse_server import app, cache, plugin, utils diff --git a/tests/unit/test_app.py b/tests/unit/test_app.py index 3017c6e9..84744d1b 100644 --- a/tests/unit/test_app.py +++ b/tests/unit/test_app.py @@ -30,13 +30,13 @@ class MockRequest: contextvars.bind_contextvars( request_id='test-request', ) - ctx = contextvars._get_context() - assert 'test-request' == ctx.get('request_id') + ctx = contextvars._CONTEXT_VARS + assert 'test-request' == ctx['structlog_request_id'].get() app.on_response(req, resp) - ctx = contextvars._get_context() - assert ctx.get('request_id') is None + ctx = contextvars._CONTEXT_VARS + assert ctx['structlog_request_id'].get() is Ellipsis def test_on_response_streaming_http_response(): @@ -50,10 +50,10 @@ class MockRequest: contextvars.bind_contextvars( request_id='test-request', ) - ctx = contextvars._get_context() - assert 'test-request' == ctx.get('request_id') + ctx = contextvars._CONTEXT_VARS + assert 'test-request' == ctx['structlog_request_id'].get() app.on_response(req, resp) - ctx = contextvars._get_context() - assert ctx.get('request_id') is None + ctx = contextvars._CONTEXT_VARS + assert ctx['structlog_request_id'].get() is Ellipsis diff --git a/tests/unit/test_server.py b/tests/unit/test_server.py index 249fff28..6d23f0f2 100644 --- a/tests/unit/test_server.py +++ b/tests/unit/test_server.py @@ -41,10 +41,12 @@ def test_initialize(self, mock_reload, mock_logger, mock_mkdirs): @mock.patch('sys.stdout.write') def test_run_ok_with_metrics(self, mock_write, mock_ruc, mock_run, mock_init): synse = server.Synse() - assert 'metrics' not in synse.app.router.routes_names.keys() + + assert ('metrics',) not in synse.app.router.routes_all synse.run() - assert 'metrics' in synse.app.router.routes_names.keys() + + assert ('metrics',) in synse.app.router.routes_all mock_write.assert_called_once() mock_init.assert_called_once()