How to use the mock.patch.dict function in mock

To help you get started, we’ve selected a few mock examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openstack / rally-openstack / tests / unit / test_osclients.py View on Github external
def test_ceilometer(self, mock_ceilometer__get_endpoint):
        fake_ceilometer = fakes.FakeCeilometerClient()
        mock_ceilometer = mock.MagicMock()
        mock_ceilometer__get_endpoint.return_value = "http://fake.to:2/fake"
        mock_keystoneauth1 = mock.MagicMock()
        mock_ceilometer.client.get_client = mock.MagicMock(
            return_value=fake_ceilometer)
        self.assertNotIn("ceilometer", self.clients.cache)
        with mock.patch.dict("sys.modules",
                             {"ceilometerclient": mock_ceilometer,
                              "keystoneauth1": mock_keystoneauth1}):
            client = self.clients.ceilometer()
            self.assertEqual(fake_ceilometer, client)
            kw = {
                "session": mock_keystoneauth1.session.Session(),
                "endpoint_override": mock_ceilometer__get_endpoint.return_value
            }
            mock_ceilometer.client.get_client.assert_called_once_with("2",
                                                                      **kw)
            self.assertEqual(fake_ceilometer,
                             self.clients.cache["ceilometer"])
github airbnb / streamalert / tests / unit / stream_alert_rule_processor / test_handler.py View on Github external
    @patch.dict(os.environ, {'ALERT_PROCESSOR': 'unit-testing_streamalert_alert_processor',
                             'ALERTS_TABLE': 'unit-testing_streamalert_alerts'})
    def test_run_threat_intel_empty_exclude_list(self, mock_threat_intel, mock_query): # pylint: disable=no-self-use
        """StreamAlert Class - Run SA when threat intel enabled but null exclude list"""
        @rule(datatypes=['sourceAddress'], outputs=['s3:sample_bucket'])
        def match_ip_address(_): # pylint: disable=unused-variable
            """Testing dummy rule"""
            return True

        mock_threat_intel.return_value = StreamThreatIntel(excluded_iocs=None,
                                                           table='test_table_name',
                                                           region='us-east-1')
        mock_query.return_value = ([], [])

        sa_handler = handler.StreamAlert(get_mock_context())
        event = {
            'account': 123456,
github inspirehep / inspire-next / tests / unit / workflows / test_workflows_tasks_classifier.py View on Github external
def test_get_classifier_api_url_returns_none_when_not_in_configuration():
    config = {'CLASSIFIER_API_URL': ''}

    with patch.dict(current_app.config, config):
        assert get_classifier_url() is None
github openstack / rally / tests / unit / env / test_env_mgr.py View on Github external
    @mock.patch.dict(os.environ, values={"KEY": "value"}, clear=True)
    @mock.patch("rally.env.platform.Platform.get_all")
    def test_create_spec_from_sys_environ(self, mock_platform_get_all):

        # let's cover all positive and minor cases at once

        class Foo1Platform(platform.Platform):
            """This platform doesn't override original methods"""

            @classmethod
            def get_fullname(cls):
                return cls.__name__

        class Foo2Platform(Foo1Platform):
            """This platform should try to modify sys environment"""

            @classmethod
github edx / bok-choy / tests / test_browser.py View on Github external
    @patch.dict(os.environ, [('SELENIUM_FIREFOX_LOG', '/foo/file.log')])
    def test_custom_firefox_log(self):
        self.verify_config(custom_log='/foo/file.log')
github inspirehep / inspire-next / tests / integration / disambiguation / test_disambiguation_api.py View on Github external
def test_save_publications(isolated_app, tmpdir):
    TestRecordMetadata.create_from_file(__name__, '792017.json')

    publications_fd = tmpdir.join('publications.jsonl')

    config = {'DISAMBIGUATION_PUBLICATIONS_PATH': str(publications_fd)}

    with patch.dict(current_app.config, config):
        save_publications()

    publications = [json.loads(line) for line in publications_fd.readlines()]

    assert {
        'abstract': 'This talk describes past progress in probing the structure of matter and the content of the Universe, which has led to the Standard Model of elementary particles, and the prospects for establishing new physics beyond the Standard Model using the LHC particle collider at CERN.',
        'authors': ['Ellis, John R.'],
        'collaborations': [],
        'keywords': [
            '29.20.Db',
            '98.80.-k',
            '12.60.-i',
            'elementary particles',
            'standard model',
            'cosmology',
            'particle accelerators',
github onecodex / onecodex / tests / test_raven.py View on Github external
def test_bad_sentry_dsn():
    with mock.patch.dict(os.environ, {"ONE_CODEX_SENTRY_DSN": "bad"}):
        raven = get_raven_client()
        assert raven is None
github openstack / rally-openstack / tests / unit / plugins / openstack / test_osclients.py View on Github external
def test_create_from_env(self):
        with mock.patch.dict("os.environ",
                             {"OS_AUTH_URL": "foo_auth_url",
                              "OS_USERNAME": "foo_username",
                              "OS_PASSWORD": "foo_password",
                              "OS_TENANT_NAME": "foo_tenant_name",
                              "OS_REGION_NAME": "foo_region_name"}):
            clients = osclients.Clients.create_from_env()

        self.assertEqual("foo_auth_url", clients.credential.auth_url)
        self.assertEqual("foo_username", clients.credential.username)
        self.assertEqual("foo_password", clients.credential.password)
        self.assertEqual("foo_tenant_name", clients.credential.tenant_name)
        self.assertEqual("foo_region_name", clients.credential.region_name)
github openstack / python-swiftclient / tests / unit / test_shell.py View on Github external
'OS_AUTH_URL': 'https://keystone.example.com/v2.0/',
            'OS_TENANT_NAME': 'demo',
            'OS_USERNAME': 'demo',
            'OS_PASSWORD': 'admin',
        }
        os_environ.update(pre_auth_env)
        os_environ['OS_AUTH_TOKEN'] = 'expired'

        fake_conn = self.fake_http_connection(401, 200)
        fake_keystone = fake_get_auth_keystone(storage_url=url + '_not_used',
                                               token=token + '_new')
        with mock.patch.multiple('swiftclient.client',
                                 http_connection=fake_conn,
                                 get_auth_keystone=fake_keystone,
                                 sleep=mock.DEFAULT):
            with mock.patch.dict(os.environ, os_environ):
                argv = ['', 'stat']
                swiftclient.shell.main(argv)
        self.assertRequests([
            ('HEAD', url, '', {
                'x-auth-token': 'expired',
            }),
            ('HEAD', url, '', {
                'x-auth-token': token + '_new',
            }),
github mozilla / amo-validator / tests / test_targetapplication.py View on Github external
@patch.dict('validator.constants.APPROVED_APPLICATIONS',
            values=MISSING_ANDROID_APPROVED_APPLICATIONS,
            clear=True)
def test_unsupported_mozilla_app_in_approved_apps():
    """
    Test that non approved applications are not validated.

    We submit an add-on which has *only* one targetApplication,
    which targetApplication is a valid Mozilla app but it's missing
    from the approved applications.
    """

    failure_case = """