python类dict()的实例源码

__init__.py 文件源码 项目:dfkernel 作者: dataflownb 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def setup():
    """setup temporary env for tests"""
    global tmp
    tmp = tempfile.mkdtemp()
    patchers[:] = [
        patch.dict(os.environ, {
            'HOME': tmp,
            # Let tests work with --user install when HOME is changed:
            'PYTHONPATH': os.pathsep.join(sys.path),
        }),
    ]
    for p in patchers:
        p.start()

    # install IPython in the temp home:
    install(user=True)
test_handlers.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_format_descr_wo_notes(self):
        """
        Tests the _format_description method when the alert has no notes.
        """
        self.mock_settings['INCLUDE_FULL_DESCRIPTION'] = False
        with patch('ambassador.transport.Transport.get_key_cert',
                   return_value=self.mock_cert):
            with patch('platforms.jira.handlers.jira.JIRA',
                       return_value=self.mock_auth):
                with patch.dict('platforms.jira.handlers.settings.JIRA',
                                self.mock_settings):
                    handler_w_user = IssueAPI(endpoint=self.endpoint,
                                              user=self.user)
                    alert = Alert.objects.get(pk=2)
                    actual = handler_w_user._format_description(alert)
                    expected = ''
        self.assertEqual(actual, expected)
test_attachments.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_allowed_file(self):
        """
        Tests the get_file_path function for an allowed file type.
        """
        self.msg.attach(self.image)
        attachment = get_first_attachment(self.msg)
        mock_uuid = Mock()
        mock_uuid.hex = self.uuid
        with patch('sifter.mailsifter.attachments.uuid.uuid4',
                   return_value=mock_uuid):
            with patch.dict('sifter.mailsifter.attachments.settings.MAILSIFTER',
                            self.mock_mailsifter_settings):
                actual = attachments.get_file_path(attachment, self.company)
                expected = '%s/test-attachments/%s.jpeg' \
                           % (self.company.uuid.hex, self.uuid)
                self.assertEqual(actual, expected)
test_attachments.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_unallowed_file(self):
        """
        Tests the get_file_path function for an unallowed file type.
        """
        self.mock_mailsifter_settings['ALLOWED_EMAIL_ATTACHMENTS'] = ('application/java',)
        with patch.dict('sifter.mailsifter.accessors.settings.MAILSIFTER',
                        self.mock_mailsifter_settings):
            self.msg.attach(self.java)
            attachment = get_first_attachment(self.msg)
            with patch('sifter.mailsifter.attachments.settings',
                       return_value=self.mock_settings):
                with LogCapture() as log_capture:
                    actual = attachments.get_file_path(attachment)
                    expected = None
                    self.assertEqual(actual, expected)
                    msg = 'The attachment %s is not an allowed file type' \
                          % self.java_file
                    log_capture.check(
                        ('sifter.mailsifter.attachments', 'WARNING', msg),
                    )
test_attachments.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_no_file_path(self):
        """
        Tests the save_attachment function.
        """
        mock_settings_1 = {
            'ALLOWED_EMAIL_ATTACHMENTS': ('application/java',)
        }
        with patch.dict('sifter.mailsifter.accessors.settings.MAILSIFTER',
                        mock_settings_1):
            self.msg.attach(self.java)
            attachment = get_first_attachment(self.msg)
            with patch('sifter.mailsifter.attachments.settings',
                       self.mock_settings):
                with LogCapture() as log_capture:
                    actual = attachments.save_attachment(attachment)
                    expected = None
                    self.assertEqual(actual, expected)
                    msg = 'The attachment %s is not an allowed file type' \
                          % self.java_file
                    log_capture.check(
                        ('sifter.mailsifter.attachments', 'WARNING', msg),
                    )
test_models.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_match_with_default(self):
        """
        Tests the process_email receiver for an email that matches an
        existing MailChute.
        """
        doc_obj = self.doc_obj
        doc_obj.data['Subject'] = 'critical alert'
        mock_config = {
            'DEFAULT_MUNGER': 'default_mail',
            'DEFAULT_MUNGER_ENABLED': True
        }
        with patch('distilleries.models.Distillery.save_data',
                   return_value='id_123') as mock_save:
            with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER',
                            mock_config):
                with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') \
                        as mock_catch_email:
                    MailChute.objects.process(doc_obj)
                    self.assertIs(mock_save.called, True)
                    self.assertIs(mock_catch_email.called, False)
