Beispiel #1
0
    def test_updates_pid_values_on_control(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, [])

        self.config.get.side_effect = lambda key: {
            "p": 4,
            "i": 5,
            "d": 6,
            "target": 23,
            "heating_limit": 40,
            "limit_window": 5
        }.get(key)

        pid_mock.return_value = 5

        controller.control()

        tunings_mock.assert_called_with((4, 5, 6))
Beispiel #2
0
 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()
Beispiel #3
0
 def test_dac_throws_always(self, gpio, dac, swim_pump_device):
     normalized_value = PropertyMock()
     normalized_value.side_effect = OSError()
     type(dac).normalized_value = normalized_value
     swim_pump_device.speed(50)
     gpio.output.assert_has_calls([call(PIN, True), call(PIN, False)])
     normalized_value.assert_called_with(0.5)
     assert normalized_value.call_count == 3
Beispiel #4
0
    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_volume_size(
    file_size: int,
    expected_train_volume_size: int,
    prop_train_volume_size: PropertyMock,
    sm_execution_engine_to_test: SageMakerExecutionEngine,
    fetcher_event: FetcherBenchmarkEvent,
):
    fetcher_event.payload.datasets[0].size_info.max_size = file_size
    fetcher_event.payload.datasets[0].size_info.total_size = file_size

    sm_execution_engine_to_test.run(fetcher_event)
    prop_train_volume_size.assert_called_with(expected_train_volume_size)
Beispiel #6
0
    def test_zap_wait_for_passive_scan_until_timeout(self):
        """Waits for the passive scan to finish until timeout."""
        zap = Mock()
        records_to_scan = PropertyMock(return_value="10")
        type(zap.pscan).records_to_scan = records_to_scan
        timeout_in_secs = 10

        with patch("time.sleep"):
            zap_common.zap_wait_for_passive_scan(zap, timeout_in_secs)

        records_to_scan.assert_called_with()
        self.assertGreater(records_to_scan.call_count, 5)
 def testFixVisibleLevels(self):
     fieldname = 'name1'
     newfieldname = 'name2'
     mock_root = MagicMock(name='mock_root')
     mock_node1 = MagicMock(name='mock_node1')
     mock_node1_text = PropertyMock(return_value=fieldname)
     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_with(newfieldname)
Beispiel #8
0
    def test_zap_wait_for_passive_scan(self):
        """Waits for the passive scan to finish."""
        zap = Mock()
        records_to_scan = PropertyMock(side_effect=Mock(
            side_effect=["15", "10", "5", "0"]))
        type(zap.pscan).records_to_scan = records_to_scan
        timeout_in_secs = None

        with patch("time.sleep"):
            zap_common.zap_wait_for_passive_scan(zap, timeout_in_secs)

        records_to_scan.assert_called_with()
        self.assertEqual(4, records_to_scan.call_count)
Beispiel #9
0
 def test_dac_throws_once(self, gpio, dac, swim_pump_device):
     def side_effect(value):
         side_effect.counter += 1
         if side_effect.counter == 1:
             raise OSError()
         return DEFAULT
     side_effect.counter = 0
     normalized_value = PropertyMock()
     normalized_value.side_effect = side_effect
     type(dac).normalized_value = normalized_value
     swim_pump_device.speed(50)
     gpio.output.assert_has_calls([call(PIN, True), call(PIN, False)])
     normalized_value.assert_called_with(0.5)
     assert normalized_value.call_count == 2
Beispiel #10
0
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)
Beispiel #11
0
 def test_get_from_artifactorial_empty_results(self, download_results_mock):
     suite_name = "2_bar"
     download_results_mock.return_value = ResultFiles()
     testjob_mock = Mock()
     testjob_mock.backend.get_implementation(
     ).proxy.results.get_testjob_suites_list_yaml.return_value = (SUITES)
     testjob_mock.backend.get_implementation(
     ).proxy.results.get_testsuite_results_yaml.return_value = ("[]")
     job_id_mock = PropertyMock(return_value=999)
     type(testjob_mock).job_id = job_id_mock
     result = self.plugin._get_from_artifactorial(testjob_mock, suite_name)
     job_id_mock.assert_called_with()
     testjob_mock.backend.get_implementation(
     ).proxy.results.get_testjob_suites_list_yaml.assert_called_once_with(
         999)
     testjob_mock.backend.get_implementation(
     ).proxy.results.get_testsuite_results_yaml.assert_called_with(
         999, '2_bar', 500, 0)
     self.assertIsNone(result)
