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


Python mock.patch函数代码示例

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


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

示例1: test_certificate_asset_by_slug

    def test_certificate_asset_by_slug(self):
        """
        Tests certificate template asset display by slug using static.certificate_asset_url method.
        """
        self._add_course_certificates(count=1, signatory_count=2)
        self._create_custom_template(mode='honor')
        test_url = get_certificate_url(
            user_id=self.user.id,
            course_id=unicode(self.course.id)
        )

        # render certificate without template asset
        with patch('certificates.api.get_course_organizations') as mock_get_orgs:
            mock_get_orgs.return_value = []
            response = self.client.get(test_url)
            self.assertContains(response, '<img class="custom-logo" src="" />')

        template_asset = CertificateTemplateAsset(
            description='custom logo',
            asset='certificate_template_assets/32/test_logo.png',
            asset_slug='custom-logo',
        )
        template_asset.save()

        # render certificate with template asset
        with patch('certificates.api.get_course_organizations') as mock_get_orgs:
            mock_get_orgs.return_value = []
            response = self.client.get(test_url)
            self.assertContains(
                response, '<img class="custom-logo" src="{}certificate_template_assets/32/test_logo.png" />'.format(
                    settings.MEDIA_URL
                )
            )
开发者ID:lemontreeran,项目名称:edx-platform,代码行数:33,代码来源:test_webview_views.py

示例2: test_net_connect_to_nat

 def test_net_connect_to_nat(self):
     # use external
     fake_client, fake_ctx = self.generate_client_and_context_network()
     fake_ctx._target.node.properties = {
         'use_external_resource': True
     }
     with mock.patch(
         'vcloud_plugin_common.VcloudAirClient.get',
         mock.MagicMock(return_value=fake_client)
     ):
         public_nat.net_connect_to_nat(ctx=fake_ctx)
     # no external
     fake_client, fake_ctx = self.generate_client_and_context_network()
     fake_ctx._target.node.properties = {
         'nat': {
             'edge_gateway': 'gateway'
         },
         'rules': [{
             'type': 'DNAT'
         }]
     }
     fake_client._vdc_gateway.get_public_ips = mock.MagicMock(return_value=[
         '10.18.1.1'
     ])
     with mock.patch(
         'vcloud_plugin_common.VcloudAirClient.get',
         mock.MagicMock(return_value=fake_client)
     ):
         public_nat.net_connect_to_nat(ctx=fake_ctx)
     fake_client._vdc_gateway.add_nat_rule.assert_called_with(
         'DNAT', '10.18.1.1', 'any', '127.1.1.100 - 127.1.1.200',
         'any', 'any'
     )
开发者ID:nmishkin,项目名称:tosca-vcloud-plugin,代码行数:33,代码来源:test_mock_network_plugin_public_nat.py

示例3: get_filesystem_encoding_test

    def get_filesystem_encoding_test(self):
        """
        Test the get_filesystem_encoding() function
        """
        with patch('openlp.core.utils.sys.getfilesystemencoding') as mocked_getfilesystemencoding, \
             patch('openlp.core.utils.sys.getdefaultencoding') as mocked_getdefaultencoding:
            # GIVEN: sys.getfilesystemencoding returns "cp1252"
            mocked_getfilesystemencoding.return_value = 'cp1252'

            # WHEN: get_filesystem_encoding() is called
            result = get_filesystem_encoding()

            # THEN: getdefaultencoding should have been called
            mocked_getfilesystemencoding.assert_called_with()
            assert not mocked_getdefaultencoding.called
            assert result == 'cp1252', 'The result should be "cp1252"'

            # GIVEN: sys.getfilesystemencoding returns None and sys.getdefaultencoding returns "utf-8"
            mocked_getfilesystemencoding.return_value = None
            mocked_getdefaultencoding.return_value = 'utf-8'

            # WHEN: get_filesystem_encoding() is called
            result = get_filesystem_encoding()

            # THEN: getdefaultencoding should have been called
            mocked_getfilesystemencoding.assert_called_with()
            mocked_getdefaultencoding.assert_called_with()
            assert result == 'utf-8', 'The result should be "utf-8"'