test_models.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_no_match_with_default(self):
        """
        Tests the process_email receiver for an email that doesn't match
        an existing MailChute when a default MailMunger is enabled.
        """
        doc_obj = self.doc_obj
        doc_obj.data['Subject'] = 'nothing to see here'
        mock_config = {
            'DEFAULT_MUNGER': 'default_mail',
            'DEFAULT_MUNGER_ENABLED': True
        }
        with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER',
                        mock_config):
            with patch('sifter.mailsifter.mailchutes.models.MailChuteManager._process_with_default') \
                    as mock_default_process:
                MailChute.objects.process(doc_obj)
                mock_default_process.assert_called_once_with(doc_obj)
test_models.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_no_match_missing_munger(self):
        """
        Tests the process_email receiver for an email that doesn't match
        an existing MailChute when a default MailChute is enabled but
        the defaul MailMunger can't be found.
        """
        doc_obj = self.doc_obj
        doc_obj.data['Subject'] = 'nothing to see here'
        mock_config = {
            'DEFAULT_MUNGER': 'missing_munger',
            'DEFAULT_MUNGER_ENABLED': True
        }
        with patch.dict('sifter.mailsifter.mailchutes.models.conf.MAILSIFTER',
                        mock_config):
            with LogCapture() as log_capture:
                msg = 'Default MailMunger "missing_munger" is not configured.'
                MailChute.objects.process(doc_obj)
                log_capture.check(
                    ('sifter.chutes.models', 'ERROR', msg),
                )
test_models.py 文件源码 项目:cyphon 作者: dunbarcyber 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_get_default_no_chute(self):
        """
        Tests the _default_munger function when the default LogMunger
        does not exist.
        """
        mock_config = {
            'DEFAULT_MUNGER': 'dummy_munger',
            'DEFAULT_MUNGER_ENABLED': True
        }
        with patch.dict('sifter.logsifter.logchutes.models.conf.LOGSIFTER',
                        mock_config):
            with LogCapture() as log_capture:
                actual = LogChute.objects._default_munger
                expected = None
                self.assertEqual(actual, expected)
                self.assertFalse(LogChute.objects._default_munger_enabled)
                log_capture.check(
                    ('sifter.chutes.models',
                     'ERROR',
                     'Default LogMunger "dummy_munger" is not configured.'),
                )
Snmp_test.py 文件源码 项目:nav 作者: UNINETT 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_raise_no_supported_snmp_backend_found_raised_if_no_snmp_libraries_are_available(
            self):
        modules = {
            'pynetsnmp': None,
        }

        with patch.dict(sys.modules, modules):
            self._patch_cleaning(sys.modules)
            pytest.raises(ImportError, 'import pynetsnmp')

            pytest.raises(ImportError, 'from nav.Snmp.pynetsnmp import *')

            try:
                from nav.Snmp import Snmp
                pytest.fail("Should never happen")
            except ImportError as foo:
                assert str(foo) == 'No supported SNMP backend was found'
plugin_test.py 文件源码 项目:nav 作者: UNINETT 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def setUp(self):
        self.plugin_a = Mock(
            name='snmptrapd plugin a')
        self.plugin_a.strip.return_value = 'nav.snmptrapd.handlers.foo'

        self.plugin_b = Mock(
            name='snmptrapd plguin b')
        self.plugin_b.strip.return_value = 'nav.snmptrapd.handlers.bar'
        del self.plugin_b.initialize

        def raise_exception():
            raise Exception('boom')

        self.bad_plugin = Mock(name='snmptrapd plugin which is bad')
        self.bad_plugin.strip.return_value = 'nav.snmptrapd.handlers.bad_plugin'
        self.bad_plugin.initialize=raise_exception

        self.patcher = patch.dict(sys.modules, {
            'nav.snmptrapd.handlers.foo': self.plugin_a,
            'nav.snmptrapd.handlers.bar': self.plugin_b,
            'nav.snmptrapd.handlers.bad_plugin': self.bad_plugin,
            'nav.snmptrapd.handlers.non_existent': None
        })
        self.patcher.start()
