当前位置: 首页>>代码示例>>Python>>正文


Python mock.patch函数代码示例

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


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


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