當前位置: 首頁>>代碼示例>>Python>>正文


Python mock.patch方法代碼示例

本文整理匯總了Python中unittest.mock.patch方法的典型用法代碼示例。如果您正苦於以下問題:Python mock.patch方法的具體用法?Python mock.patch怎麽用?Python mock.patch使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在unittest.mock的用法示例。


在下文中一共展示了mock.patch方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_mod_with_wrong_field_type_in_trans

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_mod_with_wrong_field_type_in_trans(self):
        msgid = "Correct type %(arg1)s"
        params = {'arg1': 'test1'}
        with mock.patch('gettext.translation') as trans:
            # Set up ugettext to return the original message with the
            # correct format string.
            trans.return_value.ugettext.return_value = msgid
            # Build a message and give it some parameters.
            result = _message.Message(msgid) % params
            # Now set up ugettext to return the translated version of
            # the original message, with a bad format string.
            wrong_type = u'Wrong type %(arg1)d'
            if six.PY3:
                trans.return_value.gettext.return_value = wrong_type
            else:
                trans.return_value.ugettext.return_value = wrong_type
            trans_result = result.translation()
            expected = msgid % params
            self.assertEqual(expected, trans_result) 
開發者ID:openstack,項目名稱:oslo.i18n,代碼行數:21,代碼來源:test_message.py

示例2: test_download

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_download(self):
        """
        Ensure the requested Document file is served.
        """
        simple_file = SimpleUploadedFile("delicious.txt", self.file_contents)
        document = Document.objects.create(name="Honeycrisp",
                                           author=self.user,
                                           file=simple_file,
                                           )
        document.save()

        with self.login(self.user):
            # Verify `django.views.static.serve` is called to serve up the file.
            # See related note in .views.DocumentDownload.get().
            with mock.patch("django.views.static.serve") as serve:
                serve.return_value = HttpResponse()
                self.get_check_200(self.download_urlname, pk=document.pk)
                self.assertTrue(serve.called) 
開發者ID:pinax,項目名稱:pinax-documents,代碼行數:20,代碼來源:test_views.py

示例3: test_distro_detection

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_distro_detection(self):
        def os_path_exists(f):
            if f.endswith('multibootusb.log'):
                return False
            return True
        os_path_exists_mock = MM()
        log_mock = MM()
        @patch('os.path.exists', os_path_exists)
        @patch('scripts.distro.log', log_mock)
        def _():
            fn = distro.detect_iso_from_file_list
            assert fn(['BOOT.wim', 'Sources']) == 'Windows'
            assert fn(['BOOT.wim', 'Sause']) is None
            assert fn(['config.isoclient', 'foo']) == 'opensuse'
            assert fn(['bar', 'dban', 'foo']) == 'slitaz'
            assert fn(['memtest.img']) == 'memtest'
            assert fn(['mt86.png','isolinux']) == 'raw_iso'
            assert fn(['menu.lst']) == 'grub4dos'
            assert fn(['bootwiz.cfg', 'bootmenu_logo.png']) == \
                'grub4dos_iso'
        _() 
開發者ID:mbusb,項目名稱:multibootusb,代碼行數:23,代碼來源:test-distro.py

示例4: test_admin_add_user_with_invalid_email

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_admin_add_user_with_invalid_email(self):
        admin = self._create_admin()
        self.client.force_login(admin)
        params = dict(
            username='testmail',
            email='test@invalid.com',
            password1='tester',
            password2='tester',
        )
        params.update(self.add_user_inline_params)
        params.update(self._additional_params_add())
        with patch('allauth.account.models.EmailAddress.objects.add_email') as mocked:
            mocked.side_effect = smtplib.SMTPSenderRefused(
                501, '5.1.7 Bad sender address syntax', 'test_name@test_domain'
            )
            self.client.post(reverse(f'admin:{self.app_label}_user_add'), params)
            mocked.assert_called_once() 
開發者ID:openwisp,項目名稱:openwisp-users,代碼行數:19,代碼來源:test_admin.py