Beispiel #12
0
    def test_zap_ajax_spider(self):
        """AJAX Spider is started and waits until finished."""
        zap = Mock()
        zap.ajaxSpider.scan.return_value = "OK"
        status = PropertyMock(side_effect=Mock(
            side_effect=["running", "running", "stopped"]))
        type(zap.ajaxSpider).status = status
        number_of_results = PropertyMock(return_value=10)
        type(zap.ajaxSpider).number_of_results = number_of_results
        target = "http://target.example.com"
        max_time = None

        with patch("time.sleep"):
            zap_common.zap_ajax_spider(zap, target, max_time)

        zap.ajaxSpider.scan.assert_called_once_with(target, contextname=None)
        status.assert_called_with()
        self.assertEqual(3, status.call_count)
        number_of_results.assert_called_with()
        self.assertEqual(2, number_of_results.call_count)
Beispiel #13
0
    def test_tests_with_regex_characters(self):
        test = Mock()
        test_name = PropertyMock(return_value="test[a-1]")
        type(test).name = test_name
        test_log = PropertyMock()
        type(test).log = test_log

        testrun = Mock()
        testrun_log = PropertyMock(return_value=TEST_LOG)
        type(testrun).log_file = testrun_log

        testrun.tests = Mock()
        testrun.tests.filter.return_value = [test]

        self.plugin.postprocess_testrun(testrun)

        test_name.assert_called_with()
        # uncomment when running with python3.6
        #test_log.assert_called()
        test.save.assert_called_with()
Beispiel #14
0
 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')
Beispiel #15
0
    def test_postprocess_testrun(self):
        test_1 = Mock()
        test_1_name = PropertyMock(return_value="test_1")
        type(test_1).name = test_1_name
        test_1_log = PropertyMock()
        type(test_1).log = test_1_log

        test_2 = Mock()
        test_2_name = PropertyMock(return_value="test_2")
        type(test_2).name = test_2_name
        test_2_log = PropertyMock()
        type(test_2).log = test_2_log

        test_3 = Mock()
        test_3_name = PropertyMock(return_value="test_3")
        type(test_3).name = test_3_name
        test_3_log = PropertyMock()
        type(test_3).log = test_3_log

        testrun = Mock()
        testrun_log = PropertyMock(return_value=TEST_LOG)
        type(testrun).log_file = testrun_log

        testrun.tests = Mock()
        testrun.tests.filter.return_value = [test_1, test_2, test_3]

        self.plugin.postprocess_testrun(testrun)
        testrun.tests.filter.assert_called_with(result=False)
        testrun_log.assert_called_with()

        test_1_name.assert_called_with()
        # uncomment when running with python3.6
        #test_1_log.assert_called()
        test_1.save.assert_called_with()

        # test_2 not present in the log
        test_2_name.assert_called_with()
        test_2_log.assert_not_called()
        test_2.save.assert_not_called()

        test_3_name.assert_called_with()
        # uncomment when running with python3.6
        #test_3_log.assert_called()
        test_3.save.assert_called_with()
    def test_writes_temperatures_to_lcd(self, lcd_mock_class):
        lcd_mock = lcd_mock_class.return_value

        cursor_mock = PropertyMock()
        type(lcd_mock).cursor_pos = cursor_mock

        display = Display(["environment", "vessel", "fridge", "target"], [])

        display.handle_temperature("environment", 12.3, 3)
        cursor_mock.assert_called_with((0, 0))
        lcd_mock.write_string.assert_called_with("E 12.3")

        display.handle_temperature("vessel", 14.3, 3)
        cursor_mock.assert_called_with((0, 7))
        lcd_mock.write_string.assert_called_with("V 14.3")

        display.handle_temperature("fridge", 11.3, 3)
        cursor_mock.assert_called_with((1, 0))
        lcd_mock.write_string.assert_called_with("F 11.3")

        display.handle_temperature("target", 22.3, 3)
        cursor_mock.assert_called_with((1, 7))
        lcd_mock.write_string.assert_called_with("T 22.3")
    def test_writes_switches_to_lcd(self, lcd_mock_class):
        lcd_mock = lcd_mock_class.return_value

        cursor_mock = PropertyMock()
        type(lcd_mock).cursor_pos = cursor_mock

        display = Display([], ["heater", "cooler", "limiter"])

        display.handle_switch("heater", True)
        cursor_mock.assert_called_with((0, 14))
        lcd_mock.write_string.assert_called_with("H")

        display.handle_switch("heater", False)
        cursor_mock.assert_called_with((0, 14))
        lcd_mock.write_string.assert_called_with(" ")

        display.handle_switch("cooler", True)
        cursor_mock.assert_called_with((1, 14))
        lcd_mock.write_string.assert_called_with("C")

        display.handle_switch("cooler", False)
        cursor_mock.assert_called_with((1, 14))
        lcd_mock.write_string.assert_called_with(" ")

        display.handle_switch("limiter", True)
        cursor_mock.assert_called_with((0, 15))
        lcd_mock.write_string.assert_called_with("L")

        display.handle_switch("limiter", False)
        cursor_mock.assert_called_with((0, 15))
        lcd_mock.write_string.assert_called_with(" ")
