由于 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
我如何将 httpretty 与 Twisted Web 客户端一起使用?