Example #1
0
async def test_view_conf(tmp_path, run_gui, gui_conf, gui_port, event_process,
                         conf_format):

    schema = {"$schema": "http://json-schema.org/schema#",
              "id":  f"test://views/view1.{conf_format}#",
              "type": "object",
              "required": ['x', 'y'],
              "properties": {'x': {"type": 'number'},
                             'y': {"type": 'string'}}
              }
    view_conf = {"x": 2,
                 "y": 'a'}
    views = [View(name='view1', path='views/view1',
                  file_data={'view1': 'this is view1',
                             f'schema.{conf_format}': json.encode(schema),
                             f'conf.{conf_format}': json.encode(view_conf)},
                  conf_path=f'views/view1/conf.{conf_format}')]
    gui_conf = add_adapters_users_roles(gui_conf, tmp_path, no_users_roles=1,
                                        views=views)
    gui_process = run_gui(gui_conf)
    wait_until(gui_process.listens_on, gui_port)

    user_conf = gui_conf['users'][0]
    client = await create_client(gui_conf, user_conf)
    await client.receive()

    await client.login()
    msg = await client.receive()
    assert msg['user'] == 'user1'
    assert set(views[0].file_data.keys()) == set(msg['view'].keys())
    assert msg['view'][f'schema.{conf_format}'] == schema
    assert msg['view'][f'conf.{conf_format}'] == view_conf

    await client.async_close()
    gui_process.close_and_wait_or_kill()
Example #2
0
def _record_to_msg(record):
    exc_info = ''
    with contextlib.suppress(Exception):
        if record.exc_info:
            exc_info = ''.join(
                traceback.TracebackException(*record.exc_info).format())
    return common.Msg(
        facility=common.Facility.USER,
        severity={
            logging.NOTSET: common.Severity.INFORMATIONAL,
            logging.DEBUG: common.Severity.DEBUG,
            logging.INFO: common.Severity.INFORMATIONAL,
            logging.WARNING: common.Severity.WARNING,
            logging.ERROR: common.Severity.ERROR,
            logging.CRITICAL: common.Severity.CRITICAL}[record.levelno],
        version=1,
        timestamp=record.created,
        hostname=socket.gethostname(),
        app_name=sys.argv[0],  # record.processName
        procid=str(record.process) if record.process else None,
        msgid=record.name[:32],
        data=json.encode({
            'hat@1': {
                'name': str(record.name),
                'thread': str(record.thread),
                'funcName': str(record.funcName),
                'lineno': str(record.lineno),
                'exc_info': exc_info}}),
        msg=record.getMessage())
Example #3
0
def event_payload_to_sbs(payload: EventPayload) -> sbs.Data:
    """Convert EventPayload to SBS data"""
    if payload.type == EventPayloadType.BINARY:
        return 'binary', payload.data

    if payload.type == EventPayloadType.JSON:
        return 'json', json.encode(payload.data)

    if payload.type == EventPayloadType.SBS:
        return 'sbs', _sbs_data_to_sbs(payload.data)

    raise ValueError('unsupported payload type')
Example #4
0
    async def add_event_type_mappings(self, mappings):
        """See :meth:`common.EventTypeRegistryStorage.add_event_type_mappings`"""  # NOQA
        labels = ['event_type_id', 'event_type']
        sql = "INSERT INTO mappings ({columns}) VALUES({values})".format(
            columns=', '.join(labels),
            values=', '.join(f':{label}' for label in labels))
        params = [{
            'event_type_id': event_type_id,
            'event_type': json.encode(list(event_type))
        } for event_type_id, event_type in mappings.items()]

        async with self._conn.transaction():
            await self._conn.execute_many(sql, params)
Example #5
0
async def test_invalid_client_message(server_address, tmpdir):
    server = await create_server(server_address, tmpdir, [])

    async with aiohttp.ClientSession() as session:
        async with session.ws_connect(server_address + '/ws') as ws:
            await ws.send_bytes(b'123')
            while not ws.closed:
                await ws.receive()

    async with aiohttp.ClientSession() as session:
        async with session.ws_connect(server_address + '/ws') as ws:
            await ws.send_str(json.encode({'type': 'invalid'}))
            while not ws.closed:
                await ws.receive()

    async with aiohttp.ClientSession() as session:
        async with session.ws_connect(server_address + '/ws') as ws:
            await ws.send_str(json.encode({'type': 'start', 'id': 'invalid'}))
            while not ws.closed:
                await ws.receive()

    await server.async_close()
Example #6
0
def _create_dropped_msg(dropped, func_name, lineno):
    return common.Msg(
        facility=common.Facility.USER,
        severity=common.Severity.ERROR,
        version=1,
        timestamp=datetime.datetime.now(datetime.timezone.utc).timestamp(),
        hostname=socket.gethostname(),
        app_name=sys.argv[0],  # record.processName
        procid=str(os.getpid()),
        msgid=__name__,
        data=json.encode({
            'hat@1': {
                'name': __name__,
                'thread': str(threading.get_ident()),
                'funcName': str(func_name),
                'lineno': str(lineno),
                'exc_info': ''}}),
        msg=f'dropped {dropped} log messages')
Example #7
0
def encode_tuple_str(x: typing.Tuple[str, ...]) -> bytes:
    return encode_str(json.encode(list(x)))
Example #8
0
def encode_json(x: json.Data) -> bytes:
    return encode_str(json.encode(x))
Example #9
0
        procid=None,
        msgid=None,
        data=None,
        msg=None),
    common.Msg(
        facility=common.Facility.USER,
        severity=common.Severity.DEBUG,
        version=1,
        timestamp=datetime.datetime.now(tz=datetime.timezone.utc).timestamp(),
        hostname='abc1',
        app_name='abc2',
        procid='abc3',
        msgid='abc4',
        data=json.encode({'xyz@1': {'a': 'b',
                                    'd': 'e',
                                    'f': '"]\\\\',
                                    'g': ''},
                          'abc@1': {}}),
        msg='abcabcabcabc')]

invalid_msgs = [
    common.Msg(
        facility=None,
        severity=None,
        version=None,
        timestamp=None,
        hostname=None,
        app_name=None,
        procid=None,
        msgid=None,
        data=None,
Example #10
0
def test_encode_decode(format, indent, data):
    encoded = json.encode(data, format, indent)
    decoded = json.decode(encoded, format)
    assert data == decoded