def test_send_tap_must_send_right_packet_sequence(f): send_tap(f.sock_mock, x, y) calls = [call.send(MOVE_PACKET) for _ in range(TAP_MOVE_COUNT)] calls.insert(0, call.send(TOUCH_PACKET)) calls.append(call.send(RELEASE_PACKET)) f.sock_mock.assert_has_calls(calls)
def test_get_traces_sync(self): test_parity_hosts = "hosts" test_blocks = "blocks" test_urls = ["url1", "url2"] test_trace_requests = { test_urls[0]: "trace1", test_urls[1]: "trace2" } test_transactions_requests = { test_urls[1]: "transactions2", test_urls[0]: "transactions1" } test_trace_response = { "result": ["trace"] } test_transactions_response = { "result": { "transactions": ["transactions"] } } make_trace_requests_mock = MagicMock(return_value=test_trace_requests) make_transactions_requests_mock = MagicMock(return_value=test_transactions_requests) return_response_mock = MagicMock(side_effect=[test_trace_response, test_transactions_response] * 2) send_jsonrpc_request_mock = MagicMock(side_effect=lambda x, y, getter: getter(return_response_mock())) merge_block_mock = MagicMock(side_effect=[ ["merge1"], ["merge2"] ]) process = Mock( trace_request=make_trace_requests_mock, transaction_request=make_transactions_requests_mock, send=send_jsonrpc_request_mock, merge=merge_block_mock ) with patch("operations.internal_transactions._make_trace_requests", make_trace_requests_mock), \ patch("operations.internal_transactions._make_transactions_requests", make_transactions_requests_mock), \ patch("operations.internal_transactions._send_jsonrpc_request", send_jsonrpc_request_mock), \ patch("operations.internal_transactions._merge_block", merge_block_mock): result = _get_traces_sync(test_parity_hosts, test_blocks) calls = [ call.trace_request(test_parity_hosts, test_blocks), call.transaction_request(test_parity_hosts, test_blocks) ] for url, trace_request in test_trace_requests.items(): transaction_request = test_transactions_requests[url] calls += [call.send(url, trace_request, ANY), call.send(url, transaction_request, ANY)] calls += [call.merge(["trace"], ["transactions"], ["gasUsed", "gasPrice"])] process.assert_has_calls(calls) self.assertSequenceEqual(result, ["merge1", "merge2"])
def test_add_ubridge_connection_none_nio(loop, vm): nio = None vm._ubridge_hypervisor = MagicMock() loop.run_until_complete(asyncio.async(vm._add_ubridge_connection(nio, 0, 42))) calls = [ call.send("docker create_veth veth-gns3-e0 veth-gns3-i0"), call.send('docker move_to_ns veth-gns3-i0 42 eth0'), ] # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_add_ubridge_connection_none_nio(loop, vm): nio = None vm._ubridge_hypervisor = MagicMock() loop.run_until_complete(asyncio. async (vm._add_ubridge_connection( nio, 0, 42))) calls = [ call.send("docker create_veth veth-gns3-e0 veth-gns3-i0"), call.send('docker move_to_ns veth-gns3-i0 42 eth0'), ] # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_TrackDownloadsImage(monkeypatch): mocked_data = Mock() mocked_generator = Mock() mocked_data.page_num = 0 tracker = lscat.TrackDownloadsImage(mocked_data) tracker.generator = mocked_generator test_pics = [f"12345_p{idx}_master1200.jpg" for idx in list(range(10))] # No need to shuffle because updates are always in order for pic in test_pics: tracker.update(pic) assert len(mocked_generator.mock_calls ) == 20 # 10 images * 2 because of None sends assert mocked_generator.mock_calls[:4] == [ call.send('12345_p0_master1200.jpg'), call.send(None), call.send('12345_p1_master1200.jpg'), call.send(None), ] assert mocked_generator.mock_calls[-4:] == [ call.send('12345_p8_master1200.jpg'), call.send(None), call.send('12345_p9_master1200.jpg'), call.send(None), ]
def test_TrackDownloads(): mocked_data = Mock() mocked_generator = Mock() tracker = lscat.TrackDownloads(mocked_data) tracker.generator = mocked_generator test_pics = [f"{str(idx).rjust(3, '0')}_test" for idx in list(range(30))] # Shuffle list of pics for pic in random.sample(test_pics, 30): tracker.update(pic) assert len(mocked_generator.mock_calls ) == 60 # 30 images * 2 because of None sends assert mocked_generator.mock_calls[:4] == [ call.send('000_test'), call.send(None), call.send('001_test'), call.send(None), ] assert mocked_generator.mock_calls[-4:] == [ call.send('028_test'), call.send(None), call.send('029_test'), call.send(None), ]
def test_disconnected_client(self): """ Test BrokenPipeError handling on unexpected client disconnect """ socket_mock = Mock() socket_mock.send.side_effect = [None, BrokenPipeError] logger_mock = Mock() output_wrapper = Output(socket_mock, logger_mock) output_wrapper.info('info(%d)', 1) output_wrapper.info('info(%d)', 2) output_wrapper.info('info(%d)', 3) socket_mock.assert_has_calls([call.send(b'{"text": "info(1)"}\x00'), call.send(b'{"text": "info(2)"}\x00')]) logger_mock.warning.assert_has_calls([call('Control client disconnected before operation has completed')]) logger_mock.info.assert_has_calls([call('info(%d)', 1), call('info(%d)', 2), call('info(%d)', 3)])
def test_add_ubridge_connection_none_nio(loop, vm): nio = None vm._ubridge_hypervisor = MagicMock() vm._namespace = 42 loop.run_until_complete(asyncio.async(vm._add_ubridge_connection(nio, 0))) calls = [ call.send('bridge create bridge0'), call.send("bridge add_nio_tap bridge0 tap-gns3-e0"), call.send('docker move_to_ns tap-gns3-e0 42 eth0'), ] # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_lifespan_shutdown_successful(self): """ Test that the lifespan protocol shutdown events work right for an application that supports the protocol and shuts down successfully. """ # Create a mock queue and send and receive async callables that access # it. mock_queue = MagicMock() mock_queue.receive.side_effect = [{ "type": "lifespan.shutdown.complete" }] async def send(event): mock_queue.send(event) async def receive(): return mock_queue.receive() # Create the lifespan manager. uut = aioscgi.core.LifespanManager(send, receive) # At this point, nothing should have been done with the queue. self.assertFalse(mock_queue.mock_calls) # Run the lifespan shutdown process. It should return normally. with self.assertRaises(StopIteration): uut.shutdown().send(None) # The lifespan manager should send the lifespan.shutdown event, then # wait for the application to send the complete message before # returning. self.assertEqual( mock_queue.mock_calls, [call.send({"type": "lifespan.shutdown"}), call.receive()])
def test_the_pump_should_dispatch_a_command_processor(self): """ Given that I have a message pump for a channel When I read a message from that channel Then the message should be dispatched to a handler """ handler = MyCommandHandler() request = MyCommand() channel = Mock(spec=Channel) command_processor = Mock(spec=CommandProcessor) message_pump = MessagePump(command_processor, channel, map_to_message) header = BrightsideMessageHeader(uuid4(), request.__class__.__name__, BrightsideMessageType.command) body = BrightsideMessageBody(JsonRequestSerializer(request=request).serialize_to_json(), BrightsideMessageBodyType.application_json) message = BrightsideMessage(header, body) quit_message = BrightsideMessageFactory.create_quit_message() # add messages to that when channel is called it returns first message then qui tmessage response_queue = [message, quit_message] channel_spec = {"receive.side_effect" : response_queue} channel.configure_mock(**channel_spec) message_pump.run() channel_calls = [call.receive(), call.receive] channel.assert_has_calls(channel_calls) cp_calls = [call.send(request)] command_processor.assert_has_calls(cp_calls)
async def test_del_char() -> None: session = db.Session() guild_id = 555 player_id = 111 session.add( Character( guild=guild_id, player=player_id, name="name", race="race", attr_reason=5, disc_science=12, )) session.commit() cog = STA() context = MagicMock() context.author.id = player_id context.guild.id = guild_id context.guild.__bool__.return_value = True context.author.__bool__.return_value = True future: Future[bool] = asyncio.Future() future.set_result(True) context.send.return_value = future context.mock_add_spec(["guild", "author", "send"], spec_set=True) assert db.Session().query(Character).count() == 1 await STA.del_char(cog, context) assert db.Session().query(Character).count() == 0 assert context.mock_calls == [ call.guild.__bool__(), call.send("Character deleted."), ]
def test_add_ubridge_connection_none_nio(loop, vm): nio = None vm._ubridge_hypervisor = MagicMock() vm._namespace = 42 loop.run_until_complete(asyncio.ensure_future(vm._add_ubridge_connection(nio, 0))) calls = [ call.send('bridge create bridge0'), call.send("bridge add_nio_tap bridge0 tap-gns3-e0"), call.send('docker move_to_ns tap-gns3-e0 42 eth0'), ] assert 'bridge0' in vm._bridges # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_delete_ubridge_connection(loop, vm): vm._ubridge_hypervisor = MagicMock() nio = {"type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1"} nio = vm.manager.create_nio(0, nio) loop.run_until_complete(asyncio.async(vm._add_ubridge_connection(nio, 0, 42))) loop.run_until_complete(asyncio.async(vm._delete_ubridge_connection(0))) calls = [ call.send("bridge delete bridge0"), call.send('docker delete_veth veth-gns3-e0') ] vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_add_ubridge_connection(loop, vm): nio = { "type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1" } nio = vm.manager.create_nio(0, nio) nio.startPacketCapture("/tmp/capture.pcap") vm._ubridge_hypervisor = MagicMock() loop.run_until_complete(asyncio. async (vm._add_ubridge_connection( nio, 0, 42))) calls = [ call.send("docker create_veth veth-gns3-e0 veth-gns3-i0"), call.send('docker move_to_ns veth-gns3-i0 42 eth0'), call.send('bridge create bridge0'), call.send('bridge add_nio_linux_raw bridge0 veth-gns3-e0'), call.send('bridge add_nio_udp bridge0 4242 127.0.0.1 4343'), call.send('bridge start_capture bridge0 "/tmp/capture.pcap"'), call.send('bridge start bridge0') ] # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_chunk_is_received(self, client): self.create_s3_handler() self.s3_file_handler.executor = MagicMock() self.s3_file_handler.receive_data_chunk( b"test", 0, ) # Check that we started to send data self.s3_file_handler.executor.mock_calls[0] = call.send(b"4")
def test_chunk_is_received(self, http_connection): self.create_av_handler() self.clam_av_file_handler.av_conn = MagicMock() self.clam_av_file_handler.receive_data_chunk( b"test", 0, ) # Check that we started to send data self.clam_av_file_handler.av_conn.mock_calls[0] = call.send(b"4")
def test_delete_ubridge_connection(loop, vm): vm._ubridge_hypervisor = MagicMock() nio = { "type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1" } nio = vm.manager.create_nio(0, nio) loop.run_until_complete(asyncio. async (vm._add_ubridge_connection( nio, 0, 42))) loop.run_until_complete(asyncio. async (vm._delete_ubridge_connection(0))) calls = [ call.send("bridge delete bridge0"), call.send('docker delete_veth veth-gns3-e0') ] vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_normal_send(self): """ Test normal messages sending """ socket_mock = Mock() logger_mock = Mock() output_wrapper = Output(socket_mock, logger_mock) output_wrapper.info('info(%s)', 'arg1') output_wrapper.debug('debug(%s)', 'arg2') output_wrapper.error('error(%s)', 'arg3') output_wrapper.error('no_args_error(%s)') output_wrapper.log('log(%s)', 'arg4') output_wrapper.say('say(%s)', 'arg5') output_wrapper.say('no_args_say(%s)') socket_mock.assert_has_calls([ call.send(b'{"text": "info(arg1)"}\x00'), call.send(b'{"error": "error(arg3)"}\x00'), call.send(b'{"error": "no_args_error(%s)"}\x00'), call.send(b'{"text": "log(arg4)"}\x00'), call.send(b'{"text": "say(arg5)"}\x00'), call.send(b'{"text": "no_args_say(%s)"}\x00'), ]) logger_mock.assert_has_calls([ call.info('info(%s)', 'arg1'), call.debug('debug(%s)', 'arg2'), call.error('error(%s)', 'arg3'), call.error('no_args_error(%s)'), call.info('log(%s)', 'arg4'), call.info('say(%s)', 'arg5'), call.info('no_args_say(%s)'), ])
def test_search_ok(self): args = ["artist", "test"] self.search.begin_search(args) sender_calls = [call.send("search", args, self.search._on_load)] self.assertListEqual(self.sender.mock_calls, sender_calls) observer_calls = [call.search_started(self.search)] self.assertListEqual(self.observer.mock_calls, observer_calls) self.observer.reset_mock() result = CallbackResult(CALLBACK_OK, "search", args, SEARCH_RESULTS) self.search._on_load(result) observer_calls = [call.store_changed(self.search), call.search_finished(self.search)] self.assertListEqual(self.observer.mock_calls, observer_calls) expected = [Song(item) for item in SEARCH_RESULTS] self.assertListEqual(list(self.search), expected)
def test_lifespan_startup_failed(self): """ Test that the lifespan protocol startup events work right for an application that supports the protocol but fails to initialize. """ # Create a mock queue and send and receive async callables that access # it. mock_queue = MagicMock() mock_queue.receive.side_effect = [{ "type": "lifespan.startup.failed", "message": "Application failure message" }] async def send(event): mock_queue.send(event) async def receive(): return mock_queue.receive() # Create the lifespan manager. uut = aioscgi.core.LifespanManager(send, receive) # At this point, nothing should have been done with the queue. self.assertFalse(mock_queue.mock_calls) # Run the lifespan startup process. It should raise an exception, # passing on the message from the application. with self.assertRaises(aioscgi.core.ApplicationInitializationError, msg="Application failure message"): uut.startup().send(None) # The lifespan manager should send the lifespan.startup event, then # wait for the application to send the failure message before raising # its own exception. self.assertEqual( mock_queue.mock_calls, [call.send({"type": "lifespan.startup"}), call.receive()])
def test_lifespan_shutdown_failed(self): """ Test that the lifespan protocol shutdown events work right for an application that supports the protocol but fails to shut down. """ # Create a mock queue and send and receive async callables that access # it. mock_queue = MagicMock() mock_queue.receive.side_effect = [{ "type": "lifespan.shutdown.failed", "message": "Application failure message" }] async def send(event): mock_queue.send(event) async def receive(): return mock_queue.receive() # Create the lifespan manager. uut = aioscgi.core.LifespanManager(send, receive) # At this point, nothing should have been done with the queue. self.assertFalse(mock_queue.mock_calls) # Run the lifespan shutdown process. It should return normally, because # application failures during shutdown don’t really benefit from being # reraised at the call site. with self.assertRaises(StopIteration): uut.shutdown().send(None) # The lifespan manager should send the lifespan.startup event, then # wait for the application to send the failure message before raising # its own exception. self.assertEqual( mock_queue.mock_calls, [call.send({"type": "lifespan.shutdown"}), call.receive()])
def test_lifespan_not_supported(self): """ Test that the lifespan protocol works properly when the application doesn’t support it. """ # Create a mock queue and send and receive async callables that access # it. mock_queue = MagicMock() mock_queue.receive.side_effect = [None] async def send(event): mock_queue.send(event) async def receive(): return mock_queue.receive() # Create the lifespan manager. uut = aioscgi.core.LifespanManager(send, receive) # At this point, nothing should have been done with the queue. self.assertFalse(mock_queue.mock_calls) # Run the lifespan startup process. It should return normally. Lack of # support from the application should not be considered an error. with self.assertRaises(StopIteration): uut.startup().send(None) # Run the lifespan shutdown process. It should return normally, without # doing anything, because of the earlier indication of no support. with self.assertRaises(StopIteration): uut.shutdown().send(None) # The lifespan manager should send the lifespan.startup event, then # receive the indication of no support (representing the application # callback raising an exception), then not interact with the queue # again afterwards. self.assertEqual( mock_queue.mock_calls, [call.send({"type": "lifespan.startup"}), call.receive()])
def test_search_failed(self): args = ["artist", "test"] self.search.begin_search(args) sender_calls = [call.send("search", args, self.search._on_load)] self.assertListEqual(self.sender.mock_calls, sender_calls) observer_calls = [call.search_started(self.search)] self.assertListEqual(self.observer.mock_calls, observer_calls) self.observer.reset_mock() result = CallbackResult(CALLBACK_ERR_NOT_CONNECTED, "search", args, error=None) self.search._on_load(result) observer_calls = [call.store_changed(self.search), call.search_cleared(self.search), call.search_failed(self.search)] self.assertListEqual(self.observer.mock_calls, observer_calls) self.assertListEqual(list(self.search), [])
def test_add_ubridge_connection(loop, vm): nio = {"type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1"} nio = vm.manager.create_nio(0, nio) nio.startPacketCapture("/tmp/capture.pcap") vm._ubridge_hypervisor = MagicMock() loop.run_until_complete(asyncio.async(vm._add_ubridge_connection(nio, 0, 42))) calls = [ call.send("docker create_veth veth-gns3-e0 veth-gns3-i0"), call.send('docker move_to_ns veth-gns3-i0 42 eth0'), call.send('bridge create bridge0'), call.send('bridge add_nio_linux_raw bridge0 veth-gns3-e0'), call.send('bridge add_nio_udp bridge0 4242 127.0.0.1 4343'), call.send('bridge start_capture bridge0 "/tmp/capture.pcap"'), call.send('bridge start bridge0') ] # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def test_add_ubridge_connection(loop, vm): nio = {"type": "nio_udp", "lport": 4242, "rport": 4343, "rhost": "127.0.0.1"} nio = vm.manager.create_nio(nio) nio.start_packet_capture("/tmp/capture.pcap") vm._ubridge_hypervisor = MagicMock() vm._namespace = 42 loop.run_until_complete(asyncio.ensure_future(vm._add_ubridge_connection(nio, 0))) calls = [ call.send('bridge create bridge0'), call.send("bridge add_nio_tap bridge0 tap-gns3-e0"), call.send('docker move_to_ns tap-gns3-e0 42 eth0'), call.send('bridge add_nio_udp bridge0 4242 127.0.0.1 4343'), call.send('bridge start_capture bridge0 "/tmp/capture.pcap"'), call.send('bridge start bridge0') ] assert 'bridge0' in vm._bridges # We need to check any_order ortherwise mock is confused by asyncio vm._ubridge_hypervisor.assert_has_calls(calls, any_order=True)
def sent_recved(sent): return [call.send(sent), call.recv()]
def sent(sent): return [call.send(sent)]
def test_simple(self, conn_class): """ Test a simple application. """ async def app(scope, receive, send): if scope["type"] == "lifespan": raise ValueError( "Lifespan protocol not supported by this application") self.assertEqual(scope["type"], "http") self.assertEqual(scope["asgi"]["version"], "3.0") self.assertEqual(scope["asgi"]["spec_version"], "2.1") self.assertEqual(scope["http_version"], "1.1") self.assertEqual(scope["method"], "GET") self.assertEqual(scope["scheme"], "http") self.assertEqual(scope["path"], "") self.assertEqual(scope["query_string"], B"") self.assertEqual(scope["headers"], []) self.assertEqual(scope["server"], ["localhost", 80]) self.assertEqual( scope["extensions"]["environ"], { "SERVER_PROTOCOL": B"HTTP/1.1", "REQUEST_METHOD": B"GET", "QUERY_STRING": B"", "SCRIPT_NAME": B"", "SERVER_NAME": B"localhost", "SERVER_PORT": B"80", }) message = await receive() self.assertEqual(message["type"], "http.request") self.assertFalse(message.get("body")) self.assertFalse(message.get("more_body")) await send({ "type": "http.response.start", "status": 200, "headers": [(b"content-type", b"text/plain; charset=UTF-8")] }) await send({"type": "http.response.body", "body": B"Hello World!"}) conn = conn_class.return_value headers = sioscgi.RequestHeaders({ "SERVER_PROTOCOL": B"HTTP/1.1", "REQUEST_METHOD": B"GET", "QUERY_STRING": B"", "SCRIPT_NAME": B"", "SERVER_NAME": B"localhost", "SERVER_PORT": B"80" }) conn.next_event.side_effect = [headers, sioscgi.RequestEnd()] conn.send.return_value = B"" with self.assertRaises(StopIteration): aioscgi.core.Container(None).run(app, None, None).send(None) self.assertEqual(list(conn.mock_calls), [ call.next_event(), call.next_event(), call.send( EventMatcher( sioscgi.ResponseHeaders("200 OK", [ ("Content-Type", "text/plain; charset=UTF-8") ]))), call.send(EventMatcher(sioscgi.ResponseBody(B"Hello World!"))), call.send(EventMatcher(sioscgi.ResponseEnd())) ])
def test_TrackDownloadsUser(): mocked_data = Mock() mocked_data.splitpoint = 30 mocked_generator = Mock() tracker = lscat.TrackDownloadsUsers(mocked_data) tracker.generator = mocked_generator test_pics = [f"{str(idx).rjust(3, '0')}_test" for idx in list(range(120))] # Shuffle list of pics for pic in random.sample(test_pics, 120): tracker.update(pic) assert len(mocked_generator.mock_calls ) == 240 # 120 images * 2 because of None sends assert mocked_generator.mock_calls[:8] == [ call.send('000_test'), call.send(None), call.send('030_test'), call.send(None), call.send('031_test'), call.send(None), call.send('032_test'), call.send(None), ] assert mocked_generator.mock_calls[-8:] == [ call.send('029_test'), call.send(None), call.send('117_test'), call.send(None), call.send('118_test'), call.send(None), call.send('119_test'), call.send(None), ]
def test_signup_check_less_than_10_signups(self): self.pregame.signups = [x for x in range(8)] result = OneHeadAsyncTest._run(self.pregame.signup_check(self.ctx)) self.assertEqual(self.ctx.method_calls[0], call.send('Only 8 Signup(s), require 2 more.')) self.assertFalse(result)
def test_signup_check_single_signup(self): self.pregame.signups = [1] result = OneHeadAsyncTest._run(self.pregame.signup_check(self.ctx)) self.assertEqual(self.ctx.method_calls[0], call.send('Only 1 Signup(s), require 9 more.')) self.assertFalse(result)
def test_signup_check_zero_signups(self): self.pregame.signups = [] result = OneHeadAsyncTest._run(self.pregame.signup_check(self.ctx)) self.assertEqual(self.ctx.method_calls[0], call.send('There are currently no signups.')) self.assertFalse(result)