开发者ID:marmyshev,项目名称:bug_1117098,代码行数:28,代码来源:test_utils.py

示例4: test_get_taking_too_long

    def test_get_taking_too_long(self):
        the_time = [time.time()]

        def mock_time():
            return the_time[0]

        # this is just a convenient place to hang a time jump
        def mock_is_success(status_int):
            the_time[0] += 9 * 3600
            return status_int // 100 == 2

        req = swob.Request.blank(
            '/v1/AUTH_test/mancon/manifest',
            environ={'REQUEST_METHOD': 'GET'})

        with contextlib.nested(
                mock.patch('swift.common.utils.time.time', mock_time),
                mock.patch('swift.common.utils.is_success', mock_is_success),
                mock.patch.object(dlo, 'is_success', mock_is_success)):
            status, headers, body, exc = self.call_dlo(
                req, expect_exception=True)

        self.assertEqual(status, '200 OK')
        self.assertEqual(body, 'aaaaabbbbbccccc')
        self.assertTrue(isinstance(exc, exceptions.SegmentError))
开发者ID:charint,项目名称:swift,代码行数:25,代码来源:test_dlo.py

示例5: test_increase_quota

  def test_increase_quota(self):
    """Tests successful execution of the increase_quota command."""
    mock_options = self.setup_mock_options()
    with contextlib.nested(
        patch('twitter.common.app.get_options', return_value=mock_options),
        patch('apache.aurora.admin.admin.make_admin_client',
            return_value=create_autospec(spec=AuroraClientAPI)),
        patch('apache.aurora.admin.admin.CLUSTERS', new=self.TEST_CLUSTERS)
    ) as (_, mock_make_admin_client, _):

      api = mock_make_admin_client.return_value
      role = 'test_role'
      api.get_quota.return_value = self.create_response(
          ResourceAggregate(20.0, 4000, 6000),
          ResourceAggregate(15.0, 2000, 3000),
          ResourceAggregate(6.0, 200, 600),
      )
      api.set_quota.return_value = self.create_simple_success_response()

      increase_quota([self.TEST_CLUSTER, role, '4.0', '1MB', '1MB'])

      api.set_quota.assert_called_with(role, 24.0, 4001, 6001)
      assert type(api.set_quota.call_args[0][1]) == type(float())
      assert type(api.set_quota.call_args[0][2]) == type(int())
      assert type(api.set_quota.call_args[0][3]) == type(int())
开发者ID:smarth-madan,项目名称:incubator-aurora,代码行数:25,代码来源:test_admin.py

示例6: run_main

def run_main(args, exit_code=0, expect_stderr=False):
    """Run main() of the datalad, do basic checks and provide outputs

    Parameters
    ----------
    args : list
        List of string cmdline arguments to pass
    exit_code : int
        Expected exit code. Would raise AssertionError if differs
    expect_stderr : bool or string
        Whether to expect stderr output. If string -- match

    Returns
    -------
    stdout, stderr  strings
       Output produced
    """
    with patch('sys.stderr', new_callable=StringIO) as cmerr:
        with patch('sys.stdout', new_callable=StringIO) as cmout:
            with assert_raises(SystemExit) as cm:
                main(["datalad"] + list(args))
            assert_equal(cm.exception.code, exit_code)
            stdout = cmout.getvalue()
            stderr = cmerr.getvalue()
            if expect_stderr is False:
                assert_equal(stderr, "")
            elif expect_stderr is True:
                # do nothing -- just return
                pass
            else:
                # must be a string
                assert_equal(stderr, expect_stderr)
    return stdout, stderr
开发者ID:datalad,项目名称:datalad,代码行数:33,代码来源:test_main.py

