• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mock.patch函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中tests.compat.mock.patch函数的典型用法代码示例。如果您正苦于以下问题:Python patch函数的具体用法?Python patch怎么用?Python patch使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了patch函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_list_under_parent

 def test_list_under_parent(self):
     """Establish that listing with a parent specified works."""
     with mock.patch(
             'tower_cli.models.base.ResourceMethods.list') as mock_list:
         with mock.patch(
                 'tower_cli.resources.group.Resource.lookup_with_inventory'
                 ):
             self.gr.list(parent="foo_group")
             mock_list.assert_called_once_with()
开发者ID:AlanCoding,项目名称:tower-cli,代码行数:9,代码来源:test_resources_group.py


示例2: test_post_save_hook_was_connected

    def test_post_save_hook_was_connected(self):
        with mock.patch('django.db.models.signals.post_save') as mocked_post_save, \
                mock.patch('django.db.models.signals.pre_delete'):
            caching_framework.register(TestModel)

            mocked_post_save.connect.assert_called_once_with(mock.ANY,
                                                             sender=TestModel,
                                                             weak=False,
                                                             dispatch_uid='%s_cache_object' % TestModel._meta.db_table)
开发者ID:thedrow,项目名称:django-caching-framework,代码行数:9,代码来源:test_register.py


示例3: test_associate

 def test_associate(self):
     """Establish that associate commands work."""
     with mock.patch(
             'tower_cli.models.base.ResourceMethods._assoc') as mock_assoc:
         with mock.patch(
                 'tower_cli.resources.group.Resource.lookup_with_inventory'
                 ) as mock_lookup:
             mock_lookup.return_value = {'id': 1}
             self.gr.associate(group=1, parent=2)
             mock_assoc.assert_called_once_with('children', 1, 1)
开发者ID:AlanCoding,项目名称:tower-cli,代码行数:10,代码来源:test_resources_group.py


示例4: test_reading_invalid_token_from_server

 def test_reading_invalid_token_from_server(self):
     self.expires += timedelta(hours=-1)
     expires = self.expires.strftime(TOWER_DATETIME_FMT)
     with mock.patch('six.moves.builtins.open', new_callable=mock.mock_open()):
         with mock.patch('tower_cli.api.json.load', return_value={'token': 'foobar', 'expires': expires}):
             with client.test_mode as t:
                 with self.assertRaises(exc.AuthError):
                     t.register('/authtoken/', json.dumps({}), status_code=200, method='OPTIONS')
                     t.register('/authtoken/', json.dumps({'invalid': 'invalid'}), status_code=200, method='POST')
                     self.auth(self.req)
开发者ID:ansible,项目名称:tower-cli,代码行数:10,代码来源:test_api.py


示例5: test_role_write_user_exists_FOF

 def test_role_write_user_exists_FOF(self):
     """Simulate granting user permission where they already have it."""
     with mock.patch(
             'tower_cli.models.base.ResourceMethods.read') as mock_read:
         mock_read.return_value = {'results': [copy(example_role_data)],
                                   'count': 1}
         with mock.patch('tower_cli.api.Client.post'):
             with self.assertRaises(exc.NotFound):
                 self.res.role_write(user=2, inventory=3, type='admin',
                                     fail_on_found=True)
开发者ID:cchurch,项目名称:tower-cli,代码行数:10,代码来源:test_resources_role.py


示例6: test_role_grant_user

 def test_role_grant_user(self):
     """Simulate granting user permission."""
     with mock.patch(
             'tower_cli.models.base.ResourceMethods.read') as mock_read:
         mock_read.return_value = {
             'results': [copy(example_role_data)], 'count': 0}
         with mock.patch('tower_cli.api.Client.post') as mock_post:
             self.res.role_write(user=2, inventory=3, type='admin')
             mock_post.assert_called_once_with(
                 'users/2/roles/', data={'id': 1})
开发者ID:cchurch,项目名称:tower-cli,代码行数:10,代码来源:test_resources_role.py


