def test_on_preview_port_added(self): """Create a Controller object, call add a source method and check that the callback fires """ serv = Server(path=PATH, video_port=3000) try: serv.run() controller = Controller() controller.establish_connection() test_cb = Mock(side_effect=lambda mode, serve, type: self.quit_mainloop_after(2)) controller.on_preview_port_added(test_cb) sources = TestSources(video_port=3000) sources.new_test_video() sources.new_test_video() GLib.timeout_add_seconds(5, self.quit_mainloop) self.run_mainloop() print(test_cb.call_args_list) test_cb.assert_any_call(3003, 1, 7) test_cb.assert_any_call(3004, 1, 8) assert test_cb.call_count == 2 serv.terminate(1) finally: serv.terminate_and_output_status(cov=True)
def test_mock_asserts(self): """The mock object has four useful helpers (assert_called_with, assert_called_once_with, assert_any_call, assert_has_calls) that you can use to assert various things about what the mock has been called with since instantiation""" m = Mock() m(1) m.assert_called_with(1) self.assertRaises(AssertionError, m.assert_called_with, 2) # assert_called_with asserts what the Mock's most recent call was, not that a call occurred, ever. # calling m.assert_called_with(1) now will raise error m(2) m.assert_called_with(2) self.assertRaises(AssertionError, m.assert_called_with, 1) # assert_called_once_with is the stronger assertion that the mock has been called exactly once in its history, with the # specified argument. (this mock has already been called twice, so both of these fail) self.assertRaises(AssertionError, m.assert_called_once_with, 1) self.assertRaises(AssertionError, m.assert_called_once_with, 2) # assert_any_call means it was called with the given args at any point in history m.assert_any_call(1) m.assert_any_call(2) self.assertRaises(AssertionError, m.assert_called_with, 3) # use assert_has_calls to assert the whole call history. it takes a set of mock.call objects m.assert_has_calls([mock.call(1), mock.call(2)]) # this fails because order of calls was m(1) then m(2) and by default any_order=False self.assertRaises(AssertionError, m.assert_has_calls, [mock.call(2), mock.call(1)]) # this works because any_order=true m.assert_has_calls([mock.call(2), mock.call(1)], any_order=True)
def test__init(self): mock_load_data = Mock() probes = self.get_obj(load_data=mock_load_data) mock_load_data.assert_any_call() self.assertEqual(probes.probedata, ClientProbeDataSet()) self.assertEqual(probes.cgroups, dict())
def test_manager_should_call_all(self): em = ExtensionManager.make_test_instance([test_extension2, test_extension]) func = Mock() em.map(func) func.assert_any_call(test_extension2) func.assert_any_call(test_extension)
def test_simple_handler(self): from slamon.agent.executor import Executor from slamon.agent.handlers import TaskHandler from mock import Mock mock_handler = Mock() mock_callback = Mock() @TaskHandler("test-task", 1) def test_handler(input_data): mock_handler() return input_data data = {"data": 1337} with Executor() as executor: executor.submit_task( { "task_id": "123e4567-e89b-12d3-a456-426655440000", "task_type": "test-task", "task_version": 1, "task_data": data, }, mock_callback, ) mock_handler.assert_any_call() mock_callback.assert_called_once_with("123e4567-e89b-12d3-a456-426655440000", task_data=data)
def test_rmtree_success(self): dir1_list = ["dir2", "file"] empty_list = [] mock_listdir = Mock() mock_listdir.side_effect = [dir1_list, empty_list] mock_isdir = Mock() mock_isdir.side_effect = [True, False] mock_unlink = Mock() mock_unlink.return_value = 0 mock_rmdir = Mock() mock_rmdir.return_value = 0 mock_islink = Mock() mock_islink.return_value = False with nested( patch("glusterfs.gfapi.Volume.listdir", mock_listdir), patch("glusterfs.gfapi.Volume.isdir", mock_isdir), patch("glusterfs.gfapi.Volume.islink", mock_islink), patch("glusterfs.gfapi.Volume.unlink", mock_unlink), patch("glusterfs.gfapi.Volume.rmdir", mock_rmdir), ): self.vol.rmtree("dir1") mock_rmdir.assert_any_call("dir1/dir2") mock_unlink.assert_called_once_with("dir1/file") mock_rmdir.assert_called_with("dir1")
def test_rmtree_ignore_unlink_rmdir_exception(self): dir1_list = ["dir2", "file"] empty_list = [] mock_listdir = Mock() mock_listdir.side_effect = [dir1_list, empty_list] mock_isdir = Mock() mock_isdir.side_effect = [True, False] mock_unlink = Mock() mock_unlink.side_effect = [OSError] mock_rmdir = Mock() mock_rmdir.side_effect = [0, OSError] mock_islink = Mock() mock_islink.return_value = False with nested(patch("gluster.gfapi.Volume.listdir", mock_listdir), patch("gluster.gfapi.Volume.isdir", mock_isdir), patch("gluster.gfapi.Volume.islink", mock_islink), patch("gluster.gfapi.Volume.unlink", mock_unlink), patch("gluster.gfapi.Volume.rmdir", mock_rmdir)): self.vol.rmtree("dir1", True) mock_rmdir.assert_any_call("dir1/dir2") mock_unlink.assert_called_once_with("dir1/file") mock_rmdir.assert_called_with("dir1")
class TestBuilder(object): """ """ def setup_method(self, method): self.injector = Injector([SandboxModuleTest()]) self.dispatcher = self.injector.get(Dispatcher) self.builder = self.injector.get(Builder) self._composer = self.injector.get(Composer) self._build = Mock() self.builder.build = self._build self.builder._composer = self._composer def test_build_not_sandbox_image(self): images = ['external1', 'sandbox/internal1'] calls = ['internal1:master'] options = { '<flavour>': 'with_external_component', '--force': True } self.dispatcher.build_all(options) for call in calls: self._build.assert_any_call(call) assert mock.call('external1') not in self._build.mock_calls
def test_raising_handler(self): from slamon.agent.executor import Executor from slamon.agent.handlers import TaskHandler from mock import Mock, ANY mock_handler = Mock(side_effect=Exception) mock_callback = Mock() @TaskHandler("raising-task", 1) def raising_handler(input_data): mock_handler() with Executor() as executor: executor.submit_task( { "task_id": "123e4567-e89b-12d3-a456-426655440000", "task_type": "raising-task", "task_version": 1, "task_data": {}, }, mock_callback, ) mock_handler.assert_any_call() mock_callback.assert_called_once_with("123e4567-e89b-12d3-a456-426655440000", task_error=ANY)
def test_basestring_hook_called(self): basestring_hook = Mock() with patch.object(themyutils.json.JSONDecoder, "basestring_hook", basestring_hook): themyutils.json.loads('{"data": {"datetime": "2014-02-02T17:32:01", "datetimes": [{"asdict": '+\ '"2014-02-02T17:32:02"}, "2014-02-02T17:32:03"]}}') basestring_hook.assert_any_call("2014-02-02T17:32:01") basestring_hook.assert_any_call("2014-02-02T17:32:02") basestring_hook.assert_any_call("2014-02-02T17:32:03")
def test_can_set_list(self): config = self.make_section_config({}) save_mock = Mock() section = SectionConfig("Name", config, {}, save_mock) section.set("list", [1, True, "Hello"]) self.assertEqual("1,True,Hello", config["list"]) # Automatically saved value save_mock.assert_any_call()
def test_can_set_value(self): config = self.make_section_config({}) save_mock = Mock() section = SectionConfig("Name", config, {}, save_mock) section.set("option", 42) self.assertEqual("42", config["option"]) # Automatically saved value save_mock.assert_any_call()
def test_can_set_tuple(self): config = self.make_section_config({}) save_mock = Mock() section = SectionConfig("Name", config, {}, save_mock) section.set("list", (1, 2)) self.assertEqual("1,2", config["list"]) # Automatically saved value save_mock.assert_any_call()
def test_dispatch_map_should_invoke_filter_for_extensions(self): em = DispatchExtensionManager.make_test_instance([test_extension, test_extension2]) filter_func = Mock(return_value=False) args = ('A',) kw = {'big': 'Cheese'} em.map(filter_func, None, *args, **kw) filter_func.assert_any_call(test_extension, *args, **kw) filter_func.assert_any_call(test_extension2, *args, **kw)
def test_find_books(self): """i hate assembler""" with patch('model.DB.find_author') as perm_mock: perm_mock = Mock(return_value=None) perm_mock('firstBook') perm_mock('secondBook') perm_mock('thirdBook') perm_mock.assert_any_call('thirdBook')
def test_find_author(self): """why do we need so many functions..?""" with patch('model.DB.find_author') as perm_mock: perm_mock = Mock(return_value=None) perm_mock('firstAuthor') perm_mock('secondAuthor') perm_mock('thirdAuthor') perm_mock.assert_any_call('secondAuthor')
def test_delete_book(self): """YYUUPA! the last one!""" with patch('model.DB.find_author') as perm_mock: perm_mock = Mock(return_value=None) perm_mock('firstBook') perm_mock('secondBook') perm_mock('thirdBook') perm_mock.assert_any_call('secondBook')
def test_regularize_layer_params_single_layer(self, layers): from lasagne.regularization import regularize_layer_params l_1, l_2, l_3 = layers penalty = Mock(return_value=0) loss = regularize_layer_params(l_2, penalty) assert penalty.call_count == 1 penalty.assert_any_call(l_2.W)
def testCheckSupervisordState(self, supervisorClientMock): runningState = {"statename": "RUNNING"} getStateMock = Mock(return_value=runningState) supervisorClientMock.return_value = Mock(supervisor=Mock(getState=getStateMock)) SupervisorChecker().checkSupervisordState() getStateMock.assert_any_call()
def testCheckSupervisorProcesses(self, supervisorClientMock): runningState = {"statename": "RUNNING"} getAllProcessInfoMock = Mock(return_value=[runningState]) supervisorClientMock.return_value = Mock(supervisor=Mock(getAllProcessInfo=getAllProcessInfoMock)) SupervisorChecker().checkSupervisorProcesses() getAllProcessInfoMock.assert_any_call()
def test__init(self): mock_load_data = Mock() probes = self.get_probes_object(load_data=mock_load_data) probes.core.fam.AddMonitor.assert_called_with(os.path.join(datastore, probes.name), probes.probes) mock_load_data.assert_any_call() self.assertEqual(probes.probedata, ClientProbeDataSet()) self.assertEqual(probes.cgroups, dict())
def test_given_extra_validators_when_validated_then_calls_extra_validators_for_each_element(self): validator1, validator2 = Mock(), Mock() element1, element2 = Mock(), Mock() field_type = types.Array(Mock(), validator1, validator2) field_type.validate([element1, element2]) validator1.assert_any_call(element1) validator2.assert_any_call(element2)
class TestClient(TestCase): def setUp(self): self.client = MockClient.with_basic_setup() self.callback_mock = Mock(wraps=self.client.io_loop.add_callback) self.client.io_loop.add_callback = self.callback_mock self.test_schema = { 'type': 'record', 'name': 'test_driver', 'fields': [ {'name': 'val', 'type': 'int'} ] } self.test_value = {'val': 1} def tearDown(self): if not self.client.in_shutdown: self.client.shutdown(block=False) def test_initial_produce(self): self.client.produce('test_driver', self.test_value, self.test_schema) expected_message = Message('test_driver', self.test_value, None, None, 0, 1) self.assertEqual(self.client.schema_cache['test_driver']['value'], self.test_schema) self.assertEqual(None, self.client.schema_cache['test_driver'].get('key')) self.assertEqual(1, self.client.message_queues['test_driver'].qsize()) self.client.mock_for('produce').assert_called_once_with(expected_message) self.callback_mock.assert_called_once_with(self.client.producer.evaluate_queue, 'test_driver', self.client.message_queues['test_driver']) def test_produce_raises_in_shutdown(self): self.client.shutdown(block=True) self.assertRaises(KafkaRESTShutdownException, self.client.produce, 'test_driver', self.test_value, self.test_schema) def test_produce_with_full_queue(self): self.client.message_queues['test_driver'] = Queue(maxsize=1) self.client.message_queues['test_driver'].put('whatever') self.client.produce('test_driver', self.test_value, self.test_schema) expected_message = Message('test_driver', self.test_value, None, None, 0, 1) self.assertEqual(1, self.client.message_queues['test_driver'].qsize()) self.assertTrue(self.client.mock_for('drop_message').called_with('test_driver', expected_message, 'primary_queue_full')) def test_shutdown(self): self.client.shutdown() self.callback_mock.assert_any_call(self.client.producer.start_shutdown) def test_shutdown_blocking(self): self.client.shutdown(block=True) self.callback_mock.assert_any_call(self.client.producer.start_shutdown) self.assertFalse(self.client.producer_thread.is_alive())
def test_by_role_worker(self): env.roledefs = self.TEST_ROLEDEFS callback = Mock() fabricapi.by_role_worker('coordinator', callback) self.assertFalse(callback.called, 'worker callback called for ' + 'coordinator') fabricapi.by_role_worker('worker0', callback) callback.assert_any_call()
def testCheckSupervisordRaisesExceptionOnSupervisorNotInRunningState(self, supervisorClientMock): getStateMock = Mock(return_value={"statename": "FATAL"}) supervisorClientMock.return_value = Mock(supervisor=Mock(getState=getStateMock)) with self.assertRaises(SupervisorNotRunning): SupervisorChecker().checkSupervisordState() getStateMock.assert_any_call()
def testCheckSupervisorProcessesRaisesExceptionOnSupervisorClientFailure(self, supervisorClientMock): noneState = None getAllProcessInfoMock = Mock(return_value=noneState) supervisorClientMock.return_value = Mock(supervisor=Mock(getAllProcessInfo=getAllProcessInfoMock)) with self.assertRaises(SupervisorMonitorError): SupervisorChecker().checkSupervisorProcesses() getAllProcessInfoMock.assert_any_call()
def test_no_entries(self): mock_get = Mock(return_value=[]) self.trakt.get = mock_get self.trakt.update_user("adam") mock_get.assert_any_call(API_ACTIVITY.format("adam", "episodes")) mock_get.assert_any_call(API_ACTIVITY.format("adam", "movies")) self.failIf("last_sync_episodes" in self.trakt.users["adam"]) self.failIf("last_sync_movies" in self.trakt.users["adam"])
def test_print_report_header(self): process_stack_util = Mock() process_filter = Mock() printer = Mock() process_filter.filter_processes = Mock(return_value=self.processes) reporter = CpuProcessStackUtilReporter(process_stack_util, process_filter, printer, self.options) reporter.print_report(123, " ", " ") printer.assert_any_call("Timestamp UID\tPID\tStkSize\tCommand")
def test_print_report_header_without_process_user(self): cpu_usage = Mock() process_filter = Mock() printer = Mock() process_filter.filter_processes = Mock(return_value=self.processes) reporter = CpuUsageReporter(cpu_usage, process_filter, 1, printer, self.options) reporter.print_report(123, 4, " ", " ") printer.assert_any_call("Timestamp UID\tPID\tusr\tsystem\tguest\t%CPU\tCPU\tCommand")
def test_print_report_header(self): process_memory_util = Mock() process_filter = Mock() printer = Mock() process_filter.filter_processes = Mock(return_value=self.processes) reporter = CpuProcessMemoryUtilReporter(process_memory_util, process_filter, 1, printer, self.options) reporter.print_report(123, " ", " ") printer.assert_any_call("Timestamp UID\tPID\tMinFlt/s\tMajFlt/s\tVSize\tRSS\t%Mem\tCommand")
def test_emit_payload(self): """ Submit each payload to its specific endpoint. """ agent_payload = AgentPayload() fake_emitter = Mock() fake_emitter.__name__ = None # Different payloads, different endpoints agent_payload.emit(None, None, [fake_emitter], True, merge_payloads=False) fake_emitter.assert_any_call(agent_payload.data_payload, None, None, "metrics") fake_emitter.assert_any_call(agent_payload.meta_payload, None, None, "metadata") # One payload, one endpoint agent_payload.emit(None, None, [fake_emitter], True) fake_emitter.assert_any_call(agent_payload.payload, None, None, "")
def test_assert_any_call(self): mock = Mock(return_value=None) mock(1, 2, arg='thing') mock('some', 'thing', 'else') mock.assert_any_call(1, 2, arg='thing')
def test_rebase_with_assembly(self, mocked_cmd_assert_async: mock.Mock, mocked_open: mock.Mock, mocked_os_remove: mock.Mock, mocked_copy: mock.Mock, mocked_mkdir: mock.Mock): source_sha = "3f17b42b8aa7d294c0d2b6f946af5fe488f3a722" distgit_sha = "4cd7f576ad005aadd3c25ea56c7986bc6a7e7340" runtime = self._make_runtime(assembly='tester') rpm = self._make_rpm_meta(runtime, source_sha, distgit_sha) dg = rpm.distgit_repo() mocked_cmd_assert_async.side_effect = \ lambda cmd, **kwargs: {"spectool": ("Source0: 1.tar.gz\nSource1: a.diff\nPatch0: b/c.diff\n", "")} \ .get(cmd[0], ("fake_stdout", "fake_stderr")) builder = RPMBuilder(runtime, scratch=False, dry_run=False) builder._populate_specfile_async = mock.AsyncMock( return_value=["fake spec content"]) actual = asyncio.get_event_loop().run_until_complete( builder.rebase(rpm, "1.2.3", "202104070000.test.p?")) self.assertEqual(actual, distgit_sha) self.assertEqual( rpm.release, "202104070000.test.p0.g" + source_sha[:7] + '.assembly.tester') mocked_open.assert_called_once_with(dg.dg_path / "foo.spec", "w") mocked_open.return_value.__aenter__.return_value.writelines.assert_called_once_with( ["fake spec content"]) mocked_cmd_assert_async.assert_any_call([ "tar", "-czf", dg.dg_path / f"{rpm.config.name}-{rpm.version}-{rpm.release}.tar.gz", "--exclude=.git", fr"--transform=s,^\./,{rpm.config.name}-{rpm.version}/,", "." ], cwd=rpm.source_path) mocked_cmd_assert_async.assert_any_call([ "rhpkg", "new-sources", f"{rpm.config.name}-{rpm.version}-{rpm.release}.tar.gz" ], cwd=dg.dg_path, retries=3) mocked_cmd_assert_async.assert_called_with( ["spectool", "--", dg.dg_path / "foo.spec"], cwd=dg.dg_path) mocked_copy.assert_any_call(Path(rpm.source_path) / "a.diff", dg.dg_path / "a.diff", follow_symlinks=False) mocked_copy.assert_any_call(Path(rpm.source_path) / "b/c.diff", dg.dg_path / "b/c.diff", follow_symlinks=False) rpm._run_modifications.assert_called_once_with(dg.dg_path / "foo.spec", dg.dg_path) dg.commit.assert_called_once_with( f"Automatic commit of package [{rpm.config.name}] release [{rpm.version}-{rpm.release}].", commit_attributes={ 'version': '1.2.3', 'release': '202104070000.test.p0.g3f17b42.assembly.tester', 'io.openshift.build.commit.id': '3f17b42b8aa7d294c0d2b6f946af5fe488f3a722', 'io.openshift.build.source-location': None }) dg.push_async.assert_called_once()
class LogConfigurationTests(TestCase): def setUp(self): self.configuration_property = ConfigurationProperty(key='property', default='default') self.mock_log = Mock() def test_should_log_given_path(self): log_configuration(self.mock_log, {}, 'configuration_file.yaml') self.mock_log.assert_any_call('Loaded configuration file "%s"', 'configuration_file.yaml') def test_should_log_when_configuration_file_was_empty(self): log_configuration(self.mock_log, {}, 'configuration_file.yaml') self.mock_log.assert_any_call('Configuration file was empty!') def test_should_log_given_string_configuration_property(self): log_configuration(self.mock_log, {self.configuration_property: '123'}, 'configuration_file.yaml') self.mock_log.assert_any_call('Configuration property %s = "%s" (%s)', '"property"', '123', 'str') def test_should_log_given_boolean_configuration_property(self): log_configuration(self.mock_log, {self.configuration_property: True}, 'configuration_file.yaml') self.mock_log.assert_any_call('Configuration property %s = "%s" (%s)', '"property"', True, 'bool') def test_should_log_given_integer_configuration_property(self): log_configuration(self.mock_log, {self.configuration_property: 123}, 'configuration_file.yaml') self.mock_log.assert_any_call('Configuration property %s = "%s" (%s)', '"property"', 123, 'int') def test_should_log_given_configuration_properties_in_alphabetical_order( self): property_a = ConfigurationProperty(key='a_property', default=123) property_b = ConfigurationProperty(key='b_property', default=123) property_c = ConfigurationProperty(key='c_property', default=123) configuration = { property_a: 123, property_b: False, property_c: 'hello world' } log_configuration(self.mock_log, configuration, 'configuration_file.yaml') self.mock_log.assert_any_call('Loaded configuration file "%s"', 'configuration_file.yaml') self.mock_log.assert_any_call('Configuration property %s = "%s" (%s)', '"a_property"', 123, 'int') self.mock_log.assert_any_call('Configuration property %s = "%s" (%s)', '"b_property"', False, 'bool') self.mock_log.assert_any_call('Configuration property %s = "%s" (%s)', '"c_property"', 'hello world', 'str')
def test_retrieve_files(self): """ Test run command map retrieve_files """ # retrieve_files tests with patch("dsi.common.remote_host.RemoteHost") as mongod: mock_retrieve_file = Mock() mongod.retrieve_path = mock_retrieve_file command = { "retrieve_files": [{ "source": "remote_path", "target": "mongos.log" }] } mongod.alias = "host" command_runner._run_host_command_map(mongod, command, "test_id") mock_retrieve_file.assert_any_call( "remote_path", "reports/test_id/host/mongos.log") # retrieve_files tests with patch("dsi.common.remote_host.RemoteHost") as mongod: mock_retrieve_file = Mock() mongod.retrieve_path = mock_retrieve_file command = { "retrieve_files": [{ "source": "remote_path", "target": "mongos.log" }] } mongod.alias = "host" command_runner._run_host_command_map(mongod, command, "test_id") mock_retrieve_file.assert_any_call( "remote_path", "reports/test_id/host/mongos.log") with patch("dsi.common.remote_host.RemoteHost") as mongod: mock_retrieve_file = Mock() mongod.retrieve_path = mock_retrieve_file command = { "retrieve_files": [{ "source": "remote_path", "target": "local_path" }] } mongod.alias = "host" command_runner._run_host_command_map(mongod, command, "test_id") mock_retrieve_file.assert_any_call( "remote_path", "reports/test_id/host/local_path") with patch("dsi.common.remote_host.RemoteHost") as mongod: mock_retrieve_file = Mock() mongod.retrieve_path = mock_retrieve_file mongod.alias = "mongod.0" command_runner._run_host_command_map(mongod, command, "test_id") mock_retrieve_file.assert_any_call( "remote_path", "reports/test_id/mongod.0/local_path") with patch("dsi.common.remote_host.RemoteHost") as mongod: mock_retrieve_file = Mock() mongod.retrieve_path = mock_retrieve_file command = { "retrieve_files": [{ "source": "remote_path", "target": "./local_path" }] } mongod.alias = "mongos.0" command_runner._run_host_command_map(mongod, command, "test_id") mock_retrieve_file.assert_any_call( "remote_path", "reports/test_id/mongos.0/local_path")
def test__init(self): mock_load_data = Mock() probes = self.get_probes_object(load_data=mock_load_data) mock_load_data.assert_any_call() self.assertEqual(probes.probedata, ClientProbeDataSet()) self.assertEqual(probes.cgroups, dict())
class TestAnsibleCommandExecutor(TestCase): def setUp(self): self.process_mock = Mock() self.stdout_mock = mock_enter_exit_self() self.stderr_mock = mock_enter_exit_self() self.convert_mock = Mock() self.sleep_mock = Mock() self.output_writer_mock = Mock() self.popen_patcher = patch( 'cloudshell.cm.ansible.domain.ansible_command_executor.Popen') self.stdout_patcher = patch( 'cloudshell.cm.ansible.domain.ansible_command_executor.StdoutAccumulator' ) self.stderr_patcher = patch( 'cloudshell.cm.ansible.domain.ansible_command_executor.StderrAccumulator' ) self.convert_patcher = patch( 'cloudshell.cm.ansible.domain.ansible_command_executor.UnixToHtmlColorConverter.convert' ) self.sleep_patcher = patch( 'cloudshell.cm.ansible.domain.ansible_command_executor.time.sleep') self.popen_patcher.start().return_value = self.process_mock self.stdout_patcher.start().return_value = self.stdout_mock self.stderr_patcher.start().return_value = self.stderr_mock self.convert_mock = self.convert_patcher.start() self.sleep_mock = self.sleep_patcher.start() self.convert_mock.side_effect = (lambda x: x) self.sleep_mock.side_effect = (lambda x: 0) self.executor = AnsibleCommandExecutor() def tearDown(self): self.popen_patcher.stop() self.stdout_patcher.stop() self.stderr_patcher.stop() self.convert_patcher.stop() self.sleep_patcher.stop() def test_run_prcess_with_corrent_command_line(self): with patch( 'cloudshell.cm.ansible.domain.ansible_command_executor.Popen' ) as popen: self.executor.execute_playbook('playbook1', 'inventory1', '-arg1 -args2', Mock(), Mock(), Mock()) popen.assert_called_once_with( 'ansible-playbook playbook1 -i inventory1 -arg1 -args2', shell=True, stdout=PIPE, stderr=PIPE) def test_sample_in_interval_of_2_seconds(self): self.stdout_mock.read_all_txt.side_effect = ['1', '2'] self.stderr_mock.read_all_txt.return_value = '' self.process_mock.poll = MagicMock(side_effect=[None, '0']) self.executor.execute_playbook('p', 'i', '', self.output_writer_mock, Mock(), Mock()) self.sleep_mock.assert_any_call(2) def test_result_contains_output_and_error_texts(self): self.stdout_mock.read_all_txt.side_effect = ['1', '2'] self.stderr_mock.read_all_txt.side_effect = ['3', '4'] self.process_mock.poll = MagicMock(side_effect=[None, '0']) output, error = self.executor.execute_playbook('p', 'i', '', self.output_writer_mock, Mock(), Mock()) self.assertEqual('12', output) self.assertEqual('34', error) def test_every_output_bulk_is_written_to_outputwriter(self): self.stdout_mock.read_all_txt.side_effect = ['123', '456', '789'] self.stderr_mock.read_all_txt.side_effect = ['a', 'b', ''] self.stderr_mock.read_all_txt.return_value = '' self.process_mock.poll = MagicMock(side_effect=[None, None, '0']) self.executor.execute_playbook('p', 'i', '', self.output_writer_mock, Mock(), Mock()) self.output_writer_mock.write.assert_any_call('a' + os.linesep + '123' + os.linesep + 'b' + os.linesep + '456' + os.linesep + '789')
def test_portage_detect(): if not is_gentoo(): print("Skipping not Gentoo") return from rosdep2.platforms.gentoo import portage_detect m = Mock() m.return_value = [] val = portage_detect([], exec_fn=m) assert val == [], val # Test checking for a package that we do not have installed m = Mock(return_value=[]) val = portage_detect(['tinyxml[stl]'], exec_fn=m) assert val == [], "Result was actually: %s" % val m.assert_called_with(['portageq', 'match', '/', 'tinyxml[stl]']) # Test checking for a package that we do have installed m = Mock(return_value=['dev-libs/tinyxml-2.6.2-r1']) val = portage_detect(['tinyxml[stl]'], exec_fn=m) assert val == ['tinyxml[stl]'], "Result was actually: %s" % val m.assert_called_with(['portageq', 'match', '/', 'tinyxml[stl]']) # Test checking for two packages that we have installed m = Mock(side_effect=[['sys-devel/gcc-4.5.3-r2'], ['dev-libs/tinyxml-2.6.2-r1']]) val = portage_detect(['tinyxml[stl]', 'gcc'], exec_fn=m) assert val == ['gcc', 'tinyxml[stl]'], "Result was actually: %s" % val m.assert_any_call(['portageq', 'match', '/', 'tinyxml[stl]']) m.assert_any_call(['portageq', 'match', '/', 'gcc']) # Test checking for two missing packages m = Mock(side_effect=[[], []]) val = portage_detect(['tinyxml[stl]', 'gcc'], exec_fn=m) assert val == [], "Result was actually: %s" % val m.assert_any_call(['portageq', 'match', '/', 'tinyxml[stl]']) m.assert_any_call(['portageq', 'match', '/', 'gcc']) # Test checking for one missing, one installed package m = Mock(side_effect=[['sys-devel/gcc-4.5.3-r2'], []]) val = portage_detect(['tinyxml[stl]', 'gcc'], exec_fn=m) assert val == ['gcc'], "Result was actually: %s" % val m.assert_any_call(['portageq', 'match', '/', 'tinyxml[stl]']) m.assert_any_call(['portageq', 'match', '/', 'gcc']) # Test checking for one installed, one missing package (reverse order) m = Mock(side_effect=[[], ['dev-libs/tinyxml-2.6.2-r1']]) val = portage_detect(['tinyxml[stl]', 'gcc'], exec_fn=m) assert val == ['tinyxml[stl]'], "Result was actually: %s" % val m.assert_any_call(['portageq', 'match', '/', 'tinyxml[stl]']) m.assert_any_call(['portageq', 'match', '/', 'gcc']) # Test duplicates (requesting the same package twice) #TODO what's the desired behavior here m = Mock(side_effect=[['dev-libs/tinyxml-2.6.2-r1'], ['dev-libs/tinyxml-2.6.2-r1']]) val = portage_detect(['tinyxml[stl]', 'tinyxml[stl]'], exec_fn=m) assert val == ['tinyxml[stl]', 'tinyxml[stl]'], "Result was actually: %s" % val m.assert_any_call(['portageq', 'match', '/', 'tinyxml[stl]']) # and a second of the same, but any_call won't show that. # Test packages with multiple slot m = Mock( side_effect=[['dev-lang/python-2.7.2-r3', 'dev-lang/python-3.2.2']]) val = portage_detect(['python'], exec_fn=m) assert val == ['python'], "Result was actually: %s" % val m.assert_any_call(['portageq', 'match', '/', 'python'])
def test_report_dict_should_update_indicators_and_categories(self): mock_update_indicator = Mock() mock_update_category = Mock() with patch('genweb.core.indicators.client.Client.update_indicator', side_effect=mock_update_indicator): with patch('genweb.core.indicators.client.Client.update_category', side_effect=mock_update_category): self.reporter.report(self.registry['service-2']) self.assertEqual(2, mock_update_indicator.call_count) mock_update_indicator.assert_any_call('service-2', 'indicator-1', 'Indicator 1') mock_update_indicator.assert_any_call('service-2', 'indicator-2', 'Indicator 2') self.assertEqual(4, mock_update_category.call_count) mock_update_category.assert_any_call('service-2', 'indicator-1', 'category-1.1', 'Category 1.1', None, None, 211) mock_update_category.assert_any_call('service-2', 'indicator-1', 'category-1.2', 'Category 1.2', None, None, 212) mock_update_category.assert_any_call('service-2', 'indicator-2', 'category-2.1', 'Category 2.1', None, None, 221) mock_update_category.assert_any_call('service-2', 'indicator-2', 'category-2.2', 'Category 2.2', None, None, 222)
class TimezoneInterfaceTestCase(unittest.TestCase): """Test DBus interface for the timezone module.""" def setUp(self): """Set up the timezone module.""" # Set up the timezone module. self.timezone_module = TimezoneModule() self.timezone_interface = TimezoneInterface(self.timezone_module) # Connect to the properties changed signal. self.callback = Mock() self.timezone_interface.PropertiesChanged.connect(self.callback) def kickstart_properties_test(self): """Test kickstart properties.""" self.assertEqual(self.timezone_interface.KickstartCommands, ["timezone"]) self.assertEqual(self.timezone_interface.KickstartSections, []) self.assertEqual(self.timezone_interface.KickstartAddons, []) self.callback.assert_not_called() def timezone_property_test(self): """Test the Timezone property.""" self.timezone_interface.SetTimezone("Europe/Prague") self.assertEqual(self.timezone_interface.Timezone, "Europe/Prague") self.callback.assert_called_once_with(MODULE_TIMEZONE_NAME, {'Timezone': 'Europe/Prague'}, []) def utc_property_test(self): """Test the IsUtc property.""" self.timezone_interface.SetIsUTC(True) self.assertEqual(self.timezone_interface.IsUTC, True) self.callback.assert_called_once_with(MODULE_TIMEZONE_NAME, {'IsUTC': True}, []) def ntp_property_test(self): """Test the NTPEnabled property.""" self.timezone_interface.SetNTPEnabled(False) self.assertEqual(self.timezone_interface.NTPEnabled, False) self.callback.assert_called_once_with(MODULE_TIMEZONE_NAME, {'NTPEnabled': False}, []) def ntp_servers_property_test(self): """Test the NTPServers property.""" self.timezone_interface.SetNTPServers(["ntp.cesnet.cz"]) self.assertEqual(self.timezone_interface.NTPServers, ["ntp.cesnet.cz"]) self.callback.assert_called_once_with( MODULE_TIMEZONE_NAME, {'NTPServers': ["ntp.cesnet.cz"]}, []) def _test_kickstart(self, ks_in, ks_out): """Test the kickstart string.""" # Remove extra spaces from the expected output. ks_output = "\n".join("".join(line.strip()) for line in ks_out.strip("\n").splitlines()) # Read a kickstart, result = self.timezone_interface.ReadKickstart(ks_in) self.assertEqual({k: v.unpack() for k, v in result.items()}, {"success": True}) # Generate a kickstart. self.assertEqual(ks_output, self.timezone_interface.GenerateKickstart()) # Test the properties changed callback. self.callback.assert_any_call(DBUS_MODULE_NAMESPACE, {'Kickstarted': True}, []) def kickstart_test(self): """Test the timezone command.""" ks_in = """ timezone Europe/Prague """ ks_out = """ #version=DEVEL # System timezone timezone Europe/Prague """ self._test_kickstart(ks_in, ks_out) def kickstart2_test(self): """Test the timezone command with flags.""" ks_in = """ timezone --utc --nontp Europe/Prague """ ks_out = """ #version=DEVEL # System timezone timezone Europe/Prague --isUtc --nontp """ self._test_kickstart(ks_in, ks_out) def kickstart3_test(self): """Test the timezone command with ntp servers..""" ks_in = """ timezone --ntpservers ntp.cesnet.cz Europe/Prague """ ks_out = """ #version=DEVEL # System timezone timezone Europe/Prague --ntpservers=ntp.cesnet.cz """ self._test_kickstart(ks_in, ks_out)
class DiscoveryTests(unittest.TestCase): def setUp(self): self.filesys = Mock() self.filesys.walk.return_value = [('root',[],['known','new','unknown'])] self.listener = Mock() self.filt = Mock() self.add = Mock() img = Mock() img.status = 'new' self.add.return_value = img self.dependencies = Mock() self.dependencies.getFilesystem.return_value = self.filesys self.dependencies.getListener.return_value = self.listener self.dependencies.getFileFilter.return_value = self.filt def discover(self, path): import niprov.discovery niprov.discovery.add = self.add niprov.discovery.discover(path, dependencies=self.dependencies) def test_Calls_add_on_files_encountered(self): self.setupFilter('.x') self.filesys.walk.return_value = [('root',[],['p/f1.x','p/f2.x']), ('root',[],['p/p2/f3.x'])] #(dirpath, dirnames, filenames) self.discover('root') self.filesys.walk.assert_called_with('root') self.add.assert_any_call('root/p/f1.x', transient=False, dependencies=self.dependencies) self.add.assert_any_call('root/p/f2.x', transient=False, dependencies=self.dependencies) self.add.assert_any_call('root/p/p2/f3.x', transient=False, dependencies=self.dependencies) def test_file_filters(self): self.setupFilter('valid.file') self.filesys.walk.return_value = [('root',[],['valid.file','other.file'])] self.discover('root') self.add.assert_any_call('root/valid.file', transient=False, dependencies=self.dependencies) self.assertNotCalledWith(self.add, 'root/other.file') def test_Gives_listener_summary(self): self.filesys.walk.return_value = [('root',[],['a','b','c','d','e','f','g','h'])] statuses = ['new','new','series-new-file','series-new-file', 'series-new-file','failed','new-version','new-version'] images = [] for s in statuses: img = Mock() img.status = s images.append(img) self.add.side_effect = images self.discover('root') self.listener.discoveryFinished.assert_called_with(nnew=2, nadded=3, nfailed=1, ntotal=8) def assertNotCalledWith(self, m, *args, **kwargs): c = mock.call(*args, **kwargs) assert c not in m.call_args_list, "Unexpectedly found call: "+str(c) def setupFilter(self, valid): def filter_side_effect(*args): if valid in args[0]: return True return False self.filt.include = Mock(side_effect=filter_side_effect)
class TestClient(TestCase): def setUp(self): self.client = MockClient.with_basic_setup() self.callback_mock = Mock(wraps=self.client.io_loop.add_callback) self.client.io_loop.add_callback = self.callback_mock self.test_schema = { 'type': 'record', 'name': 'test_driver', 'fields': [{ 'name': 'val', 'type': 'int' }] } self.test_value = {'val': 1} def tearDown(self): if not self.client.in_shutdown: self.client.shutdown(block=False) def test_initial_produce(self): self.client.produce('test_driver', self.test_value, self.test_schema) expected_message = Message('test_driver', self.test_value, None, None, 0, 1) self.assertEqual(self.client.schema_cache['test_driver']['value'], self.test_schema) self.assertEqual(None, self.client.schema_cache['test_driver'].get('key')) self.assertEqual(1, self.client.message_queues['test_driver'].qsize()) self.client.mock_for('produce').assert_called_once_with( expected_message) self.callback_mock.assert_called_once_with( self.client.producer.evaluate_queue, 'test_driver', self.client.message_queues['test_driver']) def test_produce_raises_in_shutdown(self): self.client.shutdown(block=True) self.assertRaises(KafkaRESTShutdownException, self.client.produce, 'test_driver', self.test_value, self.test_schema) def test_produce_with_full_queue(self): self.client.message_queues['test_driver'] = Queue(maxsize=1) self.client.message_queues['test_driver'].put('whatever') self.client.produce('test_driver', self.test_value, self.test_schema) expected_message = Message('test_driver', self.test_value, None, None, 0, 1) self.assertEqual(1, self.client.message_queues['test_driver'].qsize()) self.assertTrue( self.client.mock_for('drop_message').called_with( 'test_driver', expected_message, 'primary_queue_full')) def test_shutdown(self): self.client.shutdown() self.callback_mock.assert_any_call(self.client.producer.start_shutdown) def test_shutdown_blocking(self): self.client.shutdown(block=True) self.callback_mock.assert_any_call(self.client.producer.start_shutdown) self.assertFalse(self.client.producer_thread.is_alive())