def test_schedules(self): called = False m = CoroutineMock() def cb(): nonlocal called called = True loop = asyncio.get_event_loop() loop.call_soon(cb) run_coroutine(m(), loop=loop) self.assertTrue(called)
def test_ibr_register(self): password = "******" aux_fields = {"nick": "romeo's lover"} with unittest.mock.patch('aioxmpp.protocol.send_and_wait_for', new=CoroutineMock()) as mock1: stream = unittest.mock.Mock(spec=aioxmpp.protocol.XMLStream) stream._to = TEST_PEER.domain query = aioxmpp.ibr.Query(TEST_PEER.localpart, "aaa", aux_fields) run_coroutine(aioxmpp.ibr.register(stream, query)) _, (_, iq, *_), _ = mock1.mock_calls[0] iq = iq[0] self.assertIsInstance( iq, aioxmpp.IQ, ) self.assertEqual( iq.to, TEST_PEER.bare().replace(localpart=None), ) self.assertEqual( iq.type_, aioxmpp.IQType.SET, ) self.assertIsInstance( iq.payload, ibr_xso.Query, ) self.assertEqual( iq.payload.username, TEST_PEER.localpart, ) self.assertEqual( iq.payload.password, password, ) if aux_fields is not None: for key, value in aux_fields.items(): self.assertEqual( getattr(iq.payload, key), value, )
def setUp(self): base = unittest.mock.Mock() base.repeated_query = CoroutineMock() self.base = base self.patches = [ unittest.mock.patch( "aioxmpp.network.repeated_query", new=base.repeated_query, ), ] for patch in self.patches: patch.start()
def test_disable_does_not_send_if_feature_not_available(self): with contextlib.ExitStack() as stack: check_for_feature = stack.enter_context( unittest.mock.patch.object(self.s, "_check_for_feature", new=CoroutineMock())) check_for_feature.side_effect = RuntimeError() with self.assertRaises(RuntimeError): run_coroutine(self.s.disable()) check_for_feature.assert_called_once_with() self.cc.send.assert_not_called()
def setUp(self): self.stream = unittest.mock.Mock() self.send_iq_and_wait_for_reply = CoroutineMock() self.send_iq_and_wait_for_reply.return_value = None self.stream.send_iq_and_wait_for_reply = \ self.send_iq_and_wait_for_reply self.peer_jid = TEST_PEER_JID self.command_name = "foocmd" self.session = adhoc_service.ClientSession( self.stream, self.peer_jid, self.command_name, )
def test_disable_avatar_synchronize_vcard_pep_raises(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())) # do not do the vcard operations of pep is available but # fails self.pep.publish.side_effect = RuntimeError self.vcard.get_vcard.return_value = unittest.mock.Mock() with self.assertRaises(RuntimeError): run_coroutine(self.s.disable_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)] )
def test_set_bookmarks_failure(self): bookmarks = unittest.mock.sentinel.something_else with unittest.mock.patch.object( self.private_xml, "set_private_xml", new=CoroutineMock()) as set_private_xml_mock: with self.assertRaisesRegex( TypeError, "^set_bookmarks only accepts bookmark.Storage objects$"): run_coroutine(self.s.set_bookmarks(bookmarks)) self.assertEqual( len(set_private_xml_mock.mock_calls), 0 )
def test_propagates_ValueError_from_lookup_srv(self): base = unittest.mock.Mock() base.lookup_srv = CoroutineMock() nattempts = object() with unittest.mock.patch("aioxmpp.network.lookup_srv", new=base.lookup_srv) as lookup_srv: lookup_srv.side_effect = ValueError() with self.assertRaises(ValueError): run_coroutine( network.find_xmpp_host_addr(asyncio.get_event_loop(), base.domain, attempts=nattempts))
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__fetch_in_background_makes_lookup_in_background(self): provider = unittest.mock.Mock(spec=avatar.XMPPAvatarProvider) provider.fetch_avatar = CoroutineMock() self.am._fetch_in_background(unittest.mock.sentinel.account, provider, unittest.mock.sentinel.address) run_coroutine(asyncio.sleep(0.01)) provider.fetch_avatar.assert_called_once_with( unittest.mock.sentinel.address, ) self.listener.on_avatar_changed.assert_called_once_with( unittest.mock.sentinel.account, unittest.mock.sentinel.address, )
def test_query_info_timeout(self): to = structs.JID.fromstr("[email protected]/res1") with unittest.mock.patch.object( self.s, "send_and_decode_info_query", new=CoroutineMock()) as send_and_decode: response = {} send_and_decode.delay = 1 send_and_decode.return_value = response with self.assertRaises(TimeoutError): result = run_coroutine(self.s.query_info(to, timeout=0.01)) self.assertSequenceEqual([ unittest.mock.call(to, None), ], send_and_decode.mock_calls)
def test_query_info_reraises_but_does_not_cache_exception(self): to = structs.JID.fromstr("[email protected]/res1") with unittest.mock.patch.object( self.s, "send_and_decode_info_query", new=CoroutineMock()) as send_and_decode: send_and_decode.side_effect = errors.XMPPCancelError( condition=(namespaces.stanzas, "feature-not-implemented"), ) with self.assertRaises(errors.XMPPCancelError): run_coroutine(self.s.query_info(to, node="foobar")) send_and_decode.side_effect = ConnectionError() with self.assertRaises(ConnectionError): run_coroutine(self.s.query_info(to, node="foobar"))
def test_query_info_with_node(self): to = structs.JID.fromstr("[email protected]/res1") response = {} with self.assertRaises(TypeError): self.s.query_info(to, "foobar") with unittest.mock.patch.object( self.s, "send_and_decode_info_query", new=CoroutineMock()) as send_and_decode: send_and_decode.return_value = response result = run_coroutine(self.s.query_info(to, node="foobar")) send_and_decode.assert_called_with(to, "foobar") self.assertIs(result, response)
def test_ping_uses_global_ping(self): with unittest.mock.patch("aioxmpp.ping.service.ping", new=CoroutineMock()) as ping: ping.return_value = unittest.mock.sentinel.result result = run_coroutine(self.s.ping(unittest.mock.sentinel.peer)) ping.assert_called_once_with( self.cc, unittest.mock.sentinel.peer, ) self.assertEqual( result, unittest.mock.sentinel.result, )
def test_set_vcard(self): with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: vcard = vcard_xso.VCard() run_coroutine(self.s.set_vcard(vcard)) self.assertEqual(len(mock_send.mock_calls), 1) try: (_, (arg, ), kwargs), = mock_send.mock_calls except ValueError: self.fail("send called with wrong signature") self.assertEqual(len(kwargs), 0) self.assertIsInstance(arg, aioxmpp.IQ) self.assertEqual(arg.type_, aioxmpp.IQType.SET) self.assertEqual(arg.to, None) self.assertIs(arg.payload, vcard)
def setUp(self): self.listener = unittest.mock.Mock() self.cc = make_connected_client() self.cc.stream.send = CoroutineMock() self.cc.local_jid = LOCAL_JID self.svc = unittest.mock.Mock(["client", "_conversation_left"]) self.svc.client = self.cc self.c = p2p.Conversation(self.svc, PEER_JID) for ev in ["on_message"]: listener = getattr(self.listener, ev) signal = getattr(self.c, ev) listener.return_value = None signal.connect(listener)
def test_query_info_caches(self): to = structs.JID.fromstr("[email protected]/res1") response = {} with unittest.mock.patch.object( self.s, "send_and_decode_info_query", new=CoroutineMock()) as send_and_decode: send_and_decode.return_value = response result1 = run_coroutine(self.s.query_info(to, node="foobar")) result2 = run_coroutine(self.s.query_info(to, node="foobar")) self.assertIs(result1, response) self.assertIs(result2, response) self.assertEqual(1, len(send_and_decode.mock_calls))
def test_pinger_emits_ping_right_away(self): with contextlib.ExitStack() as stack: ping = stack.enter_context( unittest.mock.patch( "aioxmpp.ping.ping", new=CoroutineMock(), )) self.p.start() run_coroutine(asyncio.sleep(0)) self._require_task_running() ping.assert_called_once_with( self.cc, unittest.mock.sentinel.ping_address, )
def test__set_bookmarks(self): bookmarks = [] bookmarks.append( aioxmpp.bookmarks.Conference( "Coven", aioxmpp.JID.fromstr("*****@*****.**")), ) bookmarks.append( aioxmpp.bookmarks.URL("Interesting", "http://example.com/"), ) with unittest.mock.patch.object( self.private_xml, "set_private_xml", new=CoroutineMock()) as set_private_xml_mock: run_coroutine(self.s._set_bookmarks(bookmarks)) self.assertEqual(len(set_private_xml_mock.mock_calls), 1) (_, (arg, ), kwargs), = set_private_xml_mock.mock_calls self.assertEqual(len(kwargs), 0) self.assertEqual(arg.bookmarks, bookmarks)
def test_get_bookmarks(self): with unittest.mock.patch.object( self.private_xml, "get_private_xml", new=CoroutineMock()) as get_private_xml_mock: get_private_xml_mock.return_value = unittest.mock.sentinel.result res = run_coroutine(self.s.get_bookmarks()) self.assertIs(res, unittest.mock.sentinel.result) self.assertEqual( len(get_private_xml_mock.mock_calls), 1 ) (_, (arg,), kwargs), = get_private_xml_mock.mock_calls self.assertEqual(len(kwargs), 0) self.assertIsInstance(arg, aioxmpp.bookmarks.Storage) self.assertEqual(len(arg.bookmarks), 0)
def test_query_response_for_node_leads_to_signal_emission(self): handler = unittest.mock.Mock() handler.return_value = None to = structs.JID.fromstr("[email protected]/res1") response = {} with unittest.mock.patch.object( self.s, "send_and_decode_info_query", new=CoroutineMock()) as send_and_decode: send_and_decode.return_value = response self.s.on_info_result.connect(handler) run_coroutine(self.s.query_info(to, node="foo")) handler.assert_called_with(to, "foo", response)
def test_set_private_xml(self): payload = FakePayload() with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: run_coroutine(self.s.set_private_xml(payload)) self.assertEqual(len(mock_send.mock_calls), 1) try: (_, (arg,), kwargs), = mock_send.mock_calls except ValueError: self.fail("send called with wrong signature") self.assertEqual(len(kwargs), 0) self.assertIsInstance(arg, aioxmpp.IQ) self.assertEqual(arg.type_, aioxmpp.IQType.SET) self.assertIsInstance(arg.payload, private_xml_xso.Query) self.assertEqual(arg.payload.registered_payload, payload)
def test_select_common_hashes_not_supported(self): with unittest.mock.patch.object(self.disco_client, "query_info", new=CoroutineMock()) as query_info: query_info.return_value = disco_xso.InfoQuery( features=('urn:xmpp:hash-function-text-names:md5', )) with self.assertRaisesRegex( RuntimeError, "Remote does not support the urn:xmpp:hashes:2 feature."): res = run_coroutine( self.s.select_common_hashes( unittest.mock.sentinel.other_jid)) self.assertSequenceEqual(query_info.mock_calls, [ unittest.mock.call(unittest.mock.sentinel.other_jid), ])
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)
def test_starttls(self): ssl_context = unittest.mock.MagicMock() post_handshake_callback = CoroutineMock() post_handshake_callback.return_value = None self.xmlstream.transport = object() run_coroutine( asyncio.gather( self.xmlstream.starttls(ssl_context, post_handshake_callback), self.xmlstream.run_test([ XMLStreamMock.STARTTLS(ssl_context, post_handshake_callback) ], ))) post_handshake_callback.assert_called_once_with( self.xmlstream.transport)
def test_pep_get_image_bytes(self): descriptor = avatar_service.PubsubAvatarDescriptor( TEST_JID1, TEST_IMAGE_SHA1.upper(), mime_type="image/png", nbytes=len(TEST_IMAGE), pubsub=self.pubsub ) self.assertTrue(descriptor.has_image_data_in_pubsub) self.assertEqual(TEST_IMAGE_SHA1, descriptor.normalized_id) items = pubsub_xso.Items( namespaces.xep0084_data, ) pubsub_result = pubsub_xso.Request(items) with unittest.mock.patch.object(self.pubsub, "get_items_by_id", new=CoroutineMock()): self.pubsub.get_items_by_id.return_value = pubsub_result with self.assertRaises(RuntimeError): res = run_coroutine(descriptor.get_image_bytes()) item = pubsub_xso.Item(id_=TEST_IMAGE_SHA1) item.registered_payload = avatar_xso.Data(TEST_IMAGE) items.items.append(item) res = run_coroutine(descriptor.get_image_bytes()) self.assertSequenceEqual( self.pubsub.get_items_by_id.mock_calls, [ unittest.mock.call( TEST_JID1, namespaces.xep0084_data, [TEST_IMAGE_SHA1.upper()], ), unittest.mock.call( TEST_JID1, namespaces.xep0084_data, [TEST_IMAGE_SHA1.upper()], ) ] ) self.assertEqual(res, TEST_IMAGE)
def test_get_avatar_returns_result_from_fetch_avatar(self): def generate_images(): for i in itertools.count(): yield getattr(unittest.mock.sentinel, "image{}".format(i)) def generate_bytes(): for i in itertools.count(): if i == 1: yield None yield unittest.mock.sentinel.image_bytes 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.side_effect = generate_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")) render_avatar_image.side_effect = generate_images() pic1 = run_coroutine( self.ap.fetch_avatar(unittest.mock.sentinel.address1, )) self.assertIsNotNone(pic1) pic2 = run_coroutine( self.ap.fetch_avatar(unittest.mock.sentinel.address2, )) self.assertIsNone(pic2) self.assertEqual( self.ap.get_avatar(unittest.mock.sentinel.address1), unittest.mock.sentinel.image0, ) self.assertEqual( self.ap.get_avatar(unittest.mock.sentinel.address2), None, ) with self.assertRaises(KeyError): self.ap.get_avatar(unittest.mock.sentinel.address)
def test_connect_spawn(self): signal = AdHocSignal() mock = CoroutineMock() @asyncio.coroutine def coro(*args, **kwargs): yield from mock(*args, **kwargs) signal.connect(coro, AdHocSignal.SPAWN_WITH_LOOP(None)) signal.fire("a", 1, b="c") self.assertSequenceEqual(mock.mock_calls, []) run_coroutine(asyncio.sleep(0)) self.assertSequenceEqual(mock.mock_calls, [unittest.mock.call("a", 1, b="c")])
def test_get_vcard_other(self): with unittest.mock.patch.object(self.cc, "send", new=CoroutineMock()) as mock_send: mock_send.return_value = unittest.mock.sentinel.result res = run_coroutine(self.s.get_vcard(TEST_JID1)) self.assertEqual(len(mock_send.mock_calls), 1) try: (_, (arg, ), kwargs), = mock_send.mock_calls except ValueError: self.fail("send called with wrong signature") self.assertEqual(len(kwargs), 0) self.assertIsInstance(arg, aioxmpp.IQ) self.assertEqual(arg.type_, aioxmpp.IQType.GET) self.assertEqual(arg.to, TEST_JID1) self.assertIsInstance(arg.payload, vcard_xso.VCard) self.assertEqual(len(arg.payload.elements), 0) self.assertEqual(res, unittest.mock.sentinel.result)
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)