示例7: test_reading_invalid_token

 def test_reading_invalid_token(self):
     self.expires += timedelta(hours=1)
     expires = self.expires.strftime(TOWER_DATETIME_FMT)
     with mock.patch('six.moves.builtins.open', new_callable=mock.mock_open()):
         with mock.patch('tower_cli.api.json.load', return_value="invalid"):
             with client.test_mode as t:
                 t.register('/authtoken/', json.dumps({}), status_code=200, method='OPTIONS')
                 t.register('/authtoken/', json.dumps({'token': 'barfoo', 'expires': expires}), status_code=200,
                            method='POST')
                 self.auth(self.req)
                 self.assertEqual(self.req.headers['Authorization'], 'Token barfoo')
开发者ID:ansible,项目名称:tower-cli,代码行数:11,代码来源:test_api.py


示例8: setUp

 def setUp(self):
     super(MockServiceWithConfigTestCase, self).setUp()
     self.environ = {}
     self.config = {}
     self.config_patch = mock.patch('boto.provider.config.get',
                                    self.get_config)
     self.has_config_patch = mock.patch('boto.provider.config.has_option',
                                        self.has_config)
     self.environ_patch = mock.patch('os.environ', self.environ)
     self.config_patch.start()
     self.has_config_patch.start()
     self.environ_patch.start()
开发者ID:17patelumang,项目名称:boto,代码行数:12,代码来源:__init__.py


示例9: test_concurrent_upload_file

 def test_concurrent_upload_file(self):
     v = vault.Vault(None, None)
     with mock.patch("boto.glacier.vault.ConcurrentUploader") as c:
         c.return_value.upload.return_value = "archive_id"
         archive_id = v.concurrent_create_archive_from_file("filename", "my description")
         c.return_value.upload.assert_called_with("filename", "my description")
     self.assertEqual(archive_id, "archive_id")
开发者ID:MrWoodward,项目名称:boto,代码行数:7,代码来源:test_vault.py


示例10: test_create_without_special_fields

 def test_create_without_special_fields(self):
     """Establish that a create without user, team, or credential works"""
     with mock.patch(
             'tower_cli.models.base.Resource.create') as mock_create:
         cred_res = tower_cli.get_resource('credential')
         cred_res.create(name="foobar")
         mock_create.assert_called_once_with(name="foobar")
开发者ID:ghjm,项目名称:tower-cli,代码行数:7,代码来源:test_resources_credential.py


示例11: setUp

    def setUp(self, _orig_class=orig_class):
        _orig_class.setUp(self)

        def find_near_matches_dropin(subsequence, sequence, *args, **kwargs):
            if isinstance(sequence, (tuple, list)):
                self.skipTest('skipping word-list tests with find_near_matches_in_file')
            try:
                from Bio.Seq import Seq
            except ImportError:
                pass
            else:
                if isinstance(sequence, Seq):
                    self.skipTest('skipping BioPython Seq tests with find_near_matches_in_file')

            tempfilepath = tempfile.mktemp()
            if isinstance(sequence, text_type):
                f = io.open(tempfilepath, 'w+', encoding='utf-8')
            else:
                f = open(tempfilepath, 'w+b')
            try:
                f.write(sequence)
                f.seek(0)
                return find_near_matches_in_file(subsequence, f, *args, **kwargs)
            finally:
                f.close()
                os.remove(tempfilepath)

        patcher = mock.patch(
            'tests.test_find_near_matches.find_near_matches',
            find_near_matches_dropin)
        self.addCleanup(patcher.stop)
        patcher.start()
开发者ID:taleinat,项目名称:fuzzysearch,代码行数:32,代码来源:test_find_near_matches_in_file.py


示例12: test_grant_user_role

 def test_grant_user_role(self):
     """Assure that super method is called granting role"""
     with mock.patch(
             'tower_cli.resources.role.Resource.role_write') as mock_write:
         kwargs = dict(user=1, type='read', project=3)
         self.res.grant(**kwargs)
         mock_write.assert_called_once_with(fail_on_found=False, **kwargs)