示例5: test_config_deploy_failure

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_config_deploy_failure(self, mock_requests):
        """
        Cause an Exception in app.deploy to cause a release.delete
        """
        app_id = self.create_app()

        # deploy app to get a build
        url = "/v2/apps/{}/builds".format(app_id)
        body = {'image': 'autotest/example'}
        response = self.client.post(url, body)
        self.assertEqual(response.status_code, 201, response.data)
        self.assertEqual(response.data['image'], body['image'])

        with mock.patch('api.models.App.deploy') as mock_deploy:
            mock_deploy.side_effect = Exception('Boom!')
            url = '/v2/apps/{app_id}/config'.format(**locals())
            body = {'values': json.dumps({'test': "testvalue"})}
            response = self.client.post(url, body)
            self.assertEqual(response.status_code, 400) 
開發者ID:deis,項目名稱:controller,代碼行數:21,代碼來源:test_config.py

示例6: test_release_create_failure

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_release_create_failure(self, mock_requests):
        """
        Cause an Exception in app.deploy to cause a failed release in build.create
        """
        app_id = self.create_app()

        # deploy app to get a build
        url = "/v2/apps/{app_id}/builds".format(**locals())
        body = {'image': 'autotest/example'}
        response = self.client.post(url, body)
        self.assertEqual(response.status_code, 201, response.data)
        self.assertEqual(response.data['image'], body['image'])

        with mock.patch('api.models.App.deploy') as mock_deploy:
            mock_deploy.side_effect = Exception('Boom!')

            url = "/v2/apps/{app_id}/builds".format(**locals())
            body = {'image': 'autotest/example'}
            response = self.client.post(url, body)
            self.assertEqual(response.status_code, 400, response.data) 
開發者ID:deis,項目名稱:controller,代碼行數:22,代碼來源:test_build.py

示例7: test_release_registry_create_failure

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_release_registry_create_failure(self, mock_requests):
        """
        Cause a RegistryException in app.deploy to cause a failed release in build.create
        """
        app_id = self.create_app()

        # deploy app to get a build
        url = "/v2/apps/{app_id}/builds".format(**locals())
        body = {'image': 'autotest/example'}
        response = self.client.post(url, body)
        self.assertEqual(response.status_code, 201, response.data)
        self.assertEqual(response.data['image'], body['image'])

        with mock.patch('api.models.Release.publish') as mock_registry:
            mock_registry.side_effect = RegistryException('Boom!')

            url = "/v2/apps/{app_id}/builds".format(**locals())
            body = {'image': 'autotest/example'}
            response = self.client.post(url, body)
            self.assertEqual(response.status_code, 400, response.data) 
開發者ID:deis,項目名稱:controller,代碼行數:22,代碼來源:test_build.py

示例8: test_run_failure

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_run_failure(self, mock_requests):
        """Raise a KubeException via scheduler.run"""
        app_id = self.create_app()

        # create build
        body = {'image': 'autotest/example'}
        url = '/v2/apps/{app_id}/builds'.format(**locals())
        response = self.client.post(url, body)
        self.assertEqual(response.status_code, 201, response.data)

        with mock.patch('scheduler.KubeHTTPClient.run') as kube_run:
            kube_run.side_effect = KubeException('boom!')
            # run command
            url = '/v2/apps/{}/run'.format(app_id)
            body = {'command': 'ls -al'}
            response = self.client.post(url, body)
            self.assertEqual(response.status_code, 503, response.data) 
開發者ID:deis,項目名稱:controller,代碼行數:19,代碼來源:test_app.py

示例9: test_kubernetes_service_failure

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_kubernetes_service_failure(self):
        """
        Cause an Exception in kubernetes services
        """
        app_id = self.create_app()

        # scheduler.svc.get exception
        with mock.patch('scheduler.resources.service.Service.get') as mock_kube:
            mock_kube.side_effect = KubeException('Boom!')
            domain = 'foo.com'
            url = '/v2/apps/{}/domains'.format(app_id)
            response = self.client.post(url, {'domain': domain})
            self.assertEqual(response.status_code, 503, response.data)

        # scheduler.svc.update exception
        with mock.patch('scheduler.resources.service.Service.update') as mock_kube:
            domain = 'foo.com'
            url = '/v2/apps/{}/domains'.format(app_id)
            response = self.client.post(url, {'domain': domain})
            self.assertEqual(response.status_code, 201, response.data)

            mock_kube.side_effect = KubeException('Boom!')
            url = '/v2/apps/{}/domains/{}'.format(app_id, domain)
            response = self.client.delete(url)
            self.assertEqual(response.status_code, 503, response.data) 
