Пример #1
0
    async def _receive_loop(self):
        try:
            while True:
                msg_ws = await self._ws.receive()
                if self._ws.closed or msg_ws.type == aiohttp.WSMsgType.CLOSING:
                    break
                if msg_ws.type != aiohttp.WSMsgType.TEXT:
                    raise Exception('unsupported message type')

                msg = json.decode(msg_ws.data)

                if msg['type'] == 'MESSAGE':
                    self._message_queue.put_nowait(msg['payload'])

                elif msg['type'] == 'DATA':
                    self._remote_data = json.patch(self._remote_data,
                                                   msg['payload'])
                    self._remote_change_cbs.notify()

                else:
                    raise Exception("invalid message type")

        except Exception as e:
            mlog.error("juggler receive loop error: %s", e, exc_info=e)

        finally:
            self._async_group.close()
Пример #2
0
async def test_msg(message_queue, logger):
    ts_before = datetime.datetime.now(tz=datetime.timezone.utc).timestamp()
    logger.info('for your information')
    lineno = inspect.currentframe().f_lineno - 1
    ts, msg = await message_queue.get()
    ts_after = datetime.datetime.now(tz=datetime.timezone.utc).timestamp()

    assert ts_before < ts < ts_after
    assert msg.facility == common.Facility.USER
    assert msg.severity == common.Severity.INFORMATIONAL
    assert msg.version == 1
    assert ts_before < msg.timestamp < ts
    assert msg.hostname == socket.gethostname()

    # TODO pytest/__main__.py != pytest/__init__.py
    # assert msg.app_name == pytest.__file__

    assert int(msg.procid) == os.getpid()
    assert msg.msgid == logger.name
    assert msg.msg == 'for your information'

    msg_data = json.decode(msg.data)
    assert msg_data['hat@1']['name'] == logger.name
    assert int(msg_data['hat@1']['thread']) == threading.current_thread().ident
    assert msg_data['hat@1']['funcName'] == 'test_msg'
    assert int(msg_data['hat@1']['lineno']) == lineno
    assert not msg_data['hat@1']['exc_info']
Пример #3
0
async def test_exc_info(message_queue, logger):
    try:
        raise Exception('Exception!')
    except Exception as e:
        logger.error('an exception occured: %s', e, exc_info=e)
        exc_info_exp = traceback.format_exc()
    ts, msg = await message_queue.get()
    msg_data = json.decode(msg.data)
    assert msg_data['hat@1']['exc_info'] == exc_info_exp
    assert msg.msg == 'an exception occured: Exception!'
Пример #4
0
def event_payload_from_sbs(data: sbs.Data) -> EventPayload:
    """Create new EventPayload based on SBS data"""
    data_type, data_data = data

    if data_type == 'binary':
        return EventPayload(type=EventPayloadType.BINARY, data=data_data)

    if data_type == 'json':
        return EventPayload(type=EventPayloadType.JSON,
                            data=json.decode(data_data))

    if data_type == 'sbs':
        return EventPayload(type=EventPayloadType.SBS,
                            data=_sbs_data_from_sbs(data_data))

    raise ValueError('unsupported payload type')
Пример #5
0
def _register_event_from_lines(event_type_line, source_timestamp,
                               payload_lines):
    event_type = _parse_event_type(event_type_line[:-1])

    payload_str = '\n'.join(payload_lines)
    if payload_str and not payload_str.isspace():
        payload = hat.event.common.EventPayload(
            type=hat.event.common.EventPayloadType.JSON,
            data=json.decode(payload_str, json.Format.YAML))
    else:
        payload = None

    return hat.event.common.RegisterEvent(
        event_type=event_type,
        source_timestamp=source_timestamp,
        payload=payload)
Пример #6
0
    async def _receive_loop(self):
        try:
            while True:
                msg_ws = await self._ws.receive()
                if self._ws.closed or msg_ws.type == aiohttp.WSMsgType.CLOSING:
                    break
                if msg_ws.type != aiohttp.WSMsgType.TEXT:
                    raise Exception('unsupported message type')

                msg = json.decode(msg_ws.data)

                if 'id' in msg:
                    future = self._result_futures.get(msg['id'])
                    if future and not future.done():
                        future.set_result(msg['result'])

                else:
                    self._event_cbs.notify(msg['method'], msg['params'])

        except Exception as e:
            mlog.error("receive loop error: %s", e, exc_info=e)

        finally:
            self.close()
Пример #7
0
def decode_tuple_str(x: bytes) -> typing.Tuple[str, ...]:
    return tuple(json.decode(decode_str(x)))
Пример #8
0
def decode_json(x: bytes) -> json.Data:
    return json.decode(decode_str(x))
Пример #9
0
 async def get_event_type_mappings(self):
     """See :meth:`common.EventTypeRegistryStorage.get_event_type_mappings`"""  # NOQA
     result = await self._conn.execute("SELECT * FROM mappings")
     return {row[0]: tuple(json.decode(row[1])) for row in result}
Пример #10
0
def test_json_schema_repository_validate_invalid(schemas, schema_id, data):
    repo = json.SchemaRepository(*[json.decode(i, format=json.Format.YAML)
                                   for i in schemas])
    with pytest.raises(Exception):
        repo.validate(schema_id, data)
Пример #11
0
def test_json_schema_repository_validate(schemas, schema_id, data):
    repo = json.SchemaRepository(*[json.decode(i, format=json.Format.YAML)
                                   for i in schemas])
    repo.validate(schema_id, data)
Пример #12
0
def test_schema_repository_init_duplicate_id():
    schema = json.decode("id: 'xyz://abc'", format=json.Format.YAML)
    repo = json.SchemaRepository(schema)
    assert repo.to_json() == json.SchemaRepository(repo, repo).to_json()
    with pytest.raises(Exception):
        json.SchemaRepository(schema, schema)
Пример #13
0
def test_schema_repository_init():
    schema = json.decode("id: 'xyz://abc'", format=json.Format.YAML)
    repo = json.SchemaRepository(schema)
    assert repo.to_json()
Пример #14
0
def test_encode_decode(format, indent, data):
    encoded = json.encode(data, format, indent)
    decoded = json.decode(encoded, format)
    assert data == decoded