开发者ID:cchurch,项目名称:tower-cli,代码行数:7,代码来源:test_resources_role.py


示例13: test_list_user

 def test_list_user(self):
     """Assure that super method is called with right parameters"""
     with mock.patch(
             'tower_cli.models.base.ResourceMethods.list') as mock_list:
         mock_list.return_value = {'results': [example_role_data]}
         self.res.list(user=1)
         mock_list.assert_called_once_with(members__in=1)
开发者ID:cchurch,项目名称:tower-cli,代码行数:7,代码来源:test_resources_role.py


示例14: test_write_global_setting

    def test_write_global_setting(self):
        """Establish that if we attempt to write a valid setting, that
        the parser's write method is run.
        """
        # Invoke the command, but trap the file-write at the end
        # so we don't plow over real things.
        mock_open = mock.mock_open()
        with mock.patch('tower_cli.commands.config.open', mock_open,
                        create=True):
            with mock.patch.object(os.path, 'isdir') as isdir:
                isdir.return_value = True
                result = self.runner.invoke(config,
                    ['username', 'luke', '--scope=global'],
                )
                isdir.assert_called_once_with('/etc/awx/')

        # Ensure that the command completed successfully.
        self.assertEqual(result.exit_code, 0)
        self.assertEqual(result.output.strip(),
                         'Configuration updated successfully.')

        # Ensure that the output seems to be correct.
        self.assertIn(mock.call('/etc/awx/tower_cli.cfg', 'w'),
                      mock_open.mock_calls)
        self.assertIn(mock.call().write('username = luke\n'),
                      mock_open.mock_calls)
开发者ID:Robinjtu,项目名称:tower-cli,代码行数:26,代码来源:test_commands_config.py


示例15: setUp

 def setUp(self):
     with mock.patch(
         GCS_STRING.format('GoogleCloudBaseHook.__init__'),
         new=mock_base_gcp_hook_default_project_id,
     ):
         self.gcs_hook = gcs_hook.GoogleCloudStorageHook(
             google_cloud_storage_conn_id='test')
开发者ID:astronomerio,项目名称:incubator-airflow,代码行数:7,代码来源:test_gcs_hook.py


示例16: test_router_urls_with_custom_lookup_field

    def test_router_urls_with_custom_lookup_field(self):
        """Establish that a router with a viewset attached gets
        expected URLs.
        """
        # Create a model and viewset with a special lookup field.
        class PhonyModelIII(models.Model):
            class Meta:
                app_label = 'tests'

        class PhonyViewSetIII(viewsets.ModelViewSet):
            model = PhonyModelIII
            lookup_field = 'foo'

            @base_action(set(['POST']))
            def special(self, request):
                pass

        # Create the router and register our viewset.
        with mock.patch('drf_toolbox.routers.ModelSerializer'):
            router = routers.Router()
        router.register('phony', PhonyViewSetIII)

        # Attempt to establish that we got back what we expected.
        for urlpattern in router.urls:
            pattern = urlpattern.regex.pattern
            base_regex = routers.base_regex
            if '<foo>' in pattern:
                self.assertIn('(?P<foo>%s)' % base_regex.pattern, pattern)
            if '<format>' in urlpattern.regex.pattern:
                self.assertFalse(pattern.endswith(r'/\.(?P<format>[a-z]+)$'))
开发者ID:gregwym,项目名称:drf-toolbox,代码行数:30,代码来源:test_routers.py


