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


Python patch.object方法代码示例

本文整理汇总了Python中unittest.mock.patch.object方法的典型用法代码示例。如果您正苦于以下问题:Python patch.object方法的具体用法?Python patch.object怎么用?Python patch.object使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在unittest.mock.patch的用法示例。


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

示例1: test_call_train

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_call_train(self):
        feedback_records = []

        feedback1 = FeedbackRecord(
            qna_id=1, user_id="test", user_question="How are you?"
        )

        feedback2 = FeedbackRecord(qna_id=2, user_id="test", user_question="What up??")

        feedback_records.extend([feedback1, feedback2])

        with patch.object(
            QnAMaker, "call_train", return_value=None
        ) as mocked_call_train:
            qna = QnAMaker(QnaApplicationTest.tests_endpoint)
            qna.call_train(feedback_records)

            mocked_call_train.assert_called_once_with(feedback_records) 
开发者ID:microsoft,项目名称:botbuilder-python,代码行数:20,代码来源:test_qna.py

示例2: test_multiprocessing

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_multiprocessing(self):
        testargs = ['', '-j', '2', '-d', '-dt', 'yahoo', 'test']
        with patch.object(sys, 'argv', new=testargs):
            f1 = StringIO()
            with redirect_stdout(f1):
                main()

        testargs = ['', '-j', '-d', '-dt', 'yahoo', 'test']
        with patch.object(sys, 'argv', new=testargs):
            f2 = StringIO()
            with redirect_stdout(f2):
                main()

        testargs = ['', '-d', '-dt', 'yahoo', 'test']
        with patch.object(sys, 'argv', new=testargs):
            f3 = StringIO()
            with redirect_stdout(f3):
                main()

        result1 = f1.getvalue().strip()
        result2 = f2.getvalue().strip()
        result3 = f3.getvalue().strip()

        assert result1 == result2 == result3 
开发者ID:zdict,项目名称:zdict,代码行数:26,代码来源:test_arguments.py

示例3: test_platform_readline

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_platform_readline():
    '''
    Check the imported readline module on different platforms
    '''
    with patch.object(sys, 'platform', new='linux'):
        readline = import_readline()
        assert readline.__name__ == 'readline'

    with patch.object(sys, 'platform', new='darwin'):
        readline = import_readline()
        expect = 'gnureadline' if sys.version_info <= (3, 5) else 'readline'
        assert readline.__name__ == expect

    with patch.object(sys, 'platform', new='foo'):
        readline = import_readline()
        assert readline.__name__ == 'readline' 
开发者ID:zdict,项目名称:zdict,代码行数:18,代码来源:test_utils.py

示例4: post

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def post(self, _data=None, _headers=None, **kwargs):
        self.count += 1

        if _data is not None:
            with patch.object(oauth.aiohttp.payload, 'BytesPayload',
                              side_effect=dummy_func):
                assert _data._gen_form_urlencoded() == b"access_token=abc"

        if _headers is not None:
            key = "1234567890:0987654321"
            auth = base64.b64encode(key.encode('utf-8')).decode('utf-8')
            assert _headers['Authorization'] == 'Basic ' + auth

        # This is needed to run `test_oauth2_concurrent_refreshes`
        # without that, refresh tasks would be executed sequentially
        # In a sense it is a simulation of a request being fetched
        await asyncio.sleep(0.001)
        return {'access_token': "abc"} 
开发者ID:odrling,项目名称:peony-twitter,代码行数:20,代码来源:test_oauth.py

示例5: test_request_error_handler

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_request_error_handler(api_path, _error_handler=True):
    client = api_path.client
    with patch.object(client, 'request', side_effect=dummy) as client_request:
        with patch.object(client, 'error_handler',
                          side_effect=dummy_error_handler) as error_handler:
            client.loop.run_until_complete(
                requests.Request(api_path, 'get',
                                 _error_handling=_error_handler,
                                 test=1, _test=2)
            )
            assert client_request.called_with(method='get',
                                              url=url,
                                              skip_params=False,
                                              test=2,
                                              params={'test': 1})
            assert error_handler.called is _error_handler 
开发者ID:odrling,项目名称:peony-twitter,代码行数:18,代码来源:test_requests.py

示例6: test_streaming_apis

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_streaming_apis():
    async with DummyClient() as dummy_client:
        with patch.object(dummy_client, 'request', side_effect=dummy)\
                as request:
            await dummy_client.api.test.get()
            assert request.called

        with patch.object(dummy_client, 'stream_request') as request:
            dummy_client.stream.test.get()
            assert request.called

    async with DummyClient(streaming_apis={'api'}) as client:
        with patch.object(client, 'stream_request') as request:
            client.api.test.get()
            assert request.called

        with patch.object(client, 'request', side_effect=dummy) as request:
            await client.stream.test.get()
            assert request.called 
开发者ID:odrling,项目名称:peony-twitter,代码行数:21,代码来源:test_base_client.py

示例7: test_request_proxy

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_request_proxy():
    def raise_proxy(*args, proxy=None, **kwargs):
        raise RuntimeError(proxy)

    async with BasePeonyClient("", "",
                               proxy="http://some.proxy.com") as dummy_client:
        async with aiohttp.ClientSession() as session:
            with patch.object(dummy_client.headers, 'prepare_request',
                              side_effect=raise_proxy):
                try:
                    await dummy_client.request(method='get',
                                               url="http://hello.com",
                                               session=session,
                                               future=None)
                except RuntimeError as e:
                    assert str(e) == "http://some.proxy.com"
                else:
                    pytest.fail("Could not check proxy") 
开发者ID:odrling,项目名称:peony-twitter,代码行数:20,代码来源:test_base_client.py

示例8: test_chunked_upload_fail

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_chunked_upload_fail(medias):
    async with DummyPeonyClient() as client:
        media = medias['video']
        media_data = await media.download()

        chunk_size = 1024**2

        dummy_request = DummyRequest(client, media, chunk_size, True)

        with patch.object(client, 'request',
                          side_effect=dummy_request):
            with patch.object(asyncio, 'sleep', side_effect=dummy) as sleep:
                with pytest.raises(peony.exceptions.MediaProcessingError):
                    await client.upload_media(
                        media_data, chunk_size=chunk_size, chunked=True
                    )
                    sleep.assert_called_with(5) 
开发者ID:odrling,项目名称:peony-twitter,代码行数:19,代码来源:test_upload.py

示例9: test_stream_eof_reconnect

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_stream_eof_reconnect():
    async def dummy(*args, **kwargs):
        pass

    turn = -1

    async with Stream() as stream:
        with patch.object(stream, '_connect',
                          side_effect=response_eof):
            with patch.object(peony.stream.asyncio, 'sleep',
                              side_effect=dummy):
                async for data in stream:
                    turn += 1

                    if turn == 0:
                        assert data == {'connected': True}
                    elif turn % 2 == 1:
                        assert stream._state == EOF
                        assert data == {'reconnecting_in': 0,
                                        'error': None}
                    else:
                        assert data == {'stream_restart': True}
                        break 
开发者ID:odrling,项目名称:peony-twitter,代码行数:25,代码来源:test_stream.py

