def test_zmq_handler(): ctx = zmq.Context() interface = "tcp://127.0.0.1" with ctx.socket(zmq.PUB) as pub, ctx.socket(zmq.SUB) as sub: sub.setsockopt(zmq.LINGER, 0) pub.setsockopt(zmq.LINGER, 0) port = pub.bind_to_random_port(interface) sub.connect('%s:%s' % (interface, port)) sub.subscribe(b'') time.sleep(0.1) logger = logging.getLogger('qulabtest') logger.setLevel(logging.DEBUG) handler = ZMQHandler(pub) handler.setLevel(logging.DEBUG) logger.addHandler(handler) logger.debug('hello') if sub.poll(100): btopic, bmsg = sub.recv_multipart() record = logging.makeLogRecord(unpack(bmsg)) assert record.msg == 'hello' else: assert False, "ZMQ time out."
def test_BaseHandler(): hdlr = BaseHandler() record = logging.makeLogRecord(dict(name='test', lno=20, msg='hello')) bmsg = hdlr.serialize(record) assert isinstance(bmsg, bytes) record2 = logging.makeLogRecord(unpack(bmsg)) assert record2.name == hdlr.host + '.' + record.name assert record2.msg == record.msg with pytest.raises(NotImplementedError): hdlr.send_bytes(b'')
def on_bmsg(self, msgID, bmsg): if msgID not in self.pending: return fut, timeout = self.pending[msgID] result = unpack(bmsg) timeout.cancel() if isinstance(result, Exception): fut.set_exception(result) else: fut.set_result(result) del self.pending[msgID]
def on_response(self, source, data): """ Client side. """ msgID, msg = data[:20], data[20:] if msgID not in self.pending: return fut, timeout = self.pending[msgID] result = unpack(msg) timeout.cancel() if isinstance(result, Exception): fut.set_exception(result) else: fut.set_result(result) del self.pending[msgID]
async def handle(self, sock, obj, addr, msgID, msg): method, args, kw = unpack(msg) if method == 'rpc_ping': result = True else: try: result = getattr(obj, method)(*args, **kw) if isinstance(result, Awaitable): result = await result except RPCException as e: result = e except Exception as e: result = RPCServerError(*e.args) result = pack(result) await sock.send_multipart([addr, msgID, result])
async def test_redis_handler(event_loop): import redis r = redis.Redis() logger = logging.getLogger('qulabtest2') logger.setLevel(logging.DEBUG) handler = RedisHandler(r) handler.setLevel(logging.DEBUG) logger.addHandler(handler) sub = await aioredis.create_redis('redis://localhost') logChannel, = await sub.subscribe('log') logger.debug('hello') if await logChannel.wait_message(): bmsg = await logChannel.get() record = logging.makeLogRecord(unpack(bmsg)) assert record.msg == 'hello' pass
def _unpack_request(self, msg): try: method, args, kw = unpack(msg) except: raise QuLabRPCError("Could not read packet: %r" % msg) return method, args, kw