示例17: test_router_urls_uuid

    def test_router_urls_uuid(self):
        """Establish that a router with a viewset attached gets the
        expected URLs.
        """
        # Create a model and viewset with at least one special method.
        class PhonyModelII(models.Model):
            id = models.UUIDField(auto_add=True, primary_key=True)
            class Meta:
                app_label = 'tests'

        class PhonyViewSetII(viewsets.ModelViewSet):
            model = PhonyModelII

            @base_action(set(['POST']))
            def special(self, request):
                pass

        # Create the router and register our viewset.
        with mock.patch('drf_toolbox.routers.ModelSerializer'):
            router = routers.Router()
        router.register('phony', PhonyViewSetII)

        # Attempt to establish that we got back what we expected.
        for urlpattern in router.urls:
            pattern = urlpattern.regex.pattern
            uuid_regex = routers.uuid_regex
            if '<pk>' in pattern:
                self.assertIn('(?P<pk>%s)' % uuid_regex.pattern, pattern)
            if '<format>' in urlpattern.regex.pattern:
                self.assertFalse(pattern.endswith(r'/\.(?P<format>[a-z]+)$'))
开发者ID:gregwym,项目名称:drf-toolbox,代码行数:30,代码来源:test_routers.py


示例18: test_router_urls_using_serializer_class_only

    def test_router_urls_using_serializer_class_only(self):
        """Establish that a router with a viewset attached gets the
        expected URLs, even if the viewset uses a serializer class instead
        of a model.

        See #2: https://github.com/feedmagnet/drf-toolbox/issues/2
        """
        # Create a model, serializer class, and viewset.
        # The viewset should reference the serializer class only.
        class PhonyModelV(models.Model):
            class Meta:
                app_label = 'tests'

        class PhonySerializerV(serializers.ModelSerializer):
            class Meta:
                model = PhonyModelV

        class PhonyViewSetV(viewsets.ModelViewSet):
            serializer_class = PhonySerializerV

        # Create the router and register our viewset.
        with mock.patch('drf_toolbox.routers.ModelSerializer'):
            router = routers.Router()
        router.register('phony', PhonyViewSetV)

        # Attempt to establish that we got back what we expected.
        for urlpattern in router.urls:
            pattern = urlpattern.regex.pattern
            integer_regex = routers.integer_regex
            if '<pk>' in pattern:
                self.assertIn('(?P<pk>%s)' % integer_regex.pattern, pattern)
            if '<format>' in urlpattern.regex.pattern:
                self.assertFalse(pattern.endswith(r'/\.(?P<format>[a-z]+)$'))
开发者ID:gregwym,项目名称:drf-toolbox,代码行数:33,代码来源:test_routers.py


示例19: test_get_job_validate_checksum_success

 def test_get_job_validate_checksum_success(self):
     response = GlacierResponse(mock.Mock(), None)
     response['TreeHash'] = 'tree_hash'
     self.api.get_job_output.return_value = response
     with mock.patch('boto.glacier.job.tree_hash_from_str') as t:
         t.return_value = 'tree_hash'
         self.job.get_output(byte_range=(1, 1024), validate_checksum=True)
开发者ID:10sr,项目名称:hue,代码行数:7,代码来源:test_job.py


示例20: test_keyring_is_used

    def test_keyring_is_used(self):
        self.config = {
            'Credentials': {
                'aws_access_key_id': 'cfg_access_key',
                'keyring': 'test',
            }
        }
        import sys
        try:
            import keyring
            imported = True
        except ImportError:
            sys.modules['keyring'] = keyring = type(mock)('keyring', '')
            imported = False

        try:
            with mock.patch('keyring.get_password', create=True):
                keyring.get_password.side_effect = (
                    lambda kr, login: kr+login+'pw')
                p = provider.Provider('aws')
                self.assertEqual(p.access_key, 'cfg_access_key')
                self.assertEqual(p.secret_key, 'testcfg_access_keypw')
                self.assertIsNone(p.security_token)
        finally:
            if not imported:
                del sys.modules['keyring']
开发者ID:7heo,项目名称:boto,代码行数:26,代码来源:test_provider.py



注:本文中的tests.compat.mock.patch函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python unittest.main函数代码示例发布时间:2022-05-27
下一篇:
Python compat.u函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap