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

Python testing.StubTreq类代码示例

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

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



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

示例1: test_mismatched_request_causes_failure

    def test_mismatched_request_causes_failure(self):
        """
        If a request is made that is not expected as the next request,
        causes a failure.
        """
        sequence = RequestSequence(
            [(('get', 'https://anything/', {'1': ['2']},
               HasHeaders({'1': ['1']}), 'what'),
              (418, {}, 'body')),
             (('get', 'http://anything', {}, HasHeaders({'2': ['1']}), 'what'),
              (202, {}, 'deleted'))],
            async_failure_reporter=self.async_failures.append)

        stub = StubTreq(StringStubbingResource(sequence))
        get = partial(stub.get, 'https://anything?1=2', data='what',
                      headers={'1': '1'})

        resp = self.successResultOf(get())
        self.assertEqual(418, resp.code)
        self.assertEqual('body', self.successResultOf(stub.content(resp)))
        self.assertEqual([], self.async_failures)

        resp = self.successResultOf(get())
        self.assertEqual(500, resp.code)
        self.assertEqual(1, len(self.async_failures))
        self.assertIn("Expected the next request to be",
                      self.async_failures[0])

        self.assertFalse(sequence.consumed())
开发者ID:cyli,项目名称:treq,代码行数:29,代码来源:test_testing.py


示例2: test_providing_resource_to_stub_treq

    def test_providing_resource_to_stub_treq(self):
        """
        The resource provided to StubTreq responds to every request no
        matter what the URI or parameters or data.
        """
        verbs = ("GET", "PUT", "HEAD", "PATCH", "DELETE", "POST")
        urls = (
            "http://supports-http.com",
            "https://supports-https.com",
            "http://this/has/a/path/and/invalid/domain/name",
            "https://supports-https.com:8080",
            "http://supports-http.com:8080",
        )
        params = (None, {}, {b"page": [1]})
        headers = (None, {}, {b"x-random-header": [b"value", b"value2"]})
        data = (None, b"", b"some data", b'{"some": "json"}')

        stub = StubTreq(_StaticTestResource())

        combos = (
            (verb, {"url": url, "params": p, "headers": h, "data": d})
            for verb in verbs
            for url in urls
            for p in params
            for h in headers
            for d in data
        )
        for combo in combos:
            verb, kwargs = combo
            deferreds = (stub.request(verb, **kwargs), getattr(stub, verb.lower())(**kwargs))
            for d in deferreds:
                resp = self.successResultOf(d)
                self.assertEqual(418, resp.code)
                self.assertEqual([b"teapot!"], resp.headers.getRawHeaders(b"x-teapot"))
                self.assertEqual(b"" if verb == "HEAD" else b"I'm a teapot", self.successResultOf(stub.content(resp)))
开发者ID:twisted,项目名称:treq,代码行数:35,代码来源:test_testing.py


示例3: test_consume_context_manager_fails_on_remaining_requests

    def test_consume_context_manager_fails_on_remaining_requests(self):
        """
        If the `consume` context manager is used, if there are any remaining
        expecting requests, the test case will be failed.
        """
        sequence = RequestSequence(
            [((ANY, ANY, ANY, ANY, ANY), (418, {}, 'body'))] * 2,
            async_failure_reporter=self.async_failures.append)
        stub = StubTreq(StringStubbingResource(sequence))

        consume_failures = []
        with sequence.consume(sync_failure_reporter=consume_failures.append):
            self.successResultOf(stub.get('https://anything', data='what',
                                          headers={'1': '1'}))

        self.assertEqual(1, len(consume_failures))
        self.assertIn(
            "Not all expected requests were made.  Still expecting:",
            consume_failures[0])
        self.assertIn(
            "{0}(url={0}, params={0}, headers={0}, data={0})".format(
                repr(ANY)),
            consume_failures[0])

        # no asynchronous failures (mismatches, etc.)
        self.assertEqual([], self.async_failures)
开发者ID:cyli,项目名称:treq,代码行数:26,代码来源:test_testing.py


示例4: test_content

 def test_content(self):
     client = StubTreq(StaticResource(content=b'abcd'))
     response = self.successResultOf(client.get('http://an.example/'))
     self.assertEqual(200, response.code)
     self.assertEqual([b'application/xml'], response.headers.getRawHeaders(b'Content-Type'))
     body = self.successResultOf(response.content())
     self.assertEqual(b'abcd', body)
