def subscribe_test(): # Nothing beyond the base fixture is required for this test. manager = yield From(pygazebo.connect()) print('Pygazebo connected.') received_data = [] first_data_future = trollius.Future() def callback(data): received_data.append(data) if not first_data_future.done(): first_data_future.set_result(None) listen = trollius.Future() manager.server.read_packet(lambda data: listen.set_result(data)) subscriber = manager.manager.subscribe('subscribetopic', 'othermsgtype', callback) assert subscriber is not None print('Before run listen') loop.run_until_complete(listen) print('After run listen') packet_data = listen.result() # We should have received a subscribe for this topic. packet = packet_pb2.Packet.FromString(packet_data) assert packet.type == 'subscribe' subscribe = subscribe_pb2.Subscribe.FromString(packet.serialized_data) assert subscribe.topic == 'subscribetopic' assert subscribe.msg_type == 'othermsgtype'
def test_default_exc_handler_callback(self): self.loop._process_events = mock.Mock() def zero_error(fut): fut.set_result(True) 1 / 0 # Test call_soon (events.Handle) with mock.patch('trollius.base_events.logger') as log: fut = asyncio.Future(loop=self.loop) self.loop.call_soon(zero_error, fut) fut.add_done_callback(lambda fut: self.loop.stop()) self.loop.run_forever() log.error.assert_called_with( test_utils.MockPattern('Exception in callback.*zero'), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)) # Test call_later (events.TimerHandle) with mock.patch('trollius.base_events.logger') as log: fut = asyncio.Future(loop=self.loop) self.loop.call_later(0.01, zero_error, fut) fut.add_done_callback(lambda fut: self.loop.stop()) self.loop.run_forever() log.error.assert_called_with( test_utils.MockPattern('Exception in callback.*zero'), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY))
def test_cancel_handshake(self): # Python issue #23197: cancelling an handshake must not raise an # exception or log an error, even if the handshake failed sslcontext = test_utils.dummy_ssl_context() app_proto = asyncio.Protocol() waiter = asyncio.Future(loop=self.loop) ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter) handshake_fut = asyncio.Future(loop=self.loop) def do_handshake(callback): exc = Exception() callback(exc) handshake_fut.set_result(None) return [] waiter.cancel() transport = mock.Mock() sslpipe = mock.Mock() sslpipe.shutdown.return_value = b'' sslpipe.do_handshake.side_effect = do_handshake with mock.patch('trollius.sslproto._SSLPipe', return_value=sslpipe): ssl_proto.connection_made(transport) with test_utils.disable_logger(): self.loop.run_until_complete(handshake_fut) # Close the transport ssl_proto._app_transport.close()
def test_pause_resume_reading(self): tr = self.socket_transport() futures = [] for msg in [b'data1', b'data2', b'data3', b'data4', b'']: f = asyncio.Future(loop=self.loop) f.set_result(msg) futures.append(f) self.loop._proactor.recv.side_effect = futures self.loop._run_once() self.assertFalse(tr._paused) self.loop._run_once() self.protocol.data_received.assert_called_with(b'data1') self.loop._run_once() self.protocol.data_received.assert_called_with(b'data2') tr.pause_reading() self.assertTrue(tr._paused) for i in range(10): self.loop._run_once() self.protocol.data_received.assert_called_with(b'data2') tr.resume_reading() self.assertFalse(tr._paused) self.loop._run_once() self.protocol.data_received.assert_called_with(b'data3') self.loop._run_once() self.protocol.data_received.assert_called_with(b'data4') tr.close()
def test_ctor(self): fut = asyncio.Future(loop=self.loop) tr = self.socket_transport(waiter=fut) test_utils.run_briefly(self.loop) self.assertIsNone(fut.result()) self.protocol.connection_made(tr) self.proactor.recv.assert_called_with(self.sock, 4096)
def list_controllers(self, timeout): @asyncio.coroutine def on_response_received(packet, future): self.logger.debug("List of controllers received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: controllers = packet.get(name='controllers', format_function=lambda raw_ctrls: [ Controller.from_flatbuffers(raw_ctrl) for raw_ctrl in raw_ctrls ]) future.set_result(controllers) else: future.set_exception( BaBLEException(packet, "Failed to list controllers")) future = asyncio.Future() request_packet = Packet.build(GetControllersList) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.send_packet(request_packet) self.logger.debug("Waiting for list of controllers...") try: controllers = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(controllers) except asyncio.TimeoutError: self.remove_callback(request_packet.packet_uuid) raise RuntimeError("List controllers timed out")
def test_proc_exited(self): waiter = asyncio.Future(loop=self.loop) transport, protocol = self.create_transport(waiter) transport._process_exited(6) self.loop.run_until_complete(waiter) self.assertEqual(transport.get_returncode(), 6) self.assertTrue(protocol.connection_made.called) self.assertTrue(protocol.process_exited.called) self.assertTrue(protocol.connection_lost.called) self.assertEqual(protocol.connection_lost.call_args[0], (None, )) self.assertFalse(transport._closed) self.assertIsNone(transport._loop) self.assertIsNone(transport._proc) self.assertIsNone(transport._protocol) # methods must raise ProcessLookupError if the process exited self.assertRaises(ProcessLookupError, transport.send_signal, signal.SIGTERM) self.assertRaises(ProcessLookupError, transport.terminate) self.assertRaises(ProcessLookupError, transport.kill) transport.close()
def test_loop_writing_stop(self): fut = asyncio.Future(loop=self.loop) fut.set_result(b'data') tr = self.socket_transport() tr._write_fut = fut tr._loop_writing(fut) self.assertIsNone(tr._write_fut)
def test_loop_reading_data(self): res = asyncio.Future(loop=self.loop) res.set_result(b'data') tr = self.socket_transport() tr._read_fut = res tr._loop_reading(res) self.loop._proactor.recv.assert_called_with(self.sock, 4096) self.protocol.data_received.assert_called_with(b'data')
def test_future_source_traceback(self): self.loop.set_debug(True) future = asyncio.Future(loop=self.loop) lineno = sys._getframe().f_lineno - 1 self.assertIsInstance(future._source_traceback, list) filename = sys._getframe().f_code.co_filename self.assertEqual(future._source_traceback[-1][:3], (filename, lineno, 'test_future_source_traceback'))
def test_thread(loop, debug, create_loop=False): event = threading.Event() fut = asyncio.Future(loop=loop) loop.call_soon(event.set) args = (loop, event, debug, create_loop, fut) thread = threading.Thread(target=check_in_thread, args=args) thread.start() loop.run_until_complete(fut) thread.join()
def set_single_pose(self, servo_id, value): future = asyncio.Future() try: write_dict = {servo_id: value} self.controller.set_pose(write_dict, future) except Exception as e: print "Got exception writing pose:", e raise yield From(future)
def test_tb_logger_exception_unretrieved(self, m_log): self.loop.set_debug(True) asyncio.set_event_loop(self.loop) fut = asyncio.Future(loop=self.loop) fut.set_exception(RuntimeError('boom')) del fut test_utils.run_briefly(self.loop) support.gc_collect() self.assertTrue(m_log.error.called)
def test_cancel(self): f = asyncio.Future(loop=self.loop) self.assertTrue(f.cancel()) self.assertTrue(f.cancelled()) self.assertTrue(f.done()) self.assertRaises(asyncio.CancelledError, f.result) self.assertRaises(asyncio.CancelledError, f.exception) self.assertRaises(asyncio.InvalidStateError, f.set_result, None) self.assertRaises(asyncio.InvalidStateError, f.set_exception, None) self.assertFalse(f.cancel())
def monitor_status(self): voltages = {} temperatures = {} ident = 0 while True: if (self.controller is not None and hasattr(self.controller, 'get_voltage')): try: ident = (ident + 1) % len(self.servo_controls) future = asyncio.Future() self.controller.get_voltage([ident], future) this_voltage = yield From(future) voltages.update(this_voltage) # Get all temperatures. future = asyncio.Future() self.controller.get_temperature([ident], future) this_temp = yield From(future) temperatures.update(this_temp) def non_None(value): return [x for x in value if x is not None] message = "Servo status: " if len(non_None(voltages.values())): message += "%.1f/%.1fV" % ( min(non_None(voltages.values())), max(non_None(voltages.values()))) if len(non_None(temperatures.values())): message += " %.1f/%.1fC" % ( min(non_None(temperatures.values())), max(non_None(temperatures.values()))) self.status.showMessage(message, 10000) except Exception as e: traceback.print_exc() print "Error reading servo:", type(e), str(e) yield From(asyncio.sleep(2.0))
def probe_characteristics(self, controller_id, connection_handle, start_handle, end_handle, on_characteristics_probed, timeout): if isinstance(on_characteristics_probed, (tuple, list)): on_characteristics_probed_cb = on_characteristics_probed[0] on_characteristics_probed_params = on_characteristics_probed[1:] else: on_characteristics_probed_cb = on_characteristics_probed on_characteristics_probed_params = [] @asyncio.coroutine def on_response_received(packet, future): self.logger.debug( "Probe characteristics response received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: characteristics = packet.get_dict([ 'controller_id', 'connection_handle', ('characteristics', lambda chars: [Characteristic.from_flatbuffers(char) for char in chars]) ]) on_characteristics_probed_cb(True, characteristics, None, *on_characteristics_probed_params) future.set_result(characteristics) else: error = BaBLEException(packet, "Failed to probe characteristics", connection_handle=connection_handle) on_characteristics_probed_cb(False, None, error, *on_characteristics_probed_params) future.set_exception(error) future = asyncio.Future() request_packet = Packet.build(ProbeCharacteristics, controller_id=controller_id, connection_handle=connection_handle, start_handle=start_handle, end_handle=end_handle) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.send_packet(request_packet) self.logger.debug("Waiting for characteristics...") try: characteristics = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(characteristics) except asyncio.TimeoutError: self.remove_callback(request_packet.packet_uuid) raise RuntimeError("Probe characteristics timed out")
def read(self, controller_id, connection_handle, attribute_handle, on_read, timeout): if isinstance(on_read, (tuple, list)): on_read_cb = on_read[0] on_read_params = on_read[1:] else: on_read_cb = on_read on_read_params = [] @asyncio.coroutine def on_response_received(packet, future): self.logger.debug("Read response received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: data = packet.get_dict([ 'controller_id', 'connection_handle', 'attribute_handle', ('value', bytes) ]) on_read_cb(True, data, None, *on_read_params) future.set_result(data) else: error = BaBLEException(packet, "Failed to read value", connection_handle=connection_handle, attribute_handle=attribute_handle) on_read_cb(False, None, error, *on_read_params) future.set_exception(error) future = asyncio.Future() request_packet = Packet.build(ReadCentral, controller_id=controller_id, connection_handle=connection_handle, attribute_handle=attribute_handle) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.send_packet(request_packet) self.logger.debug("Reading...") try: result = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(result) except asyncio.TimeoutError: self.remove_callback(request_packet.packet_uuid) on_read_cb(False, None, "Read timed out", *on_read_params) raise RuntimeError("Read timed out")
def test_loop_writing_closing(self): fut = asyncio.Future(loop=self.loop) fut.set_result(1) tr = self.socket_transport() tr._write_fut = fut tr.close() tr._loop_writing(fut) self.assertIsNone(tr._write_fut) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None)
def handle_capture_current(self): with self.servo_update: future = asyncio.Future() self.controller.get_pose(range(len(self.servo_controls)), future) results = yield From(future) for ident, angle in results.iteritems(): if angle is None: continue control = self.servo_controls[ident] control['slider'].setSliderPosition(int(angle)) control['doublespin'].setValue(angle)
def test_get_with_putters(self): q = asyncio.Queue(1, loop=self.loop) q.put_nowait(1) waiter = asyncio.Future(loop=self.loop) q._putters.append((2, waiter)) res = self.loop.run_until_complete(q.get()) self.assertEqual(1, res) self.assertTrue(waiter.done()) self.assertIsNone(waiter.result())
def test_dont_pause_writing(self): tr = self.pause_writing_transport(high=4) # write a large chunk which completes immedialty, # it should not pause writing fut = asyncio.Future(loop=self.loop) fut.set_result(None) self.loop._proactor.send.return_value = fut tr.write(b'very large data') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 0) self.assertFalse(self.protocol.pause_writing.called)
def test_create_server_cancel(self): pf = mock.Mock() call_soon = self.loop.call_soon = mock.Mock() self.loop._start_serving(pf, self.sock) loop = call_soon.call_args[0][0] # cancelled fut = asyncio.Future(loop=self.loop) fut.cancel() loop(fut) self.assertTrue(self.sock.close.called)
def test_copy_state(self): # Test the internal _copy_state method since it's being directly # invoked in other modules. f = asyncio.Future(loop=self.loop) f.set_result(10) newf = asyncio.Future(loop=self.loop) newf._copy_state(f) self.assertTrue(newf.done()) self.assertEqual(newf.result(), 10) f_exception = asyncio.Future(loop=self.loop) f_exception.set_exception(RuntimeError()) newf_exception = asyncio.Future(loop=self.loop) newf_exception._copy_state(f_exception) self.assertTrue(newf_exception.done()) self.assertRaises(RuntimeError, newf_exception.result) f_cancelled = asyncio.Future(loop=self.loop) f_cancelled.cancel() newf_cancelled = asyncio.Future(loop=self.loop) newf_cancelled._copy_state(f_cancelled) self.assertTrue(newf_cancelled.cancelled())
def handle_move_to_pose(self): if self.ui.poseList.currentRow() < 0: return values = self.ui.poseList.currentItem().data(QtCore.Qt.UserRole) future = asyncio.Future() self.controller.set_pose(values, future) yield From(future) with self.servo_update: for ident, angle_deg in values.iteritems(): control = self.servo_controls[ident] control['slider'].setSliderPosition(int(angle_deg)) control['doublespin'].setValue(angle_deg)
def test_close(self): self.assertFalse(self.loop.is_closed()) self.loop.close() self.assertTrue(self.loop.is_closed()) # it should be possible to call close() more than once self.loop.close() self.loop.close() # operation blocked when the loop is closed f = asyncio.Future(loop=self.loop) self.assertRaises(RuntimeError, self.loop.run_forever) self.assertRaises(RuntimeError, self.loop.run_until_complete, f)
def test_write_eof_buffer(self): tr = self.socket_transport() f = asyncio.Future(loop=self.loop) tr._loop._proactor.send.return_value = f tr.write(b'data') tr.write_eof() self.assertTrue(tr._eof_written) self.assertFalse(self.sock.shutdown.called) tr._loop._proactor.send.assert_called_with(self.sock, b'data') f.set_result(4) self.loop._run_once() self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.close()
def test_exception(self): exc = RuntimeError() f = asyncio.Future(loop=self.loop) self.assertRaises(asyncio.InvalidStateError, f.exception) f.set_exception(exc) self.assertFalse(f.cancelled()) self.assertTrue(f.done()) self.assertRaises(RuntimeError, f.result) self.assertEqual(f.exception(), exc) self.assertRaises(asyncio.InvalidStateError, f.set_result, None) self.assertRaises(asyncio.InvalidStateError, f.set_exception, None) self.assertFalse(f.cancel())
def test_loop_reading_no_data(self): res = asyncio.Future(loop=self.loop) res.set_result(b'') tr = self.socket_transport() self.assertRaises(AssertionError, tr._loop_reading, res) tr.close = mock.Mock() tr._read_fut = res tr._loop_reading(res) self.assertFalse(self.loop._proactor.recv.called) self.assertTrue(self.protocol.eof_received.called) self.assertTrue(tr.close.called)
def test_write_eof_buffer_write_pipe(self): tr = _ProactorWritePipeTransport(self.loop, self.sock, self.protocol) f = asyncio.Future(loop=self.loop) tr._loop._proactor.send.return_value = f tr.write(b'data') tr.write_eof() self.assertTrue(tr._closing) self.assertFalse(self.sock.shutdown.called) tr._loop._proactor.send.assert_called_with(self.sock, b'data') f.set_result(4) self.loop._run_once() self.loop._run_once() self.assertTrue(self.sock.close.called) tr.close()
def __init__(self, factory, loop=None, logger=None, subscriptions=None): super(CoreMqClientProtocol, self).__init__() self.factory = factory self.loop = loop or factory.loop self.transport = None self.reader = asyncio.StreamReader() self.writer = None self.uuid = None self.logger = factory.get_logger(logger) self.subscriptions = subscriptions or [] self.options = dict() self.server = None self.connected_future = asyncio.Future()