示例10: test_stream_reconnection_enhance_your_calm

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_stream_reconnection_enhance_your_calm():
    async def dummy(*args, **kwargs):
        pass

    turn = -1

    async with Stream() as stream:
        with patch.object(stream, '_connect', side_effect=response_calm):
            with patch.object(peony.stream.asyncio, 'sleep',
                              side_effect=dummy):
                async for data in stream:
                    assert stream._state == ENHANCE_YOUR_CALM
                    turn += 1

                    if turn >= 100:
                        break

                    if turn == 0:
                        assert data == {'connected': True}
                    elif turn % 2 == 1:
                        timeout = ENHANCE_YOUR_CALM_TIMEOUT * 2**(turn // 2)
                        assert data == {'reconnecting_in': timeout,
                                        'error': None}
                    else:
                        assert data == {'stream_restart': True} 
开发者ID:odrling,项目名称:peony-twitter,代码行数:27,代码来源:test_stream.py

示例11: test_stream_reconnection_error_on_reconnection

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_stream_reconnection_error_on_reconnection():
    async with Stream() as stream:
        with patch.object(stream, '_connect',
                          side_effect=response_disconnection):
            await stream.connect()
            assert stream._state == DISCONNECTION
            data = {'reconnecting_in': DISCONNECTION_TIMEOUT,
                    'error': None}
            assert data == await stream.__anext__()
            assert stream._reconnecting

        with patch.object(stream, '_connect', side_effect=response_calm):
            stream._error_timeout = 0
            assert {'stream_restart': True} == await stream.__anext__()
            assert stream._state == ENHANCE_YOUR_CALM

            data = {'reconnecting_in': ENHANCE_YOUR_CALM_TIMEOUT,
                    'error': None}
            assert data == await stream.__anext__() 
开发者ID:odrling,项目名称:peony-twitter,代码行数:21,代码来源:test_stream.py

示例12: test_stream_cancel

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_stream_cancel(event_loop):
    async def cancel(task):
        await asyncio.sleep(0.001)
        task.cancel()

    async def test_stream_iterations(stream):
        async with async_timeout.timeout(0.5):
            while True:
                await _stream_iteration(stream)

    async with aiohttp.ClientSession() as session:
        client = peony.client.BasePeonyClient("", "", session=session)
        context = peony.stream.StreamResponse(method='GET',
                                              url="http://whatever.com",
                                              client=client)

        with context as stream:
            with patch.object(stream, '_connect',
                              side_effect=stream_content):
                coro = test_stream_iterations(stream)
                task = event_loop.create_task(coro)
                cancel_task = event_loop.create_task(cancel(task))

                with async_timeout.timeout(1):
                    await asyncio.wait([task, cancel_task]) 
开发者ID:odrling,项目名称:peony-twitter,代码行数:27,代码来源:test_stream.py

示例13: test_error_handler_service_unavailable

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_error_handler_service_unavailable(event_loop):
    global tries
    tries = 4

    async def service_unavailable(**kwargs):
        global tries
        tries -= 1

        if tries > 0:
            response = MockResponse(status=503)
            raise await exceptions.throw(response)
        else:
            return MockResponse()

    with patch.object(asyncio, 'sleep', side_effect=dummy) as sleep:
        try:
            fut = create_future(event_loop)
            coro = utils.DefaultErrorHandler(service_unavailable)(future=fut)
            event_loop.create_task(coro)
            await fut
        except exceptions.ServiceUnavailable:
            assert sleep.called
        else:
            pytest.fail("ServiceUnavailable not raised") 
开发者ID:odrling,项目名称:peony-twitter,代码行数:26,代码来源:test_utils.py

示例14: setUp

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def setUp(self):
        super().setUp()

        DescriptorSchema.objects.create(
            name="Sample", slug="sample", contributor=self.contributor
        )
        self.process = Process.objects.create(
            name="Test process",
            type="data:test:",
            contributor=self.contributor,
            entity_type="sample",
            entity_descriptor_schema="sample",
        )
        # Entity is created automatically when Data object is created
        self.data = Data.objects.create(
            name="Test data", contributor=self.contributor, process=self.process
        ) 
开发者ID:genialis,项目名称:resolwe,代码行数:19,代码来源:test_models.py

示例15: test_change_size

# 需要导入模块: from unittest.mock import patch [as 别名]
# 或者: from unittest.mock.patch import object [as 别名]
def test_change_size(self, path_mock):
        """Size is not changed after object is done."""
        data = self.create_data(path_mock, self.contributor, self.process)

        path_mock.return_value = MagicMock(
            stat=lambda: MagicMock(st_size=42000), is_file=lambda: True
        )

        hydrate_size(data)
        self.assertEqual(data.output["test_file"]["size"], 42000)

        path_mock.return_value = MagicMock(
            stat=lambda: MagicMock(st_size=43000), is_file=lambda: True
        )
        hydrate_size(data)
        self.assertEqual(data.output["test_file"]["size"], 43000)

        data.status = Data.STATUS_DONE
        path_mock.return_value = MagicMock(
            stat=lambda: MagicMock(st_size=44000), is_file=lambda: True
        )
        hydrate_size(data)
        self.assertEqual(data.output["test_file"]["size"], 43000) 
开发者ID:genialis,项目名称:resolwe,代码行数:25,代码来源:test_models.py


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