Example #1
0
def test_to_json_invalid_types():
    with pytest.raises(ValueError):
        Json.to_json(
            MockData(id=42, value='ok-value', nested=MockNested(ts=datetime.now(tz=timezone.utc))))  # type: ignore

    with pytest.raises(ValueError):
        Json.to_json(MockData(id='1', value='ok-value', nested=MockNested(ts="NOT A DATETIME")))  # type: ignore
Example #2
0
def test_to_json_dataobject():
    assert Json.to_json(MockData(
        id='test',
        value='ok',
        nested=MockNested(
            ts=datetime.fromtimestamp(0, tz=timezone.utc)
        )
    )) == '{"id": "test", "value": "ok", "nested": {"ts": "1970-01-01T00:00:00+00:00"}}'
Example #3
0
def _ignored_response(context: Optional[EventContext], status: int,
                      e: BaseException) -> web.Response:
    if context:
        logger.error(context, e)
        logger.ignored(context)
    else:
        logger.error(__name__, e)
    info = ErrorInfo.from_exception(e)
    return web.Response(status=status, body=Json.to_json(info))
Example #4
0
def _failed_response(context: Optional[EventContext],
                     e: Exception) -> web.Response:
    if context:
        logger.error(context, e)
        logger.failed(context)
    else:
        logger.error(__name__, e)
    info = ErrorInfo.from_exception(e)
    return web.Response(status=500, body=Json.to_json(info))
Example #5
0
    async def store(self, key: str, value: DataObject):
        """
        Stores value under specified key

        :param key: str
        :param value: DataObject, instance of dataclass annotated with @dataobject
        """
        assert self._conn
        payload_str = str(Json.to_json(value))
        await self._conn.set(key, payload_str)
Example #6
0
    async def store(self, key: str, value: DataObject) -> str:
        """
        Stores value under specified key

        :param key: str
        :param value: DataObject, instance of dataclass annotated with @dataobject
        :return: str, path where the object was stored
        """
        payload_str = Json.to_json(value)
        return await self._save_file(payload_str,
                                     path=self.path,
                                     file_name=key + SUFFIX)
Example #7
0
def test_to_json_dict_mixed():
    assert json.loads(Json.to_json({
        "item1": {
            'item': 1,
            'data': MockData(id='1', value='ok-1', nested=MockNested(ts=datetime.fromtimestamp(0, tz=timezone.utc)))
        },
        "item2": {
            'item': 2,
            'data': MockData(id='2', value='ok-2', nested=MockNested(ts=datetime.fromtimestamp(0, tz=timezone.utc)))
        }
    })) == {'item1': {'data': {'id': '1',
                               'nested': {'ts': '1970-01-01T00:00:00+00:00'},
                               'value': 'ok-1'},
                      'item': 1},
            'item2': {'data': {'id': '2',
                               'nested': {'ts': '1970-01-01T00:00:00+00:00'},
                               'value': 'ok-2'},
                      'item': 2}}
Example #8
0
def _application_json_response(result: DataObject, key: str, *args,
                               **kwargs) -> str:
    return Json.to_json(result, key=key)
Example #9
0
def test_to_json_dataobject_do_not_validate():
    data = MockDataDoNotValidate(id='test', value='not-ok')  # type: ignore
    assert Json.to_json(data) == '{"id": "test", "value": "not-ok"}'
Example #10
0
def test_to_json_dataobject_validate():
    data = MockDataValidate(id='test', value='not-ok')  # type: ignore
    with pytest.raises(ValueError):
        Json.to_json(data)
Example #11
0
def test_to_json_dict_dataobject():
    assert json.loads(Json.to_json({
        'item1': MockData(id='1', value='ok-1', nested=MockNested(ts=datetime.fromtimestamp(0, tz=timezone.utc))),
        'item2': MockData(id='2', value='ok-2', nested=MockNested(ts=datetime.fromtimestamp(0, tz=timezone.utc))),
    })) == {"item1": {"id": "1", "value": "ok-1", "nested": {"ts": "1970-01-01T00:00:00+00:00"}},
            "item2": {"id": "2", "value": "ok-2", "nested": {"ts": "1970-01-01T00:00:00+00:00"}}}
Example #12
0
def test_to_json_list_dataobject():
    assert json.loads(Json.to_json([
        MockData(id='1', value='ok-1', nested=MockNested(ts=datetime.fromtimestamp(0, tz=timezone.utc))),
        MockData(id='2', value='ok-2', nested=MockNested(ts=datetime.fromtimestamp(0, tz=timezone.utc))),
    ])) == [{"id": "1", "value": "ok-1", "nested": {"ts": "1970-01-01T00:00:00+00:00"}},
            {"id": "2", "value": "ok-2", "nested": {"ts": "1970-01-01T00:00:00+00:00"}}]
Example #13
0
def test_to_json_python_types():
    assert Json.to_json('str', key=None) == '"str"'
    assert Json.to_json(123, key=None) == '123'
    assert Json.to_json(123.45, key=None) == '123.45'
    assert Json.to_json(True, key=None) == 'true'
    assert Json.to_json('str', key='test') == '{"test": "str"}'
    assert Json.to_json(123, key='test') == '{"test": 123}'
    assert Json.to_json(123.45, key='test') == '{"test": 123.45}'
    assert Json.to_json(True, key='test') == '{"test": true}'
    assert Json.to_json({'test': 'dict'}) == '{"test": "dict"}'
    assert set(json.loads(Json.to_json({'test2', 'test1'}))) == {"test1", "test2"}
    assert Json.to_json(['test1', 'test2']) == '["test1", "test2"]'
Example #14
0
def _ser_json_utf8(data: EventPayload, level: int) -> bytes:
    return Json.to_json(data).encode('utf-8')
Example #15
0
async def store_item():
    redis = await RedisStorage().connect(address=test_url)
    await redis.store(test_key, test_redis)
    assert redis._conn.last_key == test_key
    assert redis._conn.last_payload == Json.to_json(test_redis)