开发者ID:twm,项目名称:yarrharr,代码行数:7,代码来源:test_fetch.py


示例5: test_mismatched_request_causes_failure

    def test_mismatched_request_causes_failure(self):
        """
        If a request is made that is not expected as the next request,
        causes a failure.
        """
        sequence = RequestSequence(
            [
                (
                    (b"get", "https://anything/", {b"1": [b"2"]}, HasHeaders({b"1": [b"1"]}), b"what"),
                    (418, {}, b"body"),
                ),
                ((b"get", "http://anything", {}, HasHeaders({b"2": [b"1"]}), b"what"), (202, {}, b"deleted")),
            ],
            async_failure_reporter=self.async_failures.append,
        )

        stub = StubTreq(StringStubbingResource(sequence))
        get = partial(stub.get, "https://anything?1=2", data=b"what", headers={b"1": b"1"})

        resp = self.successResultOf(get())

        self.assertEqual(418, resp.code)
        self.assertEqual(b"body", self.successResultOf(stub.content(resp)))
        self.assertEqual([], self.async_failures)

        resp = self.successResultOf(get())
        self.assertEqual(500, resp.code)
        self.assertEqual(1, len(self.async_failures))
        self.assertIn("Expected the next request to be", self.async_failures[0])

        self.assertFalse(sequence.consumed())
开发者ID:twisted,项目名称:treq,代码行数:31,代码来源:test_testing.py


示例6: test_content_type

 def test_content_type(self):
     client = StubTreq(StaticResource(content=b'hello', content_type='text/plain'))
     response = self.successResultOf(client.get('http://an.example/'))
     self.assertEqual(200, response.code)
     self.assertEqual([b'text/plain'], response.headers.getRawHeaders(b'Content-Type'))
     body = self.successResultOf(response.content())
     self.assertEqual(b'hello', body)
开发者ID:twm,项目名称:yarrharr,代码行数:7,代码来源:test_fetch.py


示例7: test_handles_invalid_schemes

 def test_handles_invalid_schemes(self):
     """
     Invalid URLs errback with a :obj:`SchemeNotSupported` failure, and does
     so even after a successful request.
     """
     stub = StubTreq(_StaticTestResource())
     self.failureResultOf(stub.get(""), SchemeNotSupported)
     self.successResultOf(stub.get("http://url.com"))
     self.failureResultOf(stub.get(""), SchemeNotSupported)
开发者ID:twisted,项目名称:treq,代码行数:9,代码来源:test_testing.py


示例8: test_handles_asynchronous_requests

 def test_handles_asynchronous_requests(self):
     """
     Handle a resource returning NOT_DONE_YET.
     """
     stub = StubTreq(_NonResponsiveTestResource())
     d = stub.request('method', 'http://url', data="1234")
     self.assertNoResult(d)
     d.cancel()
     self.failureResultOf(d, ResponseFailed)
开发者ID:cyli,项目名称:treq,代码行数:9,代码来源:test_testing.py


示例9: test_match

 def test_match(self):
     client = StubTreq(StaticEtagResource(b'abcd', b'"abcd"'))
     response = self.successResultOf(client.get('http://an.example/', headers={
         'if-none-match': ['"abcd"'],
     }))
     self.assertEqual(304, response.code)
     self.assertEqual(['application/xml'], response.headers.getRawHeaders('Content-Type'))
     self.assertEqual(['"abcd"'], response.headers.getRawHeaders('Etag'))
     body = self.successResultOf(response.content())
     self.assertEqual(b'', body)
开发者ID:twm,项目名称:yarrharr,代码行数:10,代码来源:test_fetch.py


示例10: test_handles_failing_asynchronous_requests

 def test_handles_failing_asynchronous_requests(self):
     """
     Handle a resource returning NOT_DONE_YET and then canceling the
     request.
     """
     stub = StubTreq(_NonResponsiveTestResource())
     d = stub.request("method", "http://url", data=b"1234")
     self.assertNoResult(d)
     d.cancel()
     self.failureResultOf(d, ResponseFailed)
开发者ID:twisted,项目名称:treq,代码行数:10,代码来源:test_testing.py