test_lambada.py 文件源码 项目:lambada 作者: Superpedestrian 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def test_bouncer_env(self):
        """
        Validate the environment variable loader works as expected.
        """
        # Test it doesn't leak
        with patch.dict('lambada.os.environ', dict(BLAH='asdf'), clear=True):
            config = lambada.get_config_from_env()
            self.assertFalse(config)

        # Test it works with default
        with patch.dict(
            'lambada.os.environ', dict(BOUNCER_BLAH='asdf'), clear=True
        ):
            config = lambada.get_config_from_env()
            self.assertDictEqual(config, dict(blah='asdf'))

        # Test that we can override the prefix
        with patch.dict(
            'lambada.os.environ',
            dict(STUFF_BLAH='asdf', STUFFS_BLAH='jkl;'),
            clear=True
        ):
            config = lambada.get_config_from_env('STUFF_')
            self.assertDictEqual(config, dict(blah='asdf'))
test_lambada.py 文件源码 项目:lambada 作者: Superpedestrian 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_dancer_class(self):
        """
        Verify the dancer class constructor, props, and call.
        """

        dancer = lambada.Dancer(self.sample_dancer, 'foo', 'bar', memory=128)
        # Confirm __init__
        self.assertEqual(dancer.name, 'foo')
        self.assertEqual(dancer.description, 'bar')
        self.assertDictEqual(dancer.override_config, dict(memory=128))
        # Validate config merge property
        self.assertDictEqual(
            dancer.config,
            dict(name='foo', description='bar', memory=128)
        )
        self.assertEqual((1, 2), dancer(1, 2))
test_tests_utils.py 文件源码 项目:niceman 作者: ReproNim 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_keeptemp_via_env_variable():

    if os.environ.get('NICEMAN_TESTS_KEEPTEMP'):
        raise SkipTest("We have env variable set to preserve tempfiles")

    files = []

    @with_tempfile()
    def check(f):
        open(f, 'w').write("LOAD")
        files.append(f)

    with patch.dict('os.environ', {}):
        check()

    with patch.dict('os.environ', {'NICEMAN_TESTS_KEEPTEMP': '1'}):
        check()

    eq_(len(files), 2)
    ok_(not exists(files[0]), msg="File %s still exists" % files[0])
    ok_(    exists(files[1]), msg="File %s not exists" % files[1])

    rmtemp(files[-1])
test_tests_utils.py 文件源码 项目:niceman 作者: ReproNim 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_skip_if_no_network():
    cleaned_env = os.environ.copy()
    cleaned_env.pop('NICEMAN_TESTS_NONETWORK', None)
    # we need to run under cleaned env to make sure we actually test in both conditions
    with patch('os.environ', cleaned_env):
        @skip_if_no_network
        def somefunc(a1):
            return a1
        eq_(somefunc.tags, ['network'])
        with patch.dict('os.environ', {'NICEMAN_TESTS_NONETWORK': '1'}):
            assert_raises(SkipTest, somefunc, 1)
        with patch.dict('os.environ', {}):
            eq_(somefunc(1), 1)
        # and now if used as a function, not a decorator
        with patch.dict('os.environ', {'NICEMAN_TESTS_NONETWORK': '1'}):
            assert_raises(SkipTest, skip_if_no_network)
        with patch.dict('os.environ', {}):
            eq_(skip_if_no_network(), None)
test_settings.py 文件源码 项目:windflow 作者: hartym 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def test_load_settings_from_env(tmpdir):
    with patch.dict('os.environ', {}) as e:
        load_settings_from_env(str(tmpdir))
        assert os.environ.get('FOO', None) is None

    p = tmpdir.join(".env")
    p.write("FOO = bar")

    with patch.dict('os.environ', {}) as e:
        load_settings_from_env(str(tmpdir))
        assert os.environ.get('FOO', None) == 'bar'
test_util.py 文件源码 项目:FRG-Crowdsourcing 作者: 97amarnathk 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def test_handle_content_type_json(self, mocklast, mockjsonify,
                                      mockrender, mockrequest):
        fake_d = {'Content-Type': 'application/json'}
        mockrequest.headers.__getitem__.side_effect = fake_d.__getitem__
        mockrequest.headers.get.side_effect = fake_d.get
        mockrequest.headers.__iter__.side_effect = fake_d.__iter__
        mockjsonify.side_effect = myjsonify
        res = util.handle_content_type(dict(template='example.html'))
        err_msg = "template key should exist"
        assert res.get('template') == 'example.html', err_msg
        err_msg = "jsonify should be called"
        assert mockjsonify.called, err_msg


问题


面经


文章

微信
公众号

扫码关注公众号