def test_encoding_delegation(self, delegatee): p = PropertyMock(return_value='ascii') type(delegatee).encoding = p dd = DelegatingDataset(delegatee) e = dd.encoding p.assert_called_once_with() assert e == 'ascii'
def test_extended_textual_header_delegation(self, delegatee): p = PropertyMock(return_value=['Hello', 'World!']) type(delegatee).extended_textual_header = p dd = DelegatingDataset(delegatee) eth = dd.extended_textual_header p.assert_called_once_with() assert eth == ['Hello', 'World!']
def test_dimensionality_header_delegation(self, delegatee): p = PropertyMock(return_value=3) type(delegatee).dimensionality = p dd = DelegatingDataset(delegatee) d = dd.dimensionality p.assert_called_once_with() assert d == 3
def test_binary_reel_header_delegation(self, delegatee): p = PropertyMock(return_value=BinaryReelHeader()) type(delegatee).binary_reel_header = p dd = DelegatingDataset(delegatee) brh = dd.binary_reel_header p.assert_called_once_with() assert are_equal(brh, BinaryReelHeader())
def test_endian_delegation(self, delegatee): p = PropertyMock(return_value='<') type(delegatee).endian = p dd = DelegatingDataset(delegatee) e = dd.endian p.assert_called_once_with() assert e == '<'
def test_extended_textual_header_delegation(self, delegatee): p = PropertyMock(return_value=['Hello', 'World!']) type(delegatee).extended_textual_header = p dd = DelegatingDataset(delegatee) eth = dd.extended_textual_header p.assert_called_once_with() assert eth == ['Hello', 'World!']
def test_same_speed_one_call(self, gpio, dac, swim_pump_device): normalized_value = PropertyMock() type(dac).normalized_value = normalized_value for _ in range(10): swim_pump_device.speed(50) gpio.output.assert_has_calls([call(PIN, True), call(PIN, False)]) normalized_value.assert_called_once_with(0.5)
def test_binary_reel_header_delegation(self, delegatee): p = PropertyMock(return_value=BinaryReelHeader()) type(delegatee).binary_reel_header = p dd = DelegatingDataset(delegatee) brh = dd.binary_reel_header p.assert_called_once_with() assert are_equal(brh, BinaryReelHeader())
def test_dimensionality_header_delegation(self, delegatee): p = PropertyMock(return_value=3) type(delegatee).dimensionality = p dd = DelegatingDataset(delegatee) d = dd.dimensionality p.assert_called_once_with() assert d == 3
def test_textual_reel_header_delegation(self, delegatee): p = PropertyMock(return_value=['foo']) type(delegatee).textual_reel_header = p dd = DelegatingDataset(delegatee) trh = dd.textual_reel_header p.assert_called_once_with() assert trh == ['foo']
def test_ValidateHeaders(self, mockWorksheet): testStartRowIndex = 0 testStartColIndex = 0 testHeaders = self.validHeaders mockKeys = MagicMock() mockKeys.__iter__.return_value = testHeaders mockMembers = Mock() mockMembers.keys.return_value = mockKeys mockBase = Mock() pMockMembers = PropertyMock(return_value = mockMembers) type(mockBase).__members__ = pMockMembers mockWorksheet.cell = MagicMock(side_effect = self.getValidHeaderValue) testReader = ObservedExpectedMatricesReader(mockBase) testReader._validateHeaders(testStartRowIndex, testStartColIndex, mockWorksheet) mockKeys.__iter__.assert_called_once_with() mockMembers.keys.assert_called_once_with() pMockMembers.assert_called_once_with() mockMembers.keys.assert_called_once_with() testFullHeaders = [" "] testFullHeaders.append(self.validHeaders) for index in range(len(testFullHeaders)): mockWorksheet.cell.assert_any_call(row = testStartRowIndex + index, column = testStartColIndex) mockWorksheet.cell.assert_any_call(row = testStartRowIndex, column = testStartColIndex + index)
def test_postprocess_testjob_interactive( self, results_url_mock, get_from_artifactorial_mock, assign_test_log_mock, create_testrun_attachment_mock, ): results_url_mock.return_value = "http://foo.com" get_from_artifactorial_mock.return_value = ResultFiles() testjob_mock = MagicMock() id_mock = PropertyMock(return_value="999111") type(testjob_mock).pk = id_mock job_id_mock = PropertyMock(return_value="1234") type(testjob_mock).job_id = job_id_mock testjob_mock.backend = MagicMock() implementation_type_mock = PropertyMock(return_value="lava") type(testjob_mock.backend ).implementation_type = implementation_type_mock definition_mock = PropertyMock(return_value=JOB_DEFINITION_INTERACTIVE) type(testjob_mock).definition = definition_mock testjob_target = MagicMock() project_settings_mock = PropertyMock(return_value='{}') type(testjob_target).project_settings = project_settings_mock type(testjob_mock).target = testjob_target self.plugin.postprocess_testjob(testjob_mock) implementation_type_mock.assert_called_once_with() definition_mock.assert_called_with() results_url_mock.assert_called_with() testjob_mock.testrun.metadata.__setitem__.assert_called_with( 'tradefed_results_url_1234', 'http://foo.com') testjob_mock.testrun.save.assert_called_with() assign_test_log_mock.assert_not_called() create_testrun_attachment_mock.assert_not_called()
def test_textual_reel_header_delegation(self, delegatee): p = PropertyMock(return_value=['foo']) type(delegatee).textual_reel_header = p dd = DelegatingDataset(delegatee) trh = dd.textual_reel_header p.assert_called_once_with() assert trh == ['foo']
async def test_watchdog( hass, create_hdmi_network, mock_cec_adapter, adapter_initialized_value, watchdog_actions, ): """Test the watchdog when adapter is down/up.""" adapter_initialized = PropertyMock(return_value=adapter_initialized_value) events = async_capture_events(hass, EVENT_HDMI_CEC_UNAVAILABLE) mock_cec_adapter_instance = mock_cec_adapter.return_value type(mock_cec_adapter_instance).initialized = adapter_initialized mock_hdmi_network_instance = await create_hdmi_network() mock_hdmi_network_instance.set_initialized_callback.assert_called_once() callback = mock_hdmi_network_instance.set_initialized_callback.call_args.args[0] callback() async_fire_time_changed(hass, utcnow() + timedelta(seconds=WATCHDOG_INTERVAL)) await hass.async_block_till_done() adapter_initialized.assert_called_once_with() assert len(events) == watchdog_actions assert mock_cec_adapter_instance.init.call_count == watchdog_actions
def testRead(self, mockWorksheet, mockObservedMatrix, mockExpectedMatrix): mockBases = Mock() testTitle = "Test Title" mockWorksheetTitle = PropertyMock(return_value = testTitle) type(mockWorksheet).title = mockWorksheetTitle testResult = (mockObservedMatrix, mockExpectedMatrix) testReader = ObservedExpectedMatricesReader(mockBases) testReader._validateHeaders = MagicMock(return_value = True) testReader._readAndValidateSubstitutionValues = \ MagicMock(return_value = testResult) testReader.read(mockWorksheet) self.assertEquals(testReader.matricesDictionary[testTitle], testResult, "Matrices dictionary value must be equal to the" + "test result.") testReader._validateHeaders \ .assert_any_call(18, 1, mockWorksheet) testReader._validateHeaders \ .assert_any_call(18, 7, mockWorksheet) self.assertEquals(testReader._validateHeaders.call_count, 2, "Header validation must have been called exactly twice.") testReader._readAndValidateSubstitutionValues \ .assert_called_once_with(mockWorksheet) mockWorksheetTitle.assert_called_once_with()
def test_endian_delegation(self, delegatee): p = PropertyMock(return_value='<') type(delegatee).endian = p dd = DelegatingDataset(delegatee) e = dd.endian p.assert_called_once_with() assert e == '<'
def test_encoding_delegation(self, delegatee): p = PropertyMock(return_value='ascii') type(delegatee).encoding = p dd = DelegatingDataset(delegatee) e = dd.encoding p.assert_called_once_with() assert e == 'ascii'
def test_propertymock_returnvalue(self): m = MagicMock() p = PropertyMock() type(m).foo = p returned = m.foo p.assert_called_once_with() self.assertIsInstance(returned, MagicMock) self.assertNotIsInstance(returned, PropertyMock)
def test_propertymock_returnvalue(self): m = MagicMock() p = PropertyMock() type(m).foo = p returned = m.foo p.assert_called_once_with() self.assertIsInstance(returned, MagicMock) self.assertNotIsInstance(returned, PropertyMock)
def test_checkout_no_repo(mocked_config): git_mixin = get_git_mixin_consumer() mocked_config.settings.dry_run = False mocked_repo_prop = PropertyMock(return_value=None) type(mocked_config).repo = mocked_repo_prop git_mixin.checkout_branch() mocked_repo_prop.assert_called_once_with()
def test_load(self): mock_features = PropertyMock(return_value=[1, 2, 3]) mock_labels = PropertyMock(return_value=[1, 2, 3]) mock_censoring = PropertyMock(return_value=[1, 2, 3]) with patch.object(ConvSccsFeatureDriver, "features", new_callable=mock_features): with patch.object(ConvSccsFeatureDriver, "labels", new_callable=mock_labels): with patch.object(ConvSccsFeatureDriver, "censoring", new_callable=mock_censoring): loader_ = ConvSccsFeatureDriver(**self.kwargs) loader_.load() mock_features.assert_called_with() mock_labels.assert_called_once_with() mock_censoring.assert_called_once_with() mock_missing_labels = PropertyMock(return_value=[1, 2]) mock_missing_censoring = PropertyMock(return_value=[1, 2]) with patch.object(ConvSccsFeatureDriver, "features", new_callable=mock_features): with patch.object(ConvSccsFeatureDriver, "labels", new_callable=mock_missing_labels): with patch.object(ConvSccsFeatureDriver, "censoring", new_callable=mock_censoring): loader_ = ConvSccsFeatureDriver(**self.kwargs) with self.assertRaises(AssertionError) as context: loader_.load() self.assertTrue( "Number of feature matrices does not match " "number of label matrices. You might want to" " investigate this" in str(context.exception)) with patch.object(ConvSccsFeatureDriver, "features", new_callable=mock_features): with patch.object(ConvSccsFeatureDriver, "labels", new_callable=mock_labels): with patch.object( ConvSccsFeatureDriver, "censoring", new_callable=mock_missing_censoring, ): loader_ = ConvSccsFeatureDriver(**self.kwargs) with self.assertRaises(AssertionError) as context: loader_.load() self.assertTrue( "Number of feature matrices does not match " "number of censoring values. You might want to" " investigate this" in str(context.exception))
def test_get_service_input(self): form = MagicMock() cleaned_data = PropertyMock(return_value={}) type(form).cleaned_data = cleaned_data view = MockView() rv = view.get_service_input(form) cleaned_data.assert_called_once_with() self.assertEqual({}, rv)
def test_git_add_no_repo(mocked_config): expected_path = Path("/tmp/path") git_mixin = get_git_mixin_consumer() mocked_config.settings.dry_run = False mocked_repo_prop = PropertyMock(return_value=None) type(mocked_config).repo = mocked_repo_prop git_mixin.git_add(expected_path) mocked_repo_prop.assert_called_once_with()
def test_url(self, mock__auth: PropertyMock) -> None: """Testign getter of the proxy URL""" mock__auth.side_effect = lambda: 'L:P@' proxy: Proxy = Proxy() proxy.ip = '' proxy.port = 81 proxy.protocol = 'HTTP' self.assertEqual(proxy.url, '') mock__auth.assert_not_called() proxy.ip = 'IP' self.assertEqual(proxy.url, 'HTTP://*****:*****@IP:81') mock__auth.assert_called_once_with()
def testFixVisibleLevelsDoesNotMatch(self): fieldname = 'name1' newfieldname = 'name2' mock_root = MagicMock(name='mock_root') mock_node1 = MagicMock(name='mock_node1') mock_node1_text = PropertyMock(return_value='something else') type(mock_node1).text = mock_node1_text mock_root.xpath = MagicMock(side_effect=[[mock_node1]]) self.common.fixVisibleLevels(root=mock_root, fieldname=fieldname, newfieldname=newfieldname, log=self.log) mock_node1_text.assert_called_once_with()
def test_machine_meta_data_translation_mapping(self): machine_meta_data_translation_mock = PropertyMock( return_value=AttributeDict(Cores=1, Memory=1024, Disk=1024) ) type( self.batch_system_adapter ).machine_meta_data_translation_mapping = machine_meta_data_translation_mock self.assertEqual( AttributeDict(Cores=1, Memory=1024, Disk=1024), self.batch_system_agent.machine_meta_data_translation_mapping, ) machine_meta_data_translation_mock.assert_called_once_with()
class TestSubjectFactory(unittest.TestCase): def setUp(self): self.properties = {'Group': 'Sham'} self.database = patientalloc.Database() self.entries = PropertyMock(return_value={1, 2, 3}) type(self.database).entries = self.entries self.database.getGroupFromNewEntry = MagicMock( return_value=self.properties['Group']) self.database.getEntryGroup = MagicMock() self.settings = MagicMock() self.subjectCreationType = PropertyMock(return_value='Simple') type(self.settings).subjectCreationType = self.subjectCreationType self.subjectFactory = patientalloc.SubjectFactory( self.database, self.settings) def testSubjectFactoryCreation(self): self.assertEqual(self.subjectFactory.database, self.database) self.assertEqual(self.subjectFactory.settings, self.settings) def testSimpleSubjectCreation(self): subject = self.subjectFactory.createSubject(self.properties) self.assertEqual(subject.properties, self.properties) self.assertIsInstance(subject, patientalloc.Subject) self.database.getGroupFromNewEntry.assert_called_with(self.properties) self.subjectCreationType.assert_called_with() def testBCISubjectCreation(self): self.subjectCreationType = PropertyMock(return_value='BCI') self.database.getEntryGroup.side_effect = ['Sham', 'BCI'] self.database.getEntryId = MagicMock(return_value='s04') type(self.settings).subjectCreationType = self.subjectCreationType subject = self.subjectFactory.createSubject(self.properties) self.assertIsInstance(subject, patientalloc.BCISubject) self.assertEqual(subject.properties, self.properties) self.database.getGroupFromNewEntry.assert_called_with(self.properties) self.subjectCreationType.assert_called_with() self.assertEqual(subject.matching_subject_id, 's04') def testGetMatchingSubjectId(self): self.database.getEntryGroup.side_effect = ['Sham', 'BCI'] self.database.getEntryId = MagicMock(return_value='s03') matching_subject_id = self.subjectFactory.getMatchingSubjectId() self.assertEqual(matching_subject_id, 's03') self.assertEqual(self.database.getEntryId.call_count, 1) self.entries.assert_called_once_with() self.assertEqual(self.database.getEntryGroup.call_count, 2)
def test__write__new_timestamp_queried_for_each_value(self): writer = self.MockBufferedTagWriter(Mock(ITimeStamper), 3) item = object() writer.mock_create_item.configure_mock(side_effect=None, return_value=item) writer.mock_buffer_value.configure_mock(side_effect=None) timestamp_property = PropertyMock( return_value=datetime.datetime.now(datetime.timezone.utc)) type(writer.time_stamper).timestamp = timestamp_property writer.write("tag", tbase.DataType.BOOLEAN, False, timestamp=None) timestamp_property.assert_called_once_with() timestamp_property.reset_mock() writer.write("tag", tbase.DataType.BOOLEAN, False, timestamp=None) timestamp_property.assert_called_once_with()
def test_creates_and_caches_proxy_objects(self): connection = Mock() p = PropertyMock(return_value='Account') type(connection).Account = p oc = amaxa.Operation(connection) proxy = oc.get_proxy_object('Account') self.assertEqual('Account', proxy) p.assert_called_once_with() p.reset_mock() proxy = oc.get_proxy_object('Account') # Proxy should be cached self.assertEqual('Account', proxy) p.assert_not_called()
def test_before_after(self, property_name): """Test that the property returns the value of the associated buffer attribute of pexpect.spawn split across lines.""" mock_pexpect_spawn = create_autospec( spec=pexpect.spawn, instance=True, ) mock_attribute = PropertyMock(return_value=b"foo\nbar") setattr(type(mock_pexpect_spawn), property_name, mock_attribute) # Need to add the mock spawn instance as the _proc on the expectmore instance. test_expectmore = ExpectMore() test_expectmore._proc = mock_pexpect_spawn # Read the property result = getattr(test_expectmore, property_name) # Expect the attribute to be accessed mock_attribute.assert_called_once_with() # Expect the result to match the expected result assert mock_attribute.return_value.decode().splitlines() == result
def test_download_results_expired_url(self, get_mock): requests_result_mock = Mock() status_code_mock = PropertyMock(return_value=404) type(requests_result_mock).status_code = status_code_mock content_mock = PropertyMock(return_value=bytes()) type(requests_result_mock).content = content_mock url_mock = PropertyMock(return_value="http://foo.bar.com/file.tar.xz") type(requests_result_mock).url = url_mock headers_mock = PropertyMock( return_value={"Content-Type": "application/x-tar"}) type(requests_result_mock).headers = headers_mock get_mock.return_value = requests_result_mock results = self.plugin._download_results(RESULT_DICT) status_code_mock.assert_called_once_with() content_mock.assert_not_called() self.assertEqual(self.plugin.tradefed_results_url, RESULT_URL) self.assertIsNone(results.test_results) self.assertIsNone(results.tradefed_stdout) self.assertIsNone(results.tradefed_logcat)
def test__null_timestamp_and_time_stamper_given__write__time_stamper_used( self): date_string = "2019-07-08T18:52:58.230069+0000" date_offset = datetime.datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%f%z") writer = self.MockBufferedTagWriter(Mock(ITimeStamper), 2) item = object() writer.mock_create_item.configure_mock(side_effect=None, return_value=item) writer.mock_buffer_value.configure_mock(side_effect=None, return_value=None) timestamp_property = PropertyMock(return_value=date_offset) type(writer.time_stamper).timestamp = timestamp_property writer.write("tag", tbase.DataType.BOOLEAN, False, timestamp=None) writer.mock_create_item.assert_called_once_with( "tag", tbase.DataType.BOOLEAN, "False", date_offset) writer.mock_buffer_value.assert_called_once_with("tag", item) timestamp_property.assert_called_once_with()
def test_download_results_short_file(self, get_mock, tarfile_mock): requests_result_mock = Mock() status_code_mock = PropertyMock(return_value=200) type(requests_result_mock).status_code = status_code_mock content_mock = PropertyMock(return_value=self.tarfile.read()) type(requests_result_mock).content = content_mock url_mock = PropertyMock(return_value="http://foo.bar.com/file.tar.xz") type(requests_result_mock).url = url_mock headers_mock = PropertyMock( return_value={"Content-Type": "application/x-tar"}) type(requests_result_mock).headers = headers_mock get_mock.return_value = requests_result_mock tarfile_mock.side_effect = EOFError() results = self.plugin._download_results(RESULT_DICT) status_code_mock.assert_called_once_with() self.assertEqual(content_mock.call_count, 2) self.assertEqual(self.plugin.tradefed_results_url, RESULT_URL) self.assertIsNone(results.test_results) self.assertIsNone(results.tradefed_stdout) self.assertIsNone(results.tradefed_logcat)
def test_only_updates_pid_values_if_changed(self, pid_mock_class): pid_mock = pid_mock_class.return_value tunings_mock = PropertyMock() type(pid_mock).tunings = tunings_mock tunings_mock.return_value = (1, 2, 3) components_mock = PropertyMock() type(pid_mock).components = components_mock components_mock.return_value = (4, 3, 2) controller = Controller(self.config, 5, 0.5, self.heater, self.cooler, self.limiter, self.current_temp, self.fridge_temp, []) pid_mock.return_value = 5 controller.control() tunings_mock.assert_called_once_with() # the getter, not the setter
def test_postprocess_testjob_save_attachments( self, results_url_mock, get_from_artifactorial_mock, assign_test_log_mock, create_testrun_attachment_mock, ): results_url_mock.return_value = "http://foo.com" result_files = ResultFiles() result_files.test_results = ExtractedResult() result_files.test_results.contents = BytesIO("abc".encode("utf-8")) result_files.test_results.length = 3 get_from_artifactorial_mock.return_value = result_files testjob_mock = MagicMock() id_mock = PropertyMock(return_value="999111") type(testjob_mock).pk = id_mock job_id_mock = PropertyMock(return_value="1234") type(testjob_mock).job_id = job_id_mock testjob_mock.backend = MagicMock() implementation_type_mock = PropertyMock(return_value="lava") type(testjob_mock.backend ).implementation_type = implementation_type_mock definition_mock = PropertyMock(return_value=JOB_DEFINITION) type(testjob_mock).definition = definition_mock testjob_target = MagicMock() project_settings_mock = PropertyMock(return_value='{}') type(testjob_target).project_settings = project_settings_mock type(testjob_mock).target = testjob_target self.plugin.postprocess_testjob(testjob_mock) implementation_type_mock.assert_called_once_with() definition_mock.assert_called_with() results_url_mock.assert_called_with() testjob_mock.testrun.metadata.__setitem__.assert_called_with( 'tradefed_results_url_1234', 'http://foo.com') testjob_mock.testrun.save.assert_called_with() # uncomment when moving to python 3.6 #assign_test_log_mock.assert_called() create_testrun_attachment_mock.assert_called_with( testjob_mock.testrun, 'test_results.xml', result_files.test_results, 'application/xml')
class TestBotutils(unittest.TestCase): def setUp(self): self.message = MagicMock() self.prop = PropertyMock() def test_is_channel_valid_empty_config(self): self.prop.return_value = 'can be anything' type(self.message.channel).name = self.prop ret_val = botutils.is_channel_valid({}, 'anything', self.message) self.assertTrue(ret_val) self.prop.assert_not_called() def test_is_channel_valid_valid_config(self): self.prop.return_value = 'valid channel name' type(self.message.channel).name = self.prop ret_val = botutils.is_channel_valid( {'attribute': ['valid channel name']}, 'attribute', self.message) self.assertTrue(ret_val) self.prop.assert_called_once_with() # Helper def has_prefix_helper(self, config_prefix, actual_prefix, expected): self.prop.return_value = f'{actual_prefix}foo bar it' type(self.message).content = self.prop ret_val = botutils.has_prefix({'prefix': config_prefix}, self.message) self.assertEqual(ret_val, expected) self.prop.assert_called_once_with() def test_has_prefix_valid_len_one(self): self.has_prefix_helper('!', '!', True) def test_has_prefix_valid_len_random(self): prefix = '!' * random.randint(0, 100) self.has_prefix_helper(prefix, prefix, True) def test_has_prefix_valid_invalid(self): self.has_prefix_helper('a', 'b', False) # Helper def get_content_without_prefix_helper(self, prefix, message, expected): self.prop.return_value = message type(self.message).content = self.prop ret_val = botutils.get_content_without_prefix({'prefix': prefix}, self.message) self.assertEqual(ret_val, expected) self.prop.assert_called_once_with() def test_get_content_without_prefix_prefix_len_one(self): self.get_content_without_prefix_helper('!', '!one two three', 'one two three') def test_get_content_without_prefix_prefix_len_random(self): prefix = '!' * random.randint(0, 100) self.get_content_without_prefix_helper(prefix, f'{prefix}one two three', 'one two three')
def test_list_permissions(self, mock_boto_client): cognito_idp_mock = MagicMock() mock_boto_client.return_value = cognito_idp_mock admin_get_user = PropertyMock( return_value={ "UserAttributes": [ { "Name": "name", "value": "unknown" }, { "Name": "email", "value": "unknown" }, ] }) cognito_idp_mock.admin_get_user = admin_get_user """Load form permissions.""" response = self.lg.handle_request( method="GET", path=f"/forms/{self.formId}/permissions", headers={"authorization": "auth"}, body="", ) self.assertEqual(response["statusCode"], 200, response) body = json.loads(response["body"]) # Do permissions have at least an id and name and email? for userId, user in body["res"]["userLookup"].items(): self.assertEqual(user["id"], DEV_COGNITO_IDENTITY_ID) self.assertEqual(user["name"], "unknown") self.assertEqual(user["email"], "unknown") self.assertEqual(userId, user["id"]) for perm in body["res"]["permissions"].values(): self.assertTrue(type(perm) is dict) self.assertTrue(type(body["res"]["possiblePermissions"]) is list) mock_boto_client.assert_called_once_with("cognito-idp", region_name=AWS_REGION) admin_get_user.assert_called_once_with( UserPoolId=USER_POOL_ID, Username=DEV_COGNITO_IDENTITY_ID_SPLIT)
def test_section_exists_add_before(mocked_updater_class): mock_file = Mock() expected_path = Mock() expected_path.open.return_value.__enter__ = Mock(return_value=mock_file) expected_path.open.return_value.__exit__ = Mock() expected_section = Mock() mock_add_before_return = Mock() expected_match = Mock() mocked_prop = PropertyMock(return_value=mock_add_before_return) type(expected_match).add_before = mocked_prop mocked_updater = MagicMock() mocked_updater.__getitem__.return_value = expected_match mocked_updater.sections.return_value = [expected_match] mocked_updater.has_section.side_effect = [False, True] mocked_updater_class.return_value = mocked_updater rule = SectionExists( name="Section exists rule", path=expected_path, section=expected_section, match=expected_match, add_after=False, ) result = rule.task() mocked_updater.sections.assert_called_once_with() mocked_updater.has_section.has_calls(call(expected_section), call(expected_match)) mocked_prop.assert_called_once_with() mock_add_before_return.section.assert_called_once_with(expected_section) assert mock_add_before_return.section.return_value.space.called is False assert result == expected_path
def test_section_exists_no_match(mocked_updater_class): mock_file = Mock() expected_path = Mock() expected_path.open.return_value.__enter__ = Mock(return_value=mock_file) expected_path.open.return_value.__exit__ = Mock() expected_section = Mock() mock_add_after_return = Mock() expected_match = Mock() mocked_prop = PropertyMock(return_value=mock_add_after_return) type(expected_match).add_after = mocked_prop mocked_updater = MagicMock() mocked_updater.sections.return_value = [expected_match] mocked_updater.sections_blocks.return_value = mocked_updater.sections.return_value mocked_updater.has_section.side_effect = [False, False] mocked_updater_class.return_value = mocked_updater rule = SectionExists( name="Section exists rule", path=expected_path, section=expected_section, match=Mock(), ) result = rule.task() mocked_updater.sections.assert_called_once_with() mocked_updater.has_section.has_calls(call(expected_section), call(expected_match)) mocked_prop.assert_called_once_with() mock_add_after_return.space.assert_called_once_with(rule.space) mock_add_after_return.space.return_value.section.assert_called_once_with( expected_section) assert result == expected_path