示例11: test_handles_successful_asynchronous_requests_with_streaming

    def test_handles_successful_asynchronous_requests_with_streaming(self):
        """
        Handle a resource returning NOT_DONE_YET and then streaming data back
        gradually over time.
        """
        rsrc = _EventuallyResponsiveTestResource()
        stub = StubTreq(rsrc)
        d = stub.request("method", "http://example.com/", data="1234")
        self.assertNoResult(d)

        chunks = []
        rsrc.stored_request.write(b"spam ")
        rsrc.stored_request.write(b"eggs")
        stub.flush()
        resp = self.successResultOf(d)
        d = stub.collect(resp, chunks.append)
        self.assertNoResult(d)
        self.assertEqual(b"".join(chunks), b"spam eggs")

        del chunks[:]
        rsrc.stored_request.write(b"eggs\r\nspam\r\n")
        stub.flush()
        self.assertNoResult(d)
        self.assertEqual(b"".join(chunks), b"eggs\r\nspam\r\n")

        rsrc.stored_request.finish()
        stub.flush()
        self.successResultOf(d)
开发者ID:twisted,项目名称:treq,代码行数:28,代码来源:test_testing.py


示例12: test_no_match

 def test_no_match(self):
     client = StubTreq(StaticLastModifiedResource(
         content=b'abcd',
         last_modified=u'Mon, 6 Feb 2017 00:00:00 GMT',
     ))
     response = self.successResultOf(client.get('http://an.example/'))
     self.assertEqual(200, response.code)
     self.assertEqual([u'Mon, 6 Feb 2017 00:00:00 GMT'],
                      response.headers.getRawHeaders(u'Last-Modified'))
     body = self.successResultOf(response.content())
     self.assertEqual(b'abcd', body)
开发者ID:twm,项目名称:yarrharr,代码行数:11,代码来源:test_fetch.py


示例13: test_passing_in_strange_data_is_rejected

 def test_passing_in_strange_data_is_rejected(self):
     """
     StubTreq rejects data that isn't list/dictionary/tuple/bytes/unicode.
     """
     stub = StubTreq(_StaticTestResource())
     self.assertRaises(AssertionError, stub.request, "method", "http://url", data=object())
     self.successResultOf(stub.request("method", "http://url", data={}))
     self.successResultOf(stub.request("method", "http://url", data=[]))
     self.successResultOf(stub.request("method", "http://url", data=()))
     self.successResultOf(stub.request("method", "http://url", data=binary_type(b"")))
     self.successResultOf(stub.request("method", "http://url", data=text_type("")))
开发者ID:twisted,项目名称:treq,代码行数:11,代码来源:test_testing.py


示例14: test_handles_successful_asynchronous_requests

 def test_handles_successful_asynchronous_requests(self):
     """
     Handle a resource returning NOT_DONE_YET and then later finishing the
     response.
     """
     rsrc = _EventuallyResponsiveTestResource()
     stub = StubTreq(rsrc)
     d = stub.request("method", "http://example.com/", data=b"1234")
     self.assertNoResult(d)
     rsrc.stored_request.finish()
     stub.flush()
     resp = self.successResultOf(d)
     self.assertEqual(resp.code, 200)
开发者ID:twisted,项目名称:treq,代码行数:13,代码来源:test_testing.py


示例15: test_async_failures_logged

    def test_async_failures_logged(self):
        """
        When no `async_failure_reporter` is passed async failures are logged by
        default.
        """
        sequence = RequestSequence([])
        stub = StubTreq(StringStubbingResource(sequence))

        with sequence.consume(self.fail):
            self.successResultOf(stub.get('https://example.com'))

        [failure] = self.flushLoggedErrors()
        self.assertIsInstance(failure.value, AssertionError)
开发者ID:twisted,项目名称:treq,代码行数:13,代码来源:test_testing.py


示例16: FakeMarathonAPI

class FakeMarathonAPI(object):
    app = Klein()

    def __init__(self, marathon):
        self._marathon = marathon
        self.client = StubTreq(self.app.resource())
        self.event_requests = []
        self._called_get_apps = False

    def check_called_get_apps(self):
        """ Check and reset the ``_called_get_apps`` flag. """
        was_called, self._called_get_apps = self._called_get_apps, False
        return was_called

    @app.route('/v2/apps', methods=['GET'])
    def get_apps(self, request):
        self._called_get_apps = True
        response = {
            'apps': self._marathon.get_apps()
        }
        request.setResponseCode(200)
        write_request_json(request, response)

    @app.route('/v2/events', methods=['GET'])
    def get_events(self, request):
        assert (get_single_header(request.requestHeaders, 'Accept') ==
                'text/event-stream')

        request.setResponseCode(200)
        request.setHeader('Content-Type', 'text/event-stream')
        # Push the response headers before any events are written
        request.write(b'')
        self.client.flush()

        def callback(event):
            _write_request_event(request, event)
            self.client.flush()
        self._marathon.attach_event_stream(
            callback, _get_event_types(request.args), request.getClientIP())
        self.event_requests.append(request)

        def finished_errback(failure):
            self._marathon.detach_event_stream(callback, request.getClientIP())
            self.event_requests.remove(request)

        finished = request.notifyFinish()
        finished.addErrback(finished_errback)

        return finished