開發者ID:deis,項目名稱:controller,代碼行數:27,代碼來源:test_domain.py

示例10: test_should_always_enable_force_admins_when_enabled

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_should_always_enable_force_admins_when_enabled(self, enable):
        # Given
        options = DotDict({
            'retries': 1,
            'enforce_admins': 'true',
            'github_repository': 'benjefferies/branch-bot-protection'
        })

        # When
        with patch('run.login') as mock:
            mock.return_value\
                .repository.return_value\
                .branch.return_value\
                .protection.return_value\
                .enforce_admins.enabled = True
            toggle_enforce_admin(options)

        # Then
        enable.assert_called_once() 
開發者ID:benjefferies,項目名稱:branch-protection-bot,代碼行數:21,代碼來源:test_run.py

示例11: test_should_always_disable_force_admins_when_disabled

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_should_always_disable_force_admins_when_disabled(self, disable):
        # Given
        options = DotDict({
            'retries': 1,
            'enforce_admins': 'false',
            'github_repository': 'benjefferies/branch-bot-protection'
        })

        # When
        with patch('run.login') as mock:
            mock.return_value\
                .repository.return_value\
                .branch.return_value\
                .protection.return_value\
                .enforce_admins.enabled = False
            toggle_enforce_admin(options)

        # Then
        disable.assert_called_once() 
開發者ID:benjefferies,項目名稱:branch-protection-bot,代碼行數:21,代碼來源:test_run.py

示例12: test_should_disable_force_admins

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_should_disable_force_admins(self, disable):
        # Given
        options = DotDict({
            'retries': 1,
            'github_repository': 'benjefferies/branch-bot-protection'
        })

        # When
        with patch('run.login') as mock:
            mock.return_value\
                .repository.return_value\
                .branch.return_value\
                .protection.return_value\
                .enforce_admins.enabled = True
            toggle_enforce_admin(options)

        # Then
        disable.assert_called_once() 
開發者ID:benjefferies,項目名稱:branch-protection-bot,代碼行數:20,代碼來源:test_run.py

示例13: test_should_enable_force_admins

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def test_should_enable_force_admins(self, enable):
        # Given
        options = DotDict({
            'retries': 1,
            'github_repository': 'benjefferies/branch-bot-protection'
        })

        # When
        with patch('run.login') as mock:
            mock.return_value\
                .repository.return_value\
                .branch.return_value\
                .protection.return_value\
                .enforce_admins.enabled = False
            toggle_enforce_admin(options)

        # Then
        enable.assert_called_once() 
開發者ID:benjefferies,項目名稱:branch-protection-bot,代碼行數:20,代碼來源:test_run.py

示例14: portfolio

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def portfolio(wallet_usd, wallet_btc, wallet_eth, wallet_xrp, exchange):

    portfolio = Portfolio(USD, wallets=[
        wallet_usd,
        wallet_btc,
        wallet_eth,
        wallet_xrp
    ])

    with mock.patch.object(Portfolio, 'clock', return_value=exchange.clock) as clock:
        portfolio = Portfolio(USD, wallets=[
            wallet_usd,
            wallet_btc,
            wallet_eth,
            wallet_xrp
        ])

    return portfolio 
開發者ID:tensortrade-org,項目名稱:tensortrade,代碼行數:20,代碼來源:test_portfolio.py

示例15: prop_args

# 需要導入模塊: from unittest import mock [as 別名]
# 或者: from unittest.mock import patch [as 別名]
def prop_args():
    """
    A bare-bones prop_args object. To use - make `prop_args` a test argument.
    """
    with patch('builtins.input', side_effect=ANSWERS_FOR_INPUT_PROMPTS):
        return PropArgs.create_props("basic", prop_dict=None) 
開發者ID:gcallah,項目名稱:indras_net,代碼行數:8,代碼來源:test_props.py


注:本文中的unittest.mock.patch方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。