示例7: test_run_once

    def test_run_once(self):
        def prepare_data_dir():
            devices_path = tempfile.mkdtemp()
            # will be deleted by teardown
            self.to_delete.append(devices_path)
            path = os.path.join(devices_path, 'sda1', DATADIR)
            os.makedirs(path)
            return devices_path

        def init_reaper(devices):
            r = reaper.AccountReaper({'devices': devices})
            return r

        devices = prepare_data_dir()
        r = init_reaper(devices)

        with patch('swift.account.reaper.ismount', lambda x: True):
            with patch(
                    'swift.account.reaper.AccountReaper.reap_device') as foo:
                r.run_once()
        self.assertEqual(foo.called, 1)

        with patch('swift.account.reaper.ismount', lambda x: False):
            with patch(
                    'swift.account.reaper.AccountReaper.reap_device') as foo:
                r.run_once()
        self.assertFalse(foo.called)
开发者ID:LSBDOpenstackDev,项目名称:swift,代码行数:27,代码来源:test_reaper.py

示例8: test_finalize_uploaded_assignment

    def test_finalize_uploaded_assignment(
            self, finalized_setting, model_change_expected, upload_allowed, get_student_item_dict
    ):
        """
        Tests that finalize_uploaded_assignment sets a submission to be finalized
        """
        block = self.make_xblock()
        get_student_item_dict.return_value = {
            "student_id": 1,
            "course_id": block.block_course_id,
            "item_id": block.block_id,
            "item_type": 'sga',
        }
        upload_allowed.return_value = True
        existing_submitted_at_value = django_now()
        fake_submission_data = fake_get_submission(**finalized_setting)
        fake_submission_object = mock.Mock(
            submitted_at=existing_submitted_at_value,
            answer=fake_submission_data['answer']
        )

        with mock.patch(
            'edx_sga.sga.Submission.objects.get', return_value=fake_submission_object
        ), mock.patch(
            'edx_sga.sga.StaffGradedAssignmentXBlock.get_submission', return_value=fake_submission_data
        ), mock.patch(
            'edx_sga.sga.StaffGradedAssignmentXBlock.student_state', return_value={}
        ):
            block.finalize_uploaded_assignment(mock.Mock())

        assert fake_submission_object.answer['finalized'] is True
        assert (existing_submitted_at_value != fake_submission_object.submitted_at) is model_change_expected
        assert fake_submission_object.save.called is model_change_expected
开发者ID:doctoryes,项目名称:edx-sga,代码行数:33,代码来源:test_sga.py

示例9: test_populate_policy_profile_delete

 def test_populate_policy_profile_delete(self):
     # Patch the Client class with the TestClient class
     with mock.patch(n1kv_client.__name__ + ".Client",
                     new=fake_client.TestClient):
         # Patch the _get_total_profiles() method to return a custom value
         with mock.patch(fake_client.__name__ +
                         '.TestClient._get_total_profiles') as obj_inst:
             # Return 3 policy profiles
             obj_inst.return_value = 3
             plugin = manager.NeutronManager.get_plugin()
             plugin._populate_policy_profiles()
             db_session = db.get_session()
             profile = n1kv_db_v2.get_policy_profile(
                 db_session, '00000000-0000-0000-0000-000000000001')
             # Verify that DB contains only 3 policy profiles
             self.assertEqual('pp-1', profile['name'])
             profile = n1kv_db_v2.get_policy_profile(
                 db_session, '00000000-0000-0000-0000-000000000002')
             self.assertEqual('pp-2', profile['name'])
             profile = n1kv_db_v2.get_policy_profile(
                 db_session, '00000000-0000-0000-0000-000000000003')
             self.assertEqual('pp-3', profile['name'])
             self.assertRaises(c_exc.PolicyProfileIdNotFound,
                               n1kv_db_v2.get_policy_profile,
                               db_session,
                               '00000000-0000-0000-0000-000000000004')
             # Return 2 policy profiles
             obj_inst.return_value = 2
             plugin._populate_policy_profiles()
             # Verify that the third policy profile is deleted
             self.assertRaises(c_exc.PolicyProfileIdNotFound,
                               n1kv_db_v2.get_policy_profile,
                               db_session,
                               '00000000-0000-0000-0000-000000000003')
