def test_get_avatar_metadata_mask_xmpp_errors(self): with unittest.mock.patch.object(self.pubsub, "get_items", new=CoroutineMock()): self.pubsub.get_items.side_effect = errors.XMPPCancelError( (namespaces.stanzas, "feature-not-implemented")) res = run_coroutine(self.s.get_avatar_metadata(TEST_JID1)) self.assertSequenceEqual(res, []) self.assertSequenceEqual(self.pubsub.get_items.mock_calls, [ unittest.mock.call( TEST_JID1, namespaces.xep0084_metadata, max_items=1), ]) with unittest.mock.patch.object(self.pubsub, "get_items", new=CoroutineMock()): self.pubsub.get_items.side_effect = errors.XMPPCancelError( (namespaces.stanzas, "item-not-found")) res = run_coroutine(self.s.get_avatar_metadata(TEST_JID2)) self.assertSequenceEqual(res, []) self.assertSequenceEqual(self.pubsub.get_items.mock_calls, [ unittest.mock.call( TEST_JID2, namespaces.xep0084_metadata, max_items=1), ])
def test_get_vcard_mask_cancel_error(self): with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( (namespaces.stanzas, "feature-not-implemented")) res = run_coroutine(self.s.get_vcard(TEST_JID1)) self.assertIsInstance(res, vcard_xso.VCard) self.assertEqual(len(res.elements), 0) with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( (namespaces.stanzas, "item-not-found")) res = run_coroutine(self.s.get_vcard(TEST_JID1)) self.assertIsInstance(res, vcard_xso.VCard) self.assertEqual(len(res.elements), 0) with self.assertRaises(aioxmpp.XMPPCancelError): with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( (namespaces.stanzas, "fnord")) res = run_coroutine(self.s.get_vcard(TEST_JID1))
def test_get_initial_blocklist_handles_exception(self): with contextlib.ExitStack() as stack: _check_for_blocking = stack.enter_context( unittest.mock.patch.object(self.s, "_check_for_blocking", new=CoroutineMock())) _check_for_blocking.side_effect = RuntimeError() stack.enter_context( unittest.mock.patch.object(self.cc, "send", new=CoroutineMock())) handle_initial_blocklist_mock = unittest.mock.Mock() self.s.on_initial_blocklist_received.connect( handle_initial_blocklist_mock) BLOCKLIST = [TEST_JID1, TEST_JID2] blocklist = blocking_xso.BlockList() blocklist.items[:] = BLOCKLIST self.cc.send.return_value = blocklist result = run_coroutine(self.s._get_initial_blocklist()) self.assertIsNone(self.s._blocklist) self.cc.send.assert_not_called() self.s._check_for_blocking.assert_called_once_with() self.assertTrue(result) # so that coroutine doesn’t get disconnected
def test__handle_command_raises_forbidden_for_disallowed_node(self): handler = CoroutineMock() handler.return_value = unittest.mock.sentinel.result is_allowed = unittest.mock.Mock() is_allowed.return_value = False self.s.register_stateless_command( "node", "Command name", handler, is_allowed=is_allowed, ) req = aioxmpp.IQ(type_=aioxmpp.IQType.SET, from_=TEST_PEER_JID, to=TEST_LOCAL_JID, payload=adhoc_xso.Command("node", )) with self.assertRaises(aioxmpp.errors.XMPPCancelError) as ctx: run_coroutine(self.s._handle_command(req)) is_allowed.assert_called_once_with(req.from_) self.assertEqual( ctx.exception.condition, aioxmpp.ErrorCondition.FORBIDDEN, ) handler.assert_not_called()
def test_starttls(self): self.t = TransportMock(self, self.protocol, with_starttls=True, loop=self.loop) self.assertTrue(self.t.can_starttls()) fut = asyncio.Future() def connection_made(transport): fut.set_result(None) self.protocol.connection_made = connection_made ssl_context = unittest.mock.Mock() post_handshake_callback = CoroutineMock() post_handshake_callback.return_value = None async def late_starttls(): await fut await self.t.starttls(ssl_context, post_handshake_callback) run_coroutine_with_peer( late_starttls(), self.t.run_test( [TransportMock.STARTTLS(ssl_context, post_handshake_callback)])) post_handshake_callback.assert_called_once_with(self.t)
def test__handle_command_dispatches_to_command(self): handler = CoroutineMock() handler.return_value = unittest.mock.sentinel.result self.s.register_stateless_command( "node", "Command name", handler, ) req = aioxmpp.IQ( type_=aioxmpp.IQType.SET, from_=TEST_PEER_JID, to=TEST_LOCAL_JID, payload=adhoc_xso.Command( "node", ) ) result = run_coroutine(self.s._handle_command(req)) handler.assert_called_once_with(req) self.assertEqual( result, unittest.mock.sentinel.result, )
def test_unblock_jids(self): with contextlib.ExitStack() as stack: stack.enter_context( unittest.mock.patch.object(self.s, "_check_for_blocking", new=CoroutineMock())) stack.enter_context( unittest.mock.patch.object(self.cc.stream, "send", new=CoroutineMock())) run_coroutine(self.s.unblock_jids([TEST_JID2])) self.assertSequenceEqual(self.s._check_for_blocking.mock_calls, [unittest.mock.call()]) self.assertEqual(len(self.cc.stream.send.mock_calls), 1) (_, (arg, ), _), = self.cc.stream.send.mock_calls self.assertIsInstance(arg, aioxmpp.IQ) self.assertEqual(arg.type_, aioxmpp.IQType.SET) self.assertIsInstance(arg.payload, blocking_xso.UnblockCommand) self.assertCountEqual( arg.payload.items, frozenset([TEST_JID2]), )
def test_get_vcard_mask_cancel_error(self): with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( aioxmpp.ErrorCondition.FEATURE_NOT_IMPLEMENTED) res = run_coroutine(self.s.get_vcard(TEST_JID1)) self.assertIsInstance(res, vcard_xso.VCard) self.assertEqual(len(res.elements), 0) with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( aioxmpp.ErrorCondition.ITEM_NOT_FOUND) res = run_coroutine(self.s.get_vcard(TEST_JID1)) self.assertIsInstance(res, vcard_xso.VCard) self.assertEqual(len(res.elements), 0) with self.assertRaises(aioxmpp.XMPPCancelError): with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( aioxmpp.ErrorCondition.REMOTE_SERVER_NOT_FOUND) res = run_coroutine(self.s.get_vcard(TEST_JID1))
def test_return_value(self): m = CoroutineMock() m.return_value = "foobar" self.assertEqual( "foobar", run_coroutine(m()) )
def test_check_for_pep(self): disco_info = disco_xso.InfoQuery() disco_info.identities.append( disco_xso.Identity(type_="pep", category="pubsub")) with unittest.mock.patch.object(self.disco_client, "query_info", new=CoroutineMock()): self.disco_client.query_info.return_value = disco_info # run twice, the second call must not query again but use the # cache run_coroutine(self.s._check_for_pep()) run_coroutine(self.s._check_for_pep()) self.assertEqual(1, len(self.disco_client.query_info.mock_calls)) self.disco_client.query_info.assert_called_with(TEST_FROM.bare()) # this should wipe the cache and recheck with disco mock_reason = unittest.mock.Mock() self.s.handle_stream_destroyed(mock_reason) with unittest.mock.patch.object(self.disco_client, "query_info", new=CoroutineMock()): self.disco_client.query_info.return_value = disco_info # run twice, the second call must not query again but use the # cache run_coroutine(self.s._check_for_pep()) run_coroutine(self.s._check_for_pep()) self.assertEqual(1, len(self.disco_client.query_info.mock_calls)) self.disco_client.query_info.assert_called_with(TEST_FROM.bare())
def test_publish(self): with contextlib.ExitStack() as stack: check_for_pep_mock = stack.enter_context( unittest.mock.patch.object( self.s, "_check_for_pep", CoroutineMock(), ) ) publish_mock = stack.enter_context( unittest.mock.patch.object( self.pubsub, "publish", CoroutineMock(), ) ) run_coroutine(self.s.publish( "urn:example", unittest.mock.sentinel.data, id_="example-id", )) check_for_pep_mock.assert_called_once_with() publish_mock.assert_called_once_with( None, "urn:example", unittest.mock.sentinel.data, id_="example-id", )
def test_set_delay(self): m = CoroutineMock() m.delay = 1 with self.assertRaises(asyncio.TimeoutError): run_coroutine(m(), timeout=0.01) self.assertSequenceEqual([ unittest.mock.call(), ], m.mock_calls)
def test_wipe_avatar_with_vcard(self): self.s.synchronize_vcard = True with contextlib.ExitStack() as e: e.enter_context(unittest.mock.patch.object(self.pep, "publish", new=CoroutineMock())) e.enter_context(unittest.mock.patch.object(self.presence_server, "resend_presence")) e.enter_context(unittest.mock.patch.object(self.vcard, "get_vcard", new=CoroutineMock())) e.enter_context(unittest.mock.patch.object(self.vcard, "set_vcard", new=CoroutineMock())) self.vcard.get_vcard.return_value = unittest.mock.Mock() run_coroutine(self.s.wipe_avatar()) self.assertSequenceEqual( self.presence_server.resend_presence.mock_calls, [unittest.mock.call()] ) self.assertSequenceEqual( self.vcard.get_vcard.mock_calls, [unittest.mock.call(), unittest.mock.call().clear_photo_data()] ) self.assertSequenceEqual( self.vcard.set_vcard.mock_calls, [unittest.mock.call(unittest.mock.ANY)] ) self.assertSequenceEqual( self.pep.publish.mock_calls, [ unittest.mock.call( namespaces.xep0084_metadata, unittest.mock.ANY, ), unittest.mock.call( namespaces.xep0084_data, unittest.mock.ANY, ), ] ) _, args, _ = self.pep.publish.mock_calls[0] metadata = args[1] self.assertTrue(isinstance(metadata, avatar_xso.Metadata)) self.assertEqual(0, len(metadata.info)) self.assertEqual(0, len(metadata.pointer)) _, args, _ = self.pep.publish.mock_calls[1] data = args[1] self.assertTrue(isinstance(data, avatar_xso.Data)) self.assertEqual(0, len(data.data))
def test_vcard_get_image_bytes(self): descriptor = avatar_service.VCardAvatarDescriptor( TEST_JID1, TEST_IMAGE_SHA1.upper(), nbytes=len(TEST_IMAGE), vcard=self.vcard, image_bytes=TEST_IMAGE, ) self.assertTrue(descriptor.has_image_data_in_pubsub) self.assertTrue(descriptor.can_get_image_bytes_via_xmpp) with unittest.mock.patch.object(self.vcard, "get_vcard", new=CoroutineMock()): self.assertEqual( run_coroutine(descriptor.get_image_bytes()), TEST_IMAGE ) self.assertSequenceEqual(self.vcard.get_vcard.mock_calls, []) descriptor = avatar_service.VCardAvatarDescriptor( TEST_JID1, TEST_IMAGE_SHA1.upper(), nbytes=len(TEST_IMAGE), vcard=self.vcard, ) with unittest.mock.patch.object(self.vcard, "get_vcard", new=CoroutineMock()): vcard_mock = unittest.mock.Mock() vcard_mock.get_photo_data.return_value = TEST_IMAGE self.vcard.get_vcard.return_value = vcard_mock self.assertEqual( run_coroutine(descriptor.get_image_bytes()), TEST_IMAGE ) vcard_mock.get_photo_data.return_value = None with self.assertRaises(RuntimeError): run_coroutine(descriptor.get_image_bytes()) self.assertSequenceEqual( self.vcard.get_vcard.mock_calls, [ unittest.mock.call( TEST_JID1 ), unittest.mock.call().get_photo_data(), unittest.mock.call( TEST_JID1 ), unittest.mock.call().get_photo_data(), ] )
def test_connect_and_fire(self): coro = CoroutineMock() coro.return_value = True signal = SyncAdHocSignal() signal.connect(coro) run_coroutine(signal.fire(1, 2, foo="bar")) self.assertSequenceEqual([ unittest.mock.call(1, 2, foo="bar"), ], coro.mock_calls)
def setUp(self): self.cc = make_connected_client() self.disco_service = unittest.mock.Mock() self.disco_service.query_info = CoroutineMock() self.disco_service.query_info.side_effect = AssertionError() self.disco_service.query_items = CoroutineMock() self.disco_service.query_items.side_effect = AssertionError() self.c = adhoc_service.AdHocClient(self.cc, dependencies={ aioxmpp.disco.DiscoClient: self.disco_service, })
def test_set_delay(self): m = CoroutineMock() m.delay = 1 with self.assertRaises(asyncio.TimeoutError): run_coroutine(m(), timeout=0.01) self.assertSequenceEqual( [ unittest.mock.call(), ], m.mock_calls )
def test_connect_and_fire(self): coro = CoroutineMock() coro.return_value = True signal = SyncAdHocSignal() signal.connect(coro) run_coroutine(signal.fire(1, 2, foo="bar")) self.assertSequenceEqual( [ unittest.mock.call(1, 2, foo="bar"), ], coro.mock_calls )
def test__get_image_bytes_returns_if_no_image_png_in_result(self): client = self._prep_client() self.ap.prepare_client(client) base = unittest.mock.Mock() base.avatar1 = unittest.mock.Mock( spec=aioxmpp.avatar.service.AbstractAvatarDescriptor) base.avatar1.mime_type = "image/jpeg" base.avatar1.nbytes = 4096 base.avatar1.get_image_bytes = CoroutineMock() self.avatar.get_avatar_metadata.return_value = { "image/jpeg": [base.avatar1], } result = run_coroutine( self.ap._get_image_bytes(unittest.mock.sentinel.address)) self.avatar.get_avatar_metadata.assert_called_once_with( unittest.mock.sentinel.address, ) base.avatar1.get_image_bytes.assert_not_called() self.assertIsNone(result)
def test_proceed_calls_close_and_reraises_on_SessionExpired(self): initial_response = unittest.mock.Mock() initial_response.payload = [ unittest.mock.sentinel.payload1, unittest.mock.sentinel.payload2, ] initial_response.actions = None initial_response.sessionid = "fnord" self.send_iq_and_wait_for_reply.return_value = initial_response self.send_iq_and_wait_for_reply.side_effect = None run_coroutine(self.session.start()) self.send_iq_and_wait_for_reply.mock_calls.clear() exc = aioxmpp.errors.XMPPCancelError( aioxmpp.ErrorCondition.NOT_ALLOWED, text="Session Expired", application_defined_condition=adhoc_xso.SessionExpired(), ) self.send_iq_and_wait_for_reply.side_effect = exc with unittest.mock.patch.object(self.session, "close", new=CoroutineMock()) as close_: with self.assertRaisesRegex(adhoc_service.SessionError, r"Session Expired"): run_coroutine(self.session.proceed()) close_.assert_called_once_with()
def setUp(self): self.cc = make_connected_client() self.cc.stream.send = CoroutineMock() self.cc.stream.send.side_effect = AssertionError("not configured") self.cc.local_jid = LOCAL_JID deps = { im_service.ConversationService: im_service.ConversationService( self.cc ), im_dispatcher.IMDispatcher: im_dispatcher.IMDispatcher( self.cc ) } self.svc = unittest.mock.Mock(["client", "_conversation_left"]) self.svc.client = self.cc self.s = p2p.Service(self.cc, dependencies=deps) self.listener = unittest.mock.Mock() for ev in ["on_conversation_new", "on_conversation_left"]: listener = getattr(self.listener, ev) signal = getattr(self.s, ev) listener.return_value = None signal.connect(listener) for ev in ["on_conversation_added"]: listener = getattr(self.listener, ev) signal = getattr(deps[im_service.ConversationService], ev) listener.return_value = None signal.connect(listener)
def test_ibr_get_registration_fields(self): with unittest.mock.patch('aioxmpp.protocol.send_and_wait_for', new=CoroutineMock()) as mock1: iq_res = aioxmpp.IQ(type_=aioxmpp.IQType.GET, payload=ibr_xso.Query()) iq_res.payload.username = '' mock1.return_value = iq_res stream = unittest.mock.Mock(spec=aioxmpp.protocol.XMLStream) stream._to = TEST_PEER.domain res = run_coroutine(aioxmpp.ibr.get_registration_fields(stream)) _, (_, iq, *_), _ = mock1.mock_calls[0] iq = iq[0] self.assertIsInstance( iq, aioxmpp.IQ, ) self.assertIs( iq_res.payload, res, ) self.assertIsInstance( res, ibr_xso.Query, ) self.assertEqual( res.username, '', )
def test_aenter_starts(self): with unittest.mock.patch.object(self.session, "start", new=CoroutineMock()) as start: result = run_coroutine(self.session.__aenter__()) start.assert_called_once_with() self.assertEqual(result, self.session)
def test_query_info_transparent_deduplication_when_cancelled(self): to = structs.JID.fromstr("[email protected]/res1") response = disco_xso.InfoQuery() with unittest.mock.patch.object( self.s, "send_and_decode_info_query", new=CoroutineMock()) as send_and_decode: response = {} send_and_decode.return_value = response send_and_decode.delay = 0.1 q1 = asyncio. async (self.s.query_info(to)) q2 = asyncio. async (self.s.query_info(to)) run_coroutine(asyncio.sleep(0.05)) q1.cancel() result = run_coroutine(q2) self.assertIs(result, response) self.assertSequenceEqual([ unittest.mock.call(to, None), unittest.mock.call(to, None), ], send_and_decode.mock_calls)
def test_fetch_avatar_uses__get_image_bytes_and_render_avatar_image(self): with contextlib.ExitStack() as stack: _get_image_bytes = stack.enter_context( unittest.mock.patch.object(self.ap, "_get_image_bytes", new=CoroutineMock())) _get_image_bytes.return_value = unittest.mock.sentinel.image_bytes QImage = stack.enter_context( unittest.mock.patch("jabbercat.Qt.QImage")) render_avatar_image = stack.enter_context( unittest.mock.patch("jabbercat.avatar.render_avatar_image")) result = run_coroutine( self.ap.fetch_avatar(unittest.mock.sentinel.address)) _get_image_bytes.assert_called_once_with( unittest.mock.sentinel.address) QImage.fromData.assert_called_once_with( unittest.mock.sentinel.image_bytes, "PNG", ) render_avatar_image.assert_called_once_with(QImage.fromData(), 48) self.assertEqual(result, render_avatar_image())
def test_pinger_uses_jitter_to_calculate_next(self): timeout = get_timeout(0.1) self.p.ping_interval = timedelta(seconds=timeout) self.jitter_mock.return_value = timeout * 2 self.jitter_mock.side_effect = None with contextlib.ExitStack() as stack: ping = stack.enter_context( unittest.mock.patch( "aioxmpp.ping.ping", new=CoroutineMock(), )) self.p.start() run_coroutine(asyncio.sleep(timeout / 2)) self._require_task_running() ping.assert_called_once_with(self.cc, unittest.mock.sentinel.ping_address) ping.reset_mock() run_coroutine(asyncio.sleep(timeout * 2)) self._require_task_running() ping.assert_called_once_with(self.cc, unittest.mock.sentinel.ping_address) ping.reset_mock()
def test__check_for_feature_raises_if_feature_not_present(self): info = unittest.mock.Mock() info.features = set() with contextlib.ExitStack() as stack: query_info = stack.enter_context(unittest.mock.patch.object( self.disco_client, "query_info", new=CoroutineMock(), )) query_info.return_value = info with self.assertRaisesRegex( RuntimeError, r"Message Carbons \({}\) are not supported by " "the server".format( namespaces.xep0280_carbons_2 )): run_coroutine( self.s._check_for_feature() ) query_info.assert_called_once_with( self.cc.local_jid.replace( localpart=None, resource=None ) )
def test_pinger_picks_up_on_interval_change(self): interval = get_timeout(0.1) interval2 = get_timeout(0.3) self.p.ping_interval = timedelta(seconds=interval) with contextlib.ExitStack() as stack: ping = stack.enter_context( unittest.mock.patch( "aioxmpp.ping.ping", new=CoroutineMock(), )) self.p.start() run_coroutine(asyncio.sleep(interval / 2)) self._require_task_running() ping.assert_called_once_with(self.cc, unittest.mock.sentinel.ping_address) ping.reset_mock() self.p.ping_interval = timedelta(seconds=interval2) import time run_coroutine(asyncio.sleep(interval2)) self._require_task_running() print(time.monotonic(), "slept") ping.assert_called_once_with( self.cc, unittest.mock.sentinel.ping_address, ) ping.reset_mock()
def test_pinger_skips_ping_emission_if_client_is_suspended(self): timeout = get_timeout(0.1) self.assertFalse(self.cc.suspended) self.p.ping_interval = timedelta(seconds=timeout) with contextlib.ExitStack() as stack: ping = stack.enter_context( unittest.mock.patch( "aioxmpp.ping.ping", new=CoroutineMock(), )) self.p.start() run_coroutine(asyncio.sleep(timeout / 2)) for i in range(2): self._require_task_running() ping.assert_called_once_with( self.cc, unittest.mock.sentinel.ping_address) ping.reset_mock() # we need to change the suspended flag here, because the next # sleep covers the next ping sending if i == 1: self.cc.suspended = True run_coroutine(asyncio.sleep(timeout)) for i in range(2): print(i) self._require_task_running() ping.assert_not_called() if i == 1: self.cc.suspended = False
def test_queries_version_over_stream(self): test_jid = aioxmpp.JID.fromstr("*****@*****.**") stream = unittest.mock.Mock(["send"]) stream.send = CoroutineMock() stream.send.return_value = unittest.mock.sentinel.result result = run_coroutine(version_svc.query_version( stream, test_jid, )) stream.send.assert_called_once_with(unittest.mock.ANY) _, (iq, ), _ = stream.send.mock_calls[0] self.assertIsInstance(iq, aioxmpp.IQ) self.assertEqual(iq.type_, aioxmpp.IQType.GET) self.assertEqual(iq.to, test_jid) self.assertIsInstance(iq.payload, version_xso.Query) self.assertIsNone(iq.payload.name) self.assertIsNone(iq.payload.version) self.assertIsNone(iq.payload.os) self.assertEqual( result, unittest.mock.sentinel.result, )
def test_wipe_avatar(self): with unittest.mock.patch.object(self.pep, "publish", new=CoroutineMock()): run_coroutine(self.s.wipe_avatar()) self.assertSequenceEqual( self.pep.publish.mock_calls, [ unittest.mock.call( namespaces.xep0084_metadata, unittest.mock.ANY, ), unittest.mock.call( namespaces.xep0084_data, unittest.mock.ANY, ), ] ) _, args, _ = self.pep.publish.mock_calls[0] metadata = args[1] self.assertTrue(isinstance(metadata, avatar_xso.Metadata)) self.assertEqual(0, len(metadata.info)) self.assertEqual(0, len(metadata.pointer)) _, args, _ = self.pep.publish.mock_calls[1] data = args[1] self.assertTrue(isinstance(data, avatar_xso.Data)) self.assertEqual(0, len(data.data))
def test_publish_avatar_set(self): # set the cache to indicate the server has PEP avatar_set = avatar_service.AvatarSet() avatar_set.add_avatar_image("image/png", image_bytes=TEST_IMAGE) with unittest.mock.patch.object(self.pep, "publish", new=CoroutineMock()): run_coroutine(self.s.publish_avatar_set(avatar_set)) self.assertSequenceEqual( self.pep.publish.mock_calls, [ unittest.mock.call( namespaces.xep0084_data, unittest.mock.ANY, id_=avatar_set.png_id ), unittest.mock.call( namespaces.xep0084_metadata, avatar_set.metadata, id_=avatar_set.png_id ) ], ) _, args, _ = self.pep.publish.mock_calls[0] data = args[1] self.assertTrue(isinstance(data, avatar_xso.Data)) self.assertEqual(data.data, avatar_set.image_bytes)
def test_context_connect(self): signal = SyncAdHocSignal() coro = CoroutineMock() coro.return_value = True with signal.context_connect(coro): run_coroutine(signal("foo")) run_coroutine(signal("bar")) with signal.context_connect(coro) as token: run_coroutine(signal("baz")) signal.disconnect(token) run_coroutine(signal("fnord")) self.assertSequenceEqual( [ unittest.mock.call("foo"), unittest.mock.call("baz"), ], coro.mock_calls )
def test_fire_removes_on_false_result(self): coro = CoroutineMock() coro.return_value = False signal = SyncAdHocSignal() signal.connect(coro) run_coroutine(signal.fire(1, 2, foo="bar")) self.assertSequenceEqual( [ unittest.mock.call(1, 2, foo="bar"), ], coro.mock_calls ) coro.reset_mock() run_coroutine(signal.fire(1, 2, foo="bar")) self.assertSequenceEqual( [ ], coro.mock_calls )
class TestLazyTask(unittest.TestCase): def setUp(self): self.coro = CoroutineMock() def test_yield_from_able(self): self.coro.return_value = unittest.mock.sentinel.result @asyncio.coroutine def user(fut): return (yield from fut) fut = utils.LazyTask(self.coro) result = run_coroutine(user(fut)) self.assertEqual(result, unittest.mock.sentinel.result) def test_run_coroutine_able(self): self.coro.return_value = unittest.mock.sentinel.result fut = utils.LazyTask(self.coro) result = run_coroutine(fut) self.assertEqual(result, unittest.mock.sentinel.result) def test_async_able(self): self.coro.return_value = unittest.mock.sentinel.result fut = utils.LazyTask(self.coro) result = run_coroutine(asyncio.ensure_future(fut)) self.assertEqual(result, unittest.mock.sentinel.result) def test_runs_only_once_even_if_awaited_concurrently(self): self.coro.return_value = unittest.mock.sentinel.result fut = utils.LazyTask(self.coro) result2 = run_coroutine(asyncio.ensure_future(fut)) result1 = run_coroutine(fut) self.assertEqual(result1, result2) self.assertEqual(result1, unittest.mock.sentinel.result) self.coro.assert_called_once_with() def test_add_done_callback_spawns_task(self): fut = utils.LazyTask(self.coro) cb = unittest.mock.Mock(["__call__"]) with unittest.mock.patch("asyncio.ensure_future") as async_: fut.add_done_callback(cb) async_.assert_called_once_with(unittest.mock.ANY) def test_add_done_callback_works(self): fut = utils.LazyTask(self.coro) cb = unittest.mock.Mock(["__call__"]) fut.add_done_callback(cb) run_coroutine(fut) cb.assert_called_once_with(fut) def test_is_future(self): self.assertTrue(issubclass( utils.LazyTask, asyncio.Future, )) def test_passes_args(self): self.coro.return_value = unittest.mock.sentinel.result fut = utils.LazyTask( self.coro, unittest.mock.sentinel.a1, unittest.mock.sentinel.a2, unittest.mock.sentinel.a3, ) result = run_coroutine(fut) self.assertEqual(result, unittest.mock.sentinel.result) self.coro.assert_called_once_with( unittest.mock.sentinel.a1, unittest.mock.sentinel.a2, unittest.mock.sentinel.a3, )
def test_side_effect_exception(self): m = CoroutineMock() m.side_effect = ValueError() with self.assertRaises(ValueError): run_coroutine(m())
def setUp(self): self.coro = CoroutineMock()