【问题标题】:Mocking Twisted web client HTTP requests using HTTPretty使用 HTTPretty 模拟 Twisted Web 客户端 HTTP 请求
【发布时间】:2014-08-14 07:13:24
【问题描述】:

由于 Httpretty 在 Python 套接字层上工作,因此即使是 Twisted Web 请求也应该被模拟出来。但是我在使用 httpretty 时看到了一些奇怪的行为。它试图以某种方式连接到本地主机。下面的示例显示了差异:

import httpretty
from twisted.internet import reactor
from twisted.internet.defer import Deferred
from twisted.web.client import Agent
from twisted.web.http_headers import Headers
import requests

@httpretty.activate
def main():
    httpretty.register_uri(
        httpretty.GET, "http://example.com",
        body='[{"title": "Test Deal"}]',
        content_type="application/json")

    agent = Agent(reactor)

    d = agent.request(
        'GET',
        'http://example.com',
        Headers({'User-Agent': ['Twisted Web Client Example']}),
        None)

    def cbError(message):
        print 'Async Failed : %s' % message
    d.addErrback(cbError)

    def cbShutdown(ignored): reactor.stop()
    d.addBoth(cbShutdown)

    reactor.run()

    print 'Response received from Sync: %s' % \
            requests.get('http://example.com').status_code

main()

响应是:

Async Failed : [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.ConnectionRefusedError'>: Connection was refused by other side: 111: Connection refused.
]
Response received from Sync: 200

如何在 Twisted Web 客户端中使用 httpretty?

【问题讨论】:

    标签: client twisted twisted.web httpretty


    【解决方案1】:

    你不能。 HTTPretty 阻塞 HTTP 客户端库(如请求)。它不会模拟非阻塞套接字。

    【讨论】:

    • 嗯,好的。谢谢。为此,我可以使用任何解决方法来代替 httpretty 吗?
    • 有一些努力为Agent 使用应用程序创建一个测试库。你可以帮忙解决这个问题,twistedmatrix.com/trac/ticket/4024>。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2012-07-18
    • 2011-12-30
    • 1970-01-01
    • 2022-12-03
    相关资源
    最近更新 更多