开发者ID:aignatov,项目名称:neutron,代码行数:34,代码来源:test_n1kv_plugin.py

示例10: test_reap_object

 def test_reap_object(self):
     conf = {
         'mount_check': 'false',
     }
     r = reaper.AccountReaper(conf, logger=unit.debug_logger())
     mock_path = 'swift.account.reaper.direct_delete_object'
     for policy in POLICIES:
         r.reset_stats()
         with patch(mock_path) as fake_direct_delete:
             with patch('swift.account.reaper.time') as mock_time:
                 mock_time.return_value = 1429117638.86767
                 r.reap_object('a', 'c', 'partition', cont_nodes, 'o',
                               policy.idx)
                 mock_time.assert_called_once_with()
                 for i, call_args in enumerate(
                         fake_direct_delete.call_args_list):
                     cnode = cont_nodes[i % len(cont_nodes)]
                     host = '%(ip)s:%(port)s' % cnode
                     device = cnode['device']
                     headers = {
                         'X-Container-Host': host,
                         'X-Container-Partition': 'partition',
                         'X-Container-Device': device,
                         'X-Backend-Storage-Policy-Index': policy.idx,
                         'X-Timestamp': '1429117638.86767'
                     }
                     ring = r.get_object_ring(policy.idx)
                     expected = call(dict(ring.devs[i], index=i), 0,
                                     'a', 'c', 'o',
                                     headers=headers, conn_timeout=0.5,
                                     response_timeout=10)
                     self.assertEqual(call_args, expected)
                 self.assertEqual(policy.object_ring.replicas - 1, i)
         self.assertEqual(r.stats_objects_deleted,
                          policy.object_ring.replicas)
开发者ID:LSBDOpenstackDev,项目名称:swift,代码行数:35,代码来源:test_reaper.py

示例11: test_invalid_certificate_path

 def test_invalid_certificate_path(self):
     mock_file_path = "/path/to/cert.pem"
     with patch("django_auth_adfs.backend.AdfsBackend._public_keys", []):
         with patch("django_auth_adfs.backend.settings.SIGNING_CERT", mock_file_path):
             with patch("django_auth_adfs.backend.isfile") as mock_isfile:
                 mock_isfile.return_value = False
                 self.assertRaises(ImproperlyConfigured, AdfsBackend)
开发者ID:jobec,项目名称:django-auth-adfs,代码行数:7,代码来源:test_configuration.py

示例12: setUp

    def setUp(self):
        super(TestSdnveNeutronAgent, self).setUp()
        notifier_p = mock.patch(NOTIFIER)
        notifier_cls = notifier_p.start()
        self.notifier = mock.Mock()
        notifier_cls.return_value = self.notifier
        cfg.CONF.set_override('integration_bridge',
                              'br_int', group='SDNVE')
        kwargs = sdnve_neutron_agent.create_agent_config_map(cfg.CONF)

        class MockFixedIntervalLoopingCall(object):
            def __init__(self, f):
                self.f = f

            def start(self, interval=0):
                self.f()

        with contextlib.nested(
            mock.patch('neutron.plugins.ibm.agent.sdnve_neutron_agent.'
                       'SdnveNeutronAgent.setup_integration_br',
                       return_value=mock.Mock()),
            mock.patch('neutron.openstack.common.loopingcall.'
                       'FixedIntervalLoopingCall',
                       new=MockFixedIntervalLoopingCall)):
            self.agent = sdnve_neutron_agent.SdnveNeutronAgent(**kwargs)
开发者ID:Akanksha08,项目名称:neutron,代码行数:25,代码来源:test_sdnve_agent.py

示例13: MockEventNotification

