def test_deletelistinfo(self, mock_launchcmd): """ test the delete method :param mock_launchcmd: :return: """ test_data = {"deleteinfo": ["aa,ALL,deny"]} post_data = json.dumps(test_data) file_object = open('thefile5', 'w') file_object.write("# test\naa:ALL:deny") file_object.close() mock_launchcmd.return_value = open("thefile5", 'r') with patch('__builtin__.open'): mock_open = open('thefile5', 'w+') response = self.client.delete("/tcp/deny/", data=post_data, content_type="application/json") # print mock_open.method_calls self.assertListEqual(mock_open.method_calls, [call.writelines(['# test\n']), call.close()]) self.assertEqual(response.status_code, 200)
def test_putlistinfo(self, mock_open): """ test the add method :param mock_open: :return: """ test_data = { "addInfo": { "daemon": "ahayou", "hosts": "ALL", "command": "deny" } } post_data = json.dumps(test_data) mock_open.return_value = open('testfiel', 'a') response = self.client.post("/tcp/deny/", data=post_data, content_type="application/json") # print mock_open.return_value.method_calls == [call.write('ahayou:ALL:deny\n'), call.close()] # print mock_open.return_value.method_calls self.assertListEqual(mock_open.return_value.method_calls, [call.write('ahayou:ALL:deny\n'), call.close()]) self.assertEqual(response.status_code, 200)
def test_process_work_queue_calls_close_after_commit(session): message = messages.Message(topic='annotation', payload='bar') queue = [message] streamer.process_work_queue({}, queue, session_factory=lambda: session) assert session.method_calls[-2:] == [call.commit(), call.close()]
def test_process_work_queue_calls_close_after_commit(session): message = messages.Message(topic="annotation", payload="bar") queue = [message] streamer.process_work_queue({}, queue, session_factory=lambda _: session) assert session.method_calls[-2:] == [call.commit(), call.close()]
def test_when_stop_db_and_no_commit_and_good_db_name_then_db_stopped( copyfile_mock, db, connection_mock ): db._connections["transactions"] = connection_mock db.stop_db("transactions", commit=False) connection_mock.assert_has_calls([call.close()]) assert call.commit() not in connection_mock.mock_calls copyfile_mock.assert_not_called()
def test_process_work_queue_calls_close_after_rollback(session): message = messages.Message(topic='foo', payload='bar') queue = [message] messages.handle_message.side_effect = RuntimeError('explosion') streamer.process_work_queue({}, queue, session_factory=lambda: session) assert session.method_calls[-2:] == [call.rollback(), call.close()]
def test_process_work_queue_calls_close_after_rollback(session): message = messages.Message(topic="foo", payload="bar") queue = [message] messages.handle_message.side_effect = RuntimeError("explosion") streamer.process_work_queue({}, queue, session_factory=lambda _: session) assert session.method_calls[-2:] == [call.rollback(), call.close()]
def test_close(self, sender): sender.close() assert sender._retry_time == 0 assert next(sender._wait_time) == 1.0 mock = sender._sock = MagicMock(spec=socket.socket) sender.close() assert mock.method_calls == [call.close()] assert sender._sock == None assert sender._retry_time == 0 assert next(sender._wait_time) == 1.0
def test__exit__(slot): slot._keepalive_window = 10 slot.__exit__(None, None, None) assert call.close() in slot._repl_cursor.method_calls assert call.close() in slot._repl_conn.method_calls assert call.close() in slot._normal_conn.method_calls assert call.join(timeout=13) in slot._keepalive_thread.method_calls slot._repl_cursor.close = Mock(side_effect=Exception) slot._repl_conn.close = Mock(side_effect=Exception) slot._normal_conn.close = Mock(side_effect=Exception) slot._keepalive_thread.join = Mock(side_effect=Exception) slot.__exit__(None, None, None) assert slot._keepalive_thread.join.called assert slot._repl_cursor.close.called, "Still called even thought call above raised" assert slot._repl_conn.close.called, "Still called even thought call above raised" assert slot._normal_conn.close.called, "Still called even thought call above raised"
def test_process_work_queue_calls_close_after_commit(session): message = nsq.Message(topic='foo', payload='bar') queue = [message] streamer.process_work_queue({}, queue, session_factory=lambda: session) assert session.method_calls[-2:] == [ call.commit(), call.close() ]
def run_decrypt(self, mio, mdf, dest_is_none=False): lk = self.get_local_keyring() input, output = mio.return_value content = Mock(name='content') source = Mock(name='source') dest = None if dest_is_none else Mock(name='dest') check_mode = Mock(name='check_mode') passphrase = Mock(name='passphrase') r, c = lk.decrypt(passphrase=passphrase, content=content, source=source, dest=dest, check_mode=check_mode) mio.assert_called_once_with(content, source, dest, check_mode) mdf.assert_called_once_with(input, output_file=output, passphrase=passphrase) self.assertIn(call.close(), input.mock_calls) if not dest_is_none: self.assertIn(call.close(), output.mock_calls) else: self.assertNotIn(call.close(), output.mock_calls) return r, c
def test_fetch(self): #Fetchable 1 should not be called because False is returned as the fetch decision. mock_f1 = MagicMock(spec=Blog, name="f1") #Fetchable 2 should be called, but does not return any warc records or additional fetchables. mock_f2 = MagicMock(spec=Blog, name="f2") mock_f2.fetch.return_value = (None, None) #Fetchable 4 returns 2 warc records, which should be passed to warc writer. mock_wr1 = MagicMock(name="warc record1") mock_wr2 = MagicMock(name="warc record2") mock_f4 = MagicMock(spec=Blog, name="f4") mock_f4.fetch.return_value = ((mock_wr1, mock_wr2), None) #Fetchable 3 should be called and return fetchable 4. mock_f3 = MagicMock(spec=Blog, name="f3") mock_f3.fetch.return_value = (None, (mock_f4,)) #Fetchable 5 is an UnknownResource which will return fetchable 6. #Fetchable 6 should be at depth 1 (instead of 2). mock_f6 = MagicMock(spec=Blog, name="f6") mock_f6.fetch.return_value = (None, None) mock_f5 = MagicMock(spec=UnknownResource, name="f5") mock_f5.fetch.return_value = (None, (mock_f6,)) #Fetch strategy mock_fs = MagicMock(spec=DefaultFetchStrategy) mock_fs.fetch_decision.side_effect = (False, True, True, True, True, True) #Warc mock_ww = MagicMock(spec=WarcWriter) sfh = SocialFeedHarvester([], fetch_strategy=mock_fs, warc_writer=mock_ww) sfh._fetchable_queue.add((mock_f1, mock_f2, mock_f3, mock_f5)) sfh.fetch() self.assertFalse(mock_f1.fetch.called) self.assertTrue(mock_f2.fetch.called) self.assertTrue(mock_f3.fetch.called) self.assertTrue(mock_f4.fetch.called) self.assertTrue(mock_f5.fetch.called) self.assertTrue(mock_f6.fetch.called) self.assertEqual([call.fetch_decision(mock_f1, 1), call.fetch_decision(mock_f2, 1), call.fetch_decision(mock_f3, 1), call.fetch_decision(mock_f5, 1), call.fetch_decision(mock_f4, 2), call.fetch_decision(mock_f6, 1)], mock_fs.mock_calls) self.assertEqual([call.write_record(mock_wr1), call.write_record(mock_wr2), call.close()], mock_ww.mock_calls)
def test_process_work_queue_calls_close_after_rollback(session): message = nsq.Message(topic='foo', payload='bar') queue = [message] nsq.handle_message.side_effect = RuntimeError('explosion') streamer.process_work_queue({}, queue, session_factory=lambda: session) assert session.method_calls[-2:] == [ call.rollback(), call.close() ]
def run_sign(self, mio, msf, mgst, clearsign, detached, armor, dest_is_none=False): lk = self.get_local_keyring() input, output = mio.return_value content = Mock(name='content') source = Mock(name='source') key_id = Mock('key_id') type = Mock(name='type') dest = None if dest_is_none else Mock(name='dest') check_mode = Mock(name='check_mode') passphrase = Mock(name='passphrase') r, c = lk.sign(content=content, source=source, key_id=key_id, dest=dest, type=type, check_mode=check_mode, passphrase=passphrase) mio.assert_called_once_with(content, source, dest, check_mode) msf.assert_called_once_with(input, output_file=output, keyid=key_id, clearsign=clearsign, detached=detached, armor=armor, passphrase=passphrase) self.assertIn(call.close(), input.mock_calls) if not dest_is_none: self.assertIn(call.close(), output.mock_calls) else: self.assertNotIn(call.close(), output.mock_calls) return r, c
def test_stream_handle_read_event_processes_recv_buffer_before_closing(self): # to ensure we don't reintroduce issue #41 stream = Stream() stream._socket_recv = MagicMock(return_value=None) manager = MagicMock() stream._process_recv_buffer = manager._process_recv_buffer stream.close = manager.close stream._handle_read_event() expected_calls = [call._process_recv_buffer(), call.close(flush=False)] self.assertTrue(manager.mock_calls == expected_calls)
def run_encrypt(self, mio, mef, dest_is_none=False): lk = self.get_local_keyring() input, output = mio.return_value recipients = Mock(name='recipients') content = Mock(name='content') source = Mock(name='source') dest = None if dest_is_none else Mock(name='dest') check_mode = Mock(name='check_mode') passphrase = Mock(name='passphrase') sign = Mock() key_id = Mock() r, c = lk.encrypt(recipients, passphrase=passphrase, content=content, source=source, dest=dest, check_mode=check_mode, sign=sign, key_id=key_id) mio.assert_called_once_with(content, source, dest, check_mode) mef.assert_called_once_with(input, recipients, output_file=output, sign=sign, keyid=key_id, passphrase=passphrase) self.assertIn(call.close(), input.mock_calls) if not dest_is_none: self.assertIn(call.close(), output.mock_calls) else: self.assertNotIn(call.close(), output.mock_calls) return r, c
def test_stream_handle_read_event_processes_recv_buffer_before_closing( self): # to ensure we don't reintroduce issue #41 stream = Stream() stream._socket_recv = MagicMock(return_value=None) manager = MagicMock() stream._process_recv_buffer = manager._process_recv_buffer stream.close = manager.close stream._handle_read_event() expected_calls = [call._process_recv_buffer(), call.close(flush=False)] self.assertTrue(manager.mock_calls == expected_calls)
def test_nonconcurrent_clients_get_different_buffer(self): buffer_factory = Mock(name='buffer_factory', spec=()) manager = self.make_one(buffer_factory=buffer_factory, stop_stream_holdoff=0) with manager as stream1: self.assertIs(manager._buffer, buffer_factory.return_value) self.assertEqual(buffer_factory.mock_calls, [call()]) self.assertEqual(buffer_factory.mock_calls, [call(), call().close()]) new_buffer = Mock(name='new streambuffer') buffer_factory.return_value = new_buffer with manager as stream2: self.assertIs(manager._buffer, new_buffer) self.assertEqual(new_buffer.mock_calls, []) self.assertEqual(new_buffer.mock_calls, [call.close()])
def test_if_zaxis_control_specifed_should_call_start_and_stop_correctly(self, mock_ZAxisControl, mock_LayerGenerator,mock_AudioWriter,mock_PathToAudio,mock_ZAxis,mock_LaserControl): mock_zaxis_control = mock_ZAxisControl.return_value mock_laser_control = mock_LaserControl.return_value mock_path_to_audio = mock_PathToAudio.return_value mock_audio_writer = mock_AudioWriter.return_value mock_zaxis = mock_ZAxis.return_value zaxis_return_values = [ 0.0, 0.0, 2.0, 2.0,2.0,2.0 ] def z_axis_side_effect(): return zaxis_return_values.pop(0) mock_zaxis.current_z_location_mm = z_axis_side_effect test_layer1 = Layer(0.0,[ LateralDraw([0.0,0.0],[2.0,2.0],2.0), LateralDraw([2.0,2.0],[-1.0,-1.0],2.0) ]) test_layer2 = Layer(1.0,[ LateralDraw([0.0,0.0],[2.0,2.0],2.0), LateralDraw([2.0,2.0],[-1.0,-1.0],2.0) ]) test_layer3 = Layer(2.0,[ LateralDraw([0.0,0.0],[2.0,2.0],2.0), LateralDraw([2.0,2.0],[-1.0,-1.0],2.0) ]) stub_layer_generator = StubLayerGenerator([test_layer1, test_layer2, test_layer3]) mock_path_to_audio.process.return_value = "SomeAudio" mock_laser_control.modulate.return_value = "SomeModulatedAudio" self.controller = Controller(mock_laser_control,mock_path_to_audio,mock_audio_writer,stub_layer_generator,zaxis = mock_zaxis, zaxis_control = mock_zaxis_control, max_lead_distance = 0) self.controller.start() self.wait_for_controller() expected_calls = [ call.move_up(), call.stop(), call.stop(), call.close()] actual = [ c for c in mock_zaxis_control.mock_calls if c != call.__nonzero__() ] self.assertEquals(expected_calls, actual)
def test__send__FullMessages(sock_mock): # The test assume that the socket is always correctly connected when # fileno is queried sock_mock().fileno.return_value = 11 message = 'ACommandWithParameters:#P1#P2;' msg_reply = 'ACommandWithParameters:done;' sock_mock().send.return_value = len(message) sock_mock().recv.return_value = msg_reply.encode() sock_conn = SocketConnector(host='127.0.0.3', port=10006) reply = sock_conn.__send__(message) assert reply == msg_reply sock_calls = [ call.connect(('127.0.0.3', 10006)), call.send(message.encode()), # call.shutdown(socket.SHUT_WR), call.recv(1024), call.fileno(), # This from is_connected() call.close() ] sock_mock().assert_has_calls(sock_calls)
def test_when_stop_db_and_commit_and_good_db_name_then_db_stopped( copyfile_mock, datetime_mock, db, connection_mock ): datetime_mock.now = MagicMock(return_value=datetime(2999, 12, 31, 23, 59, 59)) db._connections["transactions"] = connection_mock db.stop_db("transactions", commit=True) connection_mock.assert_has_calls([call.commit(), call.close()]) copyfile_mock.assert_has_calls( [ call( os.sep.join(["C:", "base", "db", "path", "current", "transactions.db"]), os.sep.join( [ "C:", "base", "db", "path", "backup", "transactions_29991231235959.db", ] ), ) ] )
def test_guestfs_conn_ro_teardown(self, mock_gfs): with guestfs_tools.guestfs_conn_ro(disk='dummy') as conn: pass assert call.add_drive_ro('dummy') in conn.mock_calls assert conn.mock_calls[-1] == call.close() assert conn.mock_calls[-2] == call.shutdown()
def test_receives_before_sending_if_so_requested(self): tcp_communication(PORT, receive_first=True) calls = [call.recv(ANY), call.close()] assert_equal(calls, self.conn.method_calls)
def test_deploy_view_ftp_transfer_gh_data(self, mock_curl_connection, mock_current_task): """deploy view transfer data from bitbucket to ftp""" ftp = self.ftp_connection() mock_curl = MagicMock(name='curl') mock_curl_connection.return_value = mock_curl mock_curl.perform = MagicMock(name='curl_perform_added', side_effect=['content added file1', 'content added file2', 'content added file3']) # test create files payload = self.payload.gh_payload_added() task = TaskFactory(service=self.service_gh) deploy = Deploy('host', payload, self.service_ftp_gh, task.name) deploy.perform() service = Service.objects.get(pk=self.service_ftp_gh.pk) self.assertTrue(service.log_set.all()[0].status) # test task is removed after success deploy self.assertFalse(service.task_set.all().exists()) self.assertEqual(self.ftp_read_file(ftp, 'file1.txt'), b'content added file1') self.assertEqual(self.ftp_read_file(ftp, 'folder1/file2.txt'), b'content added file2') self.assertEqual(self.ftp_read_file(ftp, 'folder1/folder2/folder3/file3.txt'), b'content added file3') mock_curl.assert_has_calls([call.authenticate(), call.close()]) calls = ([call('https://raw.github.com/Owner/repo_slug/2fa93a45f6c4f9fe30e54036fe0cf764fae0b2a2/file1.txt'), call('https://raw.github.com/Owner/repo_slug/2fa93a45f6c4f9fe30e54036fe0cf764fae0b2a2/folder1/file2.txt'), call('https://raw.github.com/Owner/repo_slug/2fa93a45f6c4f9fe30e54036fe0cf764fae0b2a2/folder1/folder2/folder3/file3.txt')]) # test celery update progress mock_current_task.assert_has_calls([call.update_state(state='PROGRESS', meta={'status': 0, 'file': u'file1.txt'}), call.update_state( state='PROGRESS', meta={'status': 33, 'file': u'file2.txt'}), call.update_state(state='PROGRESS', meta={'status': 66, 'file': u'file3.txt'})]) mock_curl.perform.assert_has_calls(calls) # test modify files mock_curl.perform = MagicMock(name='curl_perform_modified', side_effect=['content modified file1', 'content modified file3']) payload = self.payload.gh_payload_modified() task = TaskFactory(service=self.service_gh) deploy = Deploy('host', payload, self.service_ftp_gh, task.name) deploy.perform() service = Service.objects.get(pk=self.service_ftp_gh.pk) self.assertTrue(service.log_set.all()[1].status) self.assertEqual(self.ftp_read_file(ftp, 'file1.txt'), b'content modified file1') self.assertEqual(self.ftp_read_file(ftp, 'folder1/folder2/folder3/file3.txt'), b'content modified file3') # test remove files 1 payload = self.payload.gh_payload_removed1() task = TaskFactory(service=self.service_gh) deploy = Deploy('host', payload, self.service_ftp_gh, task.name) deploy.perform() service = Service.objects.get(pk=self.service_ftp_gh.pk) self.assertTrue(service.log_set.all()[2].status) self.assertNotIn('folder2', ftp.nlst('folder1')) # test remove files 2 payload = self.payload.gh_payload_removed2() task = TaskFactory(service=self.service_gh) deploy = Deploy('host', payload, self.service_ftp_gh, task.name) deploy.perform() service = Service.objects.get(pk=self.service_ftp_gh.pk) self.assertTrue(service.log_set.all()[3].status) self.assertNotIn('folder1', ftp.nlst()) self.assertNotIn('file1.txt', ftp.nlst()) ftp.quit()
def test_sends_requests_receives_replies(self): tcp_communication(PORT, requests=[REQUEST]) calls = [call.sendall(REQUEST), call.recv(ANY), call.close()] assert_equal(calls, self.conn.method_calls)
def test_fetch_weather_data(self, retrieve_function): p1 = Mock() with patch('weathervane.datasources.BuienradarParser.parse', return_value='') as parser: fetch_weather_data(p1, 0) p1.assert_has_calls([call.send(''), call.close()])
def test_close(self, handler): with patch('logging.Handler') as mock: handler.close() assert mock.method_calls == [call.close(handler)]
def test_close(self, generic_dao, postgres_mock): db = postgres_mock.return_value generic_dao.close() assert db.mock_calls == [call.close()]
def test_disconnect(self): self._subject.disconnect() assert_that(self._subject._sock.mock_calls, equal_to([call.close()]))
def test_close(self, generic_dao, mysql_mock): db = mysql_mock.return_value generic_dao.close() assert db.mock_calls == [call.close()]
def test_curl_close_method_close_current_curl_connection(self): curl = curl_connection('curl_username', 'curl_password') curl.curl = MagicMock(name='mock_curl') curl.close() curl.curl.assert_has_calls(call.close())