Beispiel #18
0
    def test_get_settings_returns_correct_result(self):
        # Arrange
        debug = False
        strict = False

        service_provider_debug_mode_mock = PropertyMock(return_value=debug)
        service_provider_strict_mode_mock = PropertyMock(return_value=strict)

        configuration = create_autospec(spec=SAMLConfiguration)
        type(configuration
             ).service_provider_debug_mode = service_provider_debug_mode_mock
        type(configuration
             ).service_provider_strict_mode = service_provider_strict_mode_mock
        configuration.get_service_provider = MagicMock(
            return_value=SERVICE_PROVIDER_WITH_CERTIFICATE)
        configuration.get_identity_providers = MagicMock(
            return_value=IDENTITY_PROVIDERS)

        onelogin_configuration = SAMLOneLoginConfiguration(configuration)

        expected_result = {
            "debug": debug,
            "strict": strict,
            "idp": {
                "entityId": IDENTITY_PROVIDERS[0].entity_id,
                "singleSignOnService": {
                    "url": IDENTITY_PROVIDERS[0].sso_service.url,
                    "binding": IDENTITY_PROVIDERS[0].sso_service.binding.value,
                },
                "singleLogoutService": {},
                "x509cert": "",
                "certFingerprint": "",
                "certFingerprintAlgorithm": "sha1",
            },
            "sp": {
                "entityId":
                SERVICE_PROVIDER_WITH_CERTIFICATE.entity_id,
                "assertionConsumerService": {
                    "url":
                    SERVICE_PROVIDER_WITH_CERTIFICATE.acs_service.url,
                    "binding":
                    SERVICE_PROVIDER_WITH_CERTIFICATE.acs_service.binding.
                    value,
                },
                "attributeConsumingService": {},
                "singleLogoutService": {
                    "binding":
                    "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"
                },
                "NameIDFormat":
                SERVICE_PROVIDER_WITH_CERTIFICATE.name_id_format,
                "x509cert":
                fixtures.strip_certificate(
                    SERVICE_PROVIDER_WITH_CERTIFICATE.certificate),
                "privateKey":
                SERVICE_PROVIDER_WITH_CERTIFICATE.private_key,
            },
            "security": {
                "failOnAuthnContextMismatch":
                False,
                "requestedAuthnContextComparison":
                "exact",
                "wantNameIdEncrypted":
                False,
                "authnRequestsSigned":
                SERVICE_PROVIDER_WITH_CERTIFICATE.authn_requests_signed
                or IDENTITY_PROVIDERS[0].want_authn_requests_signed,
                "logoutResponseSigned":
                False,
                "wantMessagesSigned":
                False,
                "metadataCacheDuration":
                None,
                "requestedAuthnContext":
                True,
                "logoutRequestSigned":
                False,
                "wantAttributeStatement":
                True,
                "signMetadata":
                False,
                "digestAlgorithm":
                "http://www.w3.org/2000/09/xmldsig#sha1",
                "metadataValidUntil":
                None,
                "wantAssertionsSigned":
                False,
                "wantNameId":
                True,
                "wantAssertionsEncrypted":
                False,
                "nameIdEncrypted":
                False,
                "signatureAlgorithm":
                "http://www.w3.org/2000/09/xmldsig#rsa-sha1",
                "allowRepeatAttributeName":
                False,
            },
        }
        db = create_autospec(spec=sqlalchemy.orm.session.Session)

        # Act
        result = onelogin_configuration.get_settings(
            db, IDENTITY_PROVIDERS[0].entity_id)

        # Assert
        result["sp"]["x509cert"] = fixtures.strip_certificate(
            result["sp"]["x509cert"])

        assert result == expected_result
        service_provider_debug_mode_mock.assert_called_with()
        service_provider_strict_mode_mock.assert_called_with()
        configuration.get_service_provider.assert_called_with(db)
        configuration.get_identity_providers.assert_called_with(db)