def MockEventNotification( response_method, native_filetype_completer = True ):
  """Mock out the EventNotification client request object, replacing the
  Response handler's JsonFromFuture with the supplied |response_method|.
  Additionally mock out YouCompleteMe's FiletypeCompleterExistsForFiletype
  method to return the supplied |native_filetype_completer| parameter, rather
  than querying the server"""

  # We don't want the event to actually be sent to the server, just have it
  # return success
  with patch( 'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync',
              return_value = MagicMock( return_value=True ) ):

    # We set up a fake a Response (as called by EventNotification.Response)
    # which calls the supplied callback method. Generally this callback just
    # raises an apropriate exception, otherwise it would have to return a mock
    # future object.
    #
    # Note: JsonFromFuture is actually part of ycm.client.base_request, but we
    # must patch where an object is looked up, not where it is defined.
    # See https://docs.python.org/dev/library/unittest.mock.html#where-to-patch
    # for details.
    with patch( 'ycm.client.event_notification.JsonFromFuture',
                side_effect = response_method ):

      # Filetype available information comes from the server, so rather than
      # relying on that request, we mock out the check. The caller decides if
      # filetype completion is available
      with patch(
        'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype',
        return_value = native_filetype_completer ):

        yield
开发者ID:DavidUser,项目名称:YouCompleteMe,代码行数:32,代码来源:event_notification_test.py

示例14: test_description_is_optional

    def test_description_is_optional(self, mock_heat_client):
        """Assert that if heat_template_version is omitted, it's added"""
        # Note that the 'with x as y, a as b:' syntax was introduced in
        # python 2.7, and contextlib.nested was deprecated in py2.7
        with mock.patch(MOD_NAME + '.HeatStack._get_status') as status_get:
            with mock.patch(MOD_NAME + '.HeatStack._wait_state') as wait_st:

                status_get.return_value = 'NOT_FOUND'
                wait_st.return_value = {}

                hs = heat_stack.HeatStack(self.mock_murano_obj,
                                          None, None, None)
                hs._heat_client = mock_heat_client
                hs._name = 'test-stack'
                hs._description = None
                hs._template = {'resources': {'test': 1}}
                hs._parameters = {}
                hs._applied = False
                hs.push()

                expected_template = {
                    'heat_template_version': '2013-05-23',
                    'resources': {'test': 1}
                }
                mock_heat_client.stacks.create.assert_called_with(
                    stack_name='test-stack',
                    disable_rollback=False,
                    parameters={},
                    template=expected_template
                )
                self.assertTrue(hs._applied)
开发者ID:ativelkov,项目名称:murano-api,代码行数:31,代码来源:test_heat_stack.py

示例15: test_staff_upload_download_annotated

    def test_staff_upload_download_annotated(self, get_sha1, is_course_staff, get_student_module):
        # pylint: disable=no-member
        """
        Tests upload and download of annotated staff files.
        """
        get_student_module.return_value = fake_student_module()
        is_course_staff.return_value = True
        get_sha1.return_value = SHA1
        file_name = 'test.txt'
        block = self.make_xblock()

        with self.dummy_upload(file_name) as (upload, expected), mock.patch(
            "edx_sga.sga.StaffGradedAssignmentXBlock.staff_grading_data",
            return_value={}
        ) as staff_grading_data:
            block.staff_upload_annotated(mock.Mock(params={'annotated': upload, 'module_id': 1}))
        assert staff_grading_data.called is True

        with mock.patch(
            "edx_sga.sga.StaffGradedAssignmentXBlock.file_storage_path",
            return_value=block.file_storage_path(SHA1, file_name)
        ):
            response = block.staff_download_annotated(mock.Mock(params={'module_id': 1}))
            assert response.body == expected

        with mock.patch(
            "edx_sga.sga.StaffGradedAssignmentXBlock.file_storage_path",
            return_value=block.file_storage_path("", "test_notfound.txt")
        ):
            response = block.staff_download_annotated(
                mock.Mock(params={'module_id': 1})
            )
            assert response.status_code == 404
开发者ID:doctoryes,项目名称:edx-sga,代码行数:33,代码来源:test_sga.py


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