def test_no_data(self): source = unittest.mock.Mock() dest = unittest.mock.Mock() source.recv.side_effect = "" OneWayThread(source, dest).run() source.sendall.assert_has_calls = [call.recv(4096), call.close()] dest.sendall.assert_has_calls = [call.close()]
def test_too_many(self): source = unittest.mock.MagicMock() dest = unittest.mock.MagicMock() source.recv.side_effect = b'fubar' OneWayThread(source, dest, limit=2).run() source.sendall.assert_has_calls = [call.recv(4096), \ call.recv(4096), call.close()] dest.sendall.assert_has_calls = [ \ call.sendall('f'), \ call.sendall('u'), \ call.close()]
def test_simple_data(self): source = unittest.mock.Mock() dest = unittest.mock.Mock() source.recv.side_effect = b'fubar' OneWayThread(source, dest).run() source.sendall.assert_has_calls = [call.recv(4096), call.close()] dest.sendall.assert_has_calls = [ \ call.sendall('f'), \ call.sendall('u'), \ call.sendall('b'), \ call.sendall('a'), \ call.sendall('r'), \ call.close()]
def test_finish_logging_request_no_response_id(self): self.LOGGER.result = 'Error' pubreq = DebugPublicRequest() pubreq.finish_logging_request(self.LOGGER, None, None) self.assertEqual(self.LOGGER.mock_calls, [call.close(properties=[], references=[])]) self.assertEqual(self.LOGGER.result, 'Fail')
def test_get_must_call_query_and_close(self): #Arrange db_mock = Mock() model_mock = Mock() model_mock.deleted_at = None filter_mock = Mock() db_mock.query = Mock(return_value=filter_mock) filter_mock.filter.return_value = 'response' repository = Repository() repository.set_db(db_mock) #Action response = repository.get(model_mock) #Asserts self.assertEqual(response, 'response') db_mock_calls = db_mock.mock_calls self.assertEqual(len(db_mock_calls), 2) db_mock.assert_has_calls([ call.query(model_mock), call.close() ]) filter_mock_calls =filter_mock.mock_calls self.assertEqual(len(filter_mock_calls), 1) filter_mock.asssert_has_calls([ call.filter(True) ])
def test_one_part(self): utils.split_file_by_parts(self.testfile, 1) FAKEOPEN.assert_called_once_with('testfile-1.txt', 'w') self.assertEqual( FAKEFILE.method_calls, [call.writelines(self.lines), call.close()] )
def test_finish_logging_request(self): self.LOGGER.result = 'Error' pubreq = DebugPublicRequest() pubreq.finish_logging_request(self.LOGGER, 42, None) self.assertEqual( self.LOGGER.mock_calls, [call.close(properties=[], references=[('publicrequest', 42)])]) self.assertEqual(self.LOGGER.result, 'Ok')
def test_finish_logging_request_unexpected_exception(self): self.LOGGER.result = 'Error' pubreq = DebugPublicRequest() pubreq.finish_logging_request(self.LOGGER, None, TestException()) self.assertEqual(self.LOGGER.mock_calls, [ call.close(properties=[('exception', 'TestException')], references=[]) ]) self.assertEqual(self.LOGGER.result, 'Error')
def test_close_filenos_maxfd_12(self): self.resource_mock.getrlimit.return_value = (12, 12) calls = [call.close(0), call.close(3), call.close(5), call.close(6), call.close(7), call.close(8), call.close(10), call.close(11)] pep3143daemon.daemon.close_filenos(set((1, 2, 4, 9))) self.os_mock.assert_has_calls(calls)
def test_finish_logging_request_with_known_exception(self): self.LOGGER.result = 'Error' pubreq = DebugPublicRequest() pubreq.finish_logging_request( self.LOGGER, None, PublicRequestKnownException(type(OBJECT_NOT_FOUND()).__name__)) self.assertEqual(self.LOGGER.mock_calls, [ call.close(properties=[('reason', 'OBJECT_NOT_FOUND')], references=[]) ]) self.assertEqual(self.LOGGER.result, 'Fail')
def _make_expected_write_calls(self, lines, lines_per_file, header=False): expected_write_calls = [] start_line = 1 if header else 0 for i in range(start_line, len(lines), lines_per_file): if header: expected_write_calls.append(call.write(self.lines[0])) expected_write_calls.append( call.writelines(lines[i:i+lines_per_file])) expected_write_calls.append(call.close()) return expected_write_calls
def test___del__(self): mock = MagicMock() tested = BinaryLoggerBis(self.log_file) tested.file_handle.close() # the file handle is correctly closed on instance destruction tested.file_handle = mock del tested expected = [ call.__bool__(), call.close(), ] self.assertEqual(expected, mock.mock_calls)
def test_mux_with_failure(mux_tr, my_tr, my_ftr): mux_tr += my_ftr mux_tr += my_tr # notice that the mux_tr raises a TransportError wrapping the subtransport's # exceptions (in this case, a single MyTransportError). with pytest.raises(TransportError) as excinfo: mux_tr.start() # my_tr starts normally, then is stopped when the other one fails. assert my_tr.mock_calls == [call.open(), call.run(), call.close()] assert my_ftr.mock_calls == [call.open()] assert len(excinfo.value.exceptions) == 1 assert isinstance(excinfo.value.exceptions[0], MyTransportError)
def test_close_connection(self): mock_ssh = MagicMock() close_ssh_session(ssh=mock_ssh) self.assertEqual( first=[ call.exec_command(command='quit'), call.close() ], second=mock_ssh.mock_calls, msg='Calls the command "quit" in the SSH session and closes the session' )
def test_close_filenos_maxfd_12(self): self.resource_mock.getrlimit.return_value = (12, 12) calls = [ call.close(0), call.close(3), call.close(5), call.close(6), call.close(7), call.close(8), call.close(10), call.close(11) ] pep3143daemon.daemon.close_filenos(set((1, 2, 4, 9))) self.os_mock.assert_has_calls(calls)
def test_open_first_fork_child_second_fork_child_and_pitfile(self): self.os_mock.fork = MagicMock(side_effect=[0, 0]) self.daemoncontext.pidfile = Mock() terminate = getattr(self.daemoncontext, 'terminate') self.daemoncontext.signal_map = { self.signal_mock.SIGTSTP: None, self.signal_mock.SIGTTIN: None, self.signal_mock.SIGTTOU: None, self.signal_mock.SIGTERM: 'terminate' } self.daemoncontext.open() self.os_mock.assert_has_calls([ call.getuid(), call.getgid(), call.chdir('/'), call.setgid(54321), call.setuid(12345), call.umask(0), call.fork(), call.setsid(), call.fork(), call.close(0), call.open(self.os_mock.devnull, self.os_mock.O_RDWR), call.dup2(self.os_mock.open(), self.sys_mock.stdin.fileno()), call.open(self.os_mock.devnull, self.os_mock.O_RDWR), call.dup2(self.os_mock.open(), self.sys_mock.stdout.fileno()), call.open(self.os_mock.devnull, self.os_mock.O_RDWR), call.dup2(self.os_mock.open(), self.sys_mock.stderr.fileno()) ]) self.resource_mock.assert_has_calls([ call.setrlimit(self.resource_mock.RLIMIT_CORE, (0, 0)), call.getrlimit(2048) ]) self.signal_mock.assert_has_calls([ call.signal(self.signal_mock.SIGTSTP, self.signal_mock.SIG_IGN), call.signal(self.signal_mock.SIGTERM, terminate), call.signal(self.signal_mock.SIGTTIN, self.signal_mock.SIG_IGN), call.signal(self.signal_mock.SIGTTOU, self.signal_mock.SIG_IGN) ], any_order=True) self.sys_mock.assert_has_calls([ call.stdin.fileno(), call.stdout.fileno(), call.stderr.fileno(), call.stdin.fileno(), call.stdout.fileno(), call.stderr.fileno() ]) self.daemoncontext.pidfile.assert_has_calls([call.acquire()])
def test_open_sftp(self): ssh = MagicMock() with open_sftp(ssh=ssh) as sftp: self.assertEqual( first=ssh.open_sftp.return_value, second=sftp, msg='Returns an sftp opened from the ssh passed' ) self.assertIn( member=call.open_sftp(), container=ssh.mock_calls, msg='Opens the sftp from the ssh passed' ) self.assertNotIn( member=call.close(), container=sftp.mock_calls, msg='Does not close the sftp while the context is open' ) self.assertIn( member=call.close(), container=sftp.mock_calls, msg='Closes the sftp after the context is closed' )
def test_save(self, fp, mocked_open, mocked_os): # Prepare test self.cache.clean = Mock() self.cache.fp = fp # Execute test self.cache.save() # Evaluate results expected = [call.__bool__(), call.close()] self.assertEqual(expected, fp.mock_calls, ASSERT_MOCK_CALLS) expected = [call(self.cache.cache_file, 'w')] self.assertEqual(expected, mocked_open.mock_calls, ASSERT_MOCK_CALLS) expected = [call.unlink(self.cache.cache_file)] self.assertEqual(expected, mocked_os.mock_calls, ASSERT_MOCK_CALLS) self.cache.clean.assert_called_with(persist=True)
def test_close_must_call_the_close(self): #Arrange db_mock = Mock() repository = Repository() repository.set_db(db_mock) #Action repository.close() #Asserts db_mock_calls = db_mock.mock_calls self.assertEqual(1, len(db_mock_calls)) db_mock.assert_has_calls([ call.close() ])
def test_exit(self, mock_sessionmaker): ds = DatabaseSession() session = MagicMock() ds.session = session ds.__exit__(None, None, None) session.assert_has_calls([ call.flush(), call.expunge_all(), call.close(), ]) session.rollback.assert_not_called() self.assertIsNone(ds.session) session.reset_mock() ds.session = session ds.__exit__('exc type', 'exc val', 'exc tb') session.assert_has_calls( [call.rollback(), call.expunge_all(), call.close()]) session.flush.assert_not_called() self.assertIsNone(ds.session)
def test_open_first_fork_child_second_fork_child_and_pitfile(self): self.os_mock.fork = MagicMock(side_effect=[0, 0]) self.daemoncontext.pidfile = Mock() terminate = getattr(self.daemoncontext, 'terminate') self.daemoncontext.signal_map = { self.signal_mock.SIGTSTP: None, self.signal_mock.SIGTTIN: None, self.signal_mock.SIGTTOU: None, self.signal_mock.SIGTERM: 'terminate'} self.daemoncontext.open() self.os_mock.assert_has_calls( [call.getuid(), call.getgid(), call.chdir('/'), call.setgid(54321), call.setuid(12345), call.umask(0), call.fork(), call.setsid(), call.fork(), call.close(0), call.open(self.os_mock.devnull, self.os_mock.O_RDWR), call.dup2(self.os_mock.open(), self.sys_mock.stdin.fileno()), call.open(self.os_mock.devnull, self.os_mock.O_RDWR), call.dup2(self.os_mock.open(), self.sys_mock.stdout.fileno()), call.open(self.os_mock.devnull, self.os_mock.O_RDWR), call.dup2(self.os_mock.open(), self.sys_mock.stderr.fileno())]) self.resource_mock.assert_has_calls( [call.setrlimit(self.resource_mock.RLIMIT_CORE, (0, 0)), call.getrlimit(2048)]) self.signal_mock.assert_has_calls( [call.signal(self.signal_mock.SIGTSTP, self.signal_mock.SIG_IGN), call.signal(self.signal_mock.SIGTERM, terminate), call.signal(self.signal_mock.SIGTTIN, self.signal_mock.SIG_IGN), call.signal(self.signal_mock.SIGTTOU, self.signal_mock.SIG_IGN)], any_order=True) self.sys_mock.assert_has_calls( [call.stdin.fileno(), call.stdout.fileno(), call.stderr.fileno(), call.stdin.fileno(), call.stdout.fileno(), call.stderr.fileno()]) self.daemoncontext.pidfile.assert_has_calls( [call.acquire()] )
def test_save_must_save_the_model(self): #Arrange db_mock = Mock() repository = Repository() repository.set_db(db_mock) #Action repository.save('model') #Asserts db_mock_calls = db_mock.mock_calls self.assertEqual(4, len(db_mock_calls)) db_mock.assert_has_calls([ call.add('model'), call.commit(), call.refresh('model'), call.close(), ])
def test_pre_ping_weakref_finalizer(self): pool = self._pool_fixture(pre_ping=True) conn = pool.connect() old_dbapi_conn = conn.dbapi_connection conn.close() # no cursor() because no pre ping eq_(old_dbapi_conn.mock_calls, [call.rollback()]) conn = pool.connect() conn.close() # connect again, we see pre-ping eq_( old_dbapi_conn.mock_calls, [call.rollback(), call.cursor(), call.rollback()], ) self.dbapi.shutdown("execute", stop=True) self.dbapi.restart() conn = pool.connect() dbapi_conn = conn.dbapi_connection del conn gc_collect() # new connection was reset on return appropriately eq_(dbapi_conn.mock_calls, [call.rollback()]) # old connection was just closed - did not get an # erroneous reset on return eq_( old_dbapi_conn.mock_calls, [ call.rollback(), call.cursor(), call.rollback(), call.cursor(), call.close(), ], )
def test_get_by_id_must_call_query_and_get(self): #Arrange db_mock = Mock() repository = Repository() repository.set_db(db_mock) #Action response = repository.get_by_id('Model', 'id') #Asserts db_mock_calls = db_mock.mock_calls self.assertEqual(len(db_mock_calls), 3) db_mock.assert_has_calls([ call.query('Model'), call.query().get('id'), call.close() ]) self.assertEqual(response, db_mock.query().get())
async def test_invalid_initial_response(mock_aio_protocol): """Test we try switching protocol if we an unexpected response.""" light = AIOWifiLedBulb("192.168.1.166", timeout=0.1) def _updated_callback(*args, **kwargs): pass task = asyncio.create_task(light.async_setup(_updated_callback)) transport, protocol = await mock_aio_protocol() light._aio_protocol.data_received(b"\x31\x25") with pytest.raises(RuntimeError): await task assert transport.mock_calls == [ call.get_extra_info("peername"), call.write(bytearray(b"\x81\x8a\x8b\x96")), call.write_eof(), call.close(), ] assert not light.available
async def test_no_initial_response(mock_aio_protocol): """Test we try switching protocol if we get no initial response.""" light = AIOWifiLedBulb("192.168.1.166", timeout=0.1) assert light.protocol is None def _updated_callback(*args, **kwargs): pass task = asyncio.create_task(light.async_setup(_updated_callback)) transport, protocol = await mock_aio_protocol() with pytest.raises(RuntimeError): await task assert transport.mock_calls == [ call.get_extra_info("peername"), call.write(bytearray(b"\x81\x8a\x8b\x96")), call.write_eof(), call.close(), ] assert not light.available assert light.protocol is PROTOCOL_LEDENET_ORIGINAL
def test_close(self, fp): # Prepare test self.key = self.test_close.__name__ self.cache.fp = fp self.cache.cache_dict[self.key] = self.cache_entry self.cache.count = 1 # Execute test self.cache.close() # Evaluate internal state (attribute values) self.assertIsNone(self.cache.fp, ASSERT_INVALID_VALUE_FMT.format('sr_cache.fp')) self.assertDictEqual( {}, self.cache.cache_dict, ASSERT_INVALID_VALUE_FMT.format('sr_cache.cache_dict')) self.assertEqual(0, self.cache.count, ASSERT_INVALID_VALUE_FMT.format('sr_cache.count')) # Evaluate external calls expected = [call.flush(), call.close()] self.assertEqual(expected, fp.mock_calls)
def test_conn_close_called_on_close(self): mock_conn = Mock() create_func = Mock(return_value=mock_conn) pool = DBConnectionPool(create_func, min_size=2, max_size=2) pool.close() mock_conn.assert_has_calls([call.close(), call.close()])
def test_mux_add_after_start(mux_tr, my_tr): mux_tr.start() mux_tr += my_tr mux_tr -= my_tr mux_tr.stop() assert my_tr.mock_calls == [call.open(), call.run(), call.close()]
def test_succeeding_start(my_tr): my_tr.start() my_tr.stop() assert my_tr.mock_calls == [call.open(), call.run(), call.close()]
def test_report_download_finished(self, _error, _info, _confirm, tqdm, _position_after_bars): items = [NonCallableMagicMock(), NonCallableMagicMock()] tqdm.side_effect = items with thespiae.cli.CLI('thespiae') as ui: ui.feedback.confirm_operations([DownloadSpec(name='test'), DownloadSpec(name='test2')], [], []) ui.feedback.report_entry_download_initiated(DownloadSpec(name='test')) ui.feedback.report_entry_download_initiated(DownloadSpec(name='test2')) ui.feedback.report_entry_download_started(DownloadSpec(name='test'), 5) ui.feedback.report_entry_download_started(DownloadSpec(name='test2'), 10) ui.feedback.report_entry_download_progress(DownloadSpec(name='test'), 5) ui.feedback.report_entry_download_progress(DownloadSpec(name='test2'), 10) ui.feedback.report_download_finished() _info.assert_called() _error.assert_not_called() _confirm.assert_called() self.assertEqual(tqdm.call_count, 2) _position_after_bars.assert_called_once_with(2) self.assertSequenceEqual(items[0].method_calls, [call.refresh(), call.update(5), call.refresh(), call.close()]) self.assertSequenceEqual(items[1].method_calls, [call.refresh(), call.update(10), call.refresh(), call.close()])
def test_with(sock, brick): with brick: pass assert sock.mock_calls == [call.close()]
def test_close(sock, brick): brick.close() assert sock.mock_calls == [call.close()]