开发者ID:praekeltfoundation,项目名称:marathon-acme,代码行数:49,代码来源:fake_marathon.py


示例17: test_unexpected_number_of_request_causes_failure

    def test_unexpected_number_of_request_causes_failure(self):
        """
        If there are no more expected requests, making a request causes a
        failure.
        """
        sequence = RequestSequence([], async_failure_reporter=self.async_failures.append)
        stub = StubTreq(StringStubbingResource(sequence))
        d = stub.get("https://anything", data=b"what", headers={b"1": b"1"})
        resp = self.successResultOf(d)
        self.assertEqual(500, resp.code)
        self.assertEqual(1, len(self.async_failures))
        self.assertIn("No more requests expected, but request", self.async_failures[0])

        # the expected requests have all been made
        self.assertTrue(sequence.consumed())
开发者ID:twisted,项目名称:treq,代码行数:15,代码来源:test_testing.py


示例18: test_works_with_mock_any

    def test_works_with_mock_any(self):
        """
        :obj:`mock.ANY` can be used with the request parameters.
        """
        sequence = RequestSequence(
            [((ANY, ANY, ANY, ANY, ANY), (418, {}, b"body"))], async_failure_reporter=self.async_failures.append
        )
        stub = StubTreq(StringStubbingResource(sequence))

        with sequence.consume(sync_failure_reporter=self.fail):
            d = stub.get("https://anything", data=b"what", headers={b"1": b"1"})
            resp = self.successResultOf(d)
            self.assertEqual(418, resp.code)
            self.assertEqual(b"body", self.successResultOf(stub.content(resp)))

        self.assertEqual([], self.async_failures)

        # the expected requests have all been made
        self.assertTrue(sequence.consumed())
开发者ID:twisted,项目名称:treq,代码行数:19,代码来源:test_testing.py


示例19: test_interacts_successfully_with_istub

    def test_interacts_successfully_with_istub(self):
        """
        The :obj:`IStringResponseStubs` is passed the correct parameters with
        which to evaluate the response, and the response is returned.
        """
        resource = StringStubbingResource(
            self._get_response_for(
                (b"DELETE", "http://what/a/thing", {b"page": [b"1"]}, {b"x-header": [b"eh"]}, b"datastr"),
                (418, {b"x-response": b"responseheader"}, b"response body"),
            )
        )

        stub = StubTreq(resource)

        d = stub.delete("http://what/a/thing", headers={b"x-header": b"eh"}, params={b"page": b"1"}, data=b"datastr")
        resp = self.successResultOf(d)
        self.assertEqual(418, resp.code)
        self.assertEqual([b"responseheader"], resp.headers.getRawHeaders(b"x-response"))
        self.assertEqual(b"response body", self.successResultOf(stub.content(resp)))
开发者ID:twisted,项目名称:treq,代码行数:19,代码来源:test_testing.py


示例20: test_interacts_successfully_with_istub

    def test_interacts_successfully_with_istub(self):
        """
        The :obj:`IStringResponseStubs` is passed the correct parameters with
        which to evaluate the response, and the response is returned.
        """
        resource = StringStubbingResource(self._get_response_for(
            ('DELETE', 'http://what/a/thing', {'page': ['1']},
             {'x-header': ['eh']}, 'datastr'),
            (418, {'x-response': 'responseheader'}, 'response body')))

        stub = StubTreq(resource)

        d = stub.delete('http://what/a/thing', headers={'x-header': 'eh'},
                        params={'page': '1'}, data='datastr')
        resp = self.successResultOf(d)
        self.assertEqual(418, resp.code)
        self.assertEqual(['responseheader'],
                         resp.headers.getRawHeaders('x-response'))
        self.assertEqual('response body',
                         self.successResultOf(stub.content(resp)))
开发者ID:cyli,项目名称:treq,代码行数:20,代码来源:test_testing.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python client.BaseClient类代码示例发布时间:2022-05-27
下一篇:
Python client.HTTPClient类代码示例发布时间: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