我有一个扩展 tornado.testing.AsyncHTTPTestCase
的测试类,并且我正在使用 Nose 来运行其测试方法。每个测试方法都会检查来自被测 Tornado 服务器上 URL 的响应。其中一些请求需要几秒钟才能完成。每个请求都通过多种方法进行测试。
我想避免在测试期间两次发出相同的 HTTP 请求,因为这会显着减慢测试速度。确保每个请求仅发出一次的最佳方法是什么?
示例:
class ServerTest(AsyncHTTPTestCase):
def test_endpoint(self):
self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()
self.assertTrue(response.code == 200)
def test_endpoint_differently(self):
self.http_client.fetch(self.get_url('/'), self.stop)
response = self.wait()
self.assertTrue(response.body != "")
以上两种测试方法都请求/
端点,速度很慢。如何让此请求发生一次(在第一次测试运行之前)并让测试检查缓存的响应?
我已经使用类变量来实现这个功能,如下所示:
class ServerTest(AsyncHTTPTestCase):
responses = {}
def setUp(self):
if self.responses == {}:
# do http request
responses['/'] = result
但我想知道是否有更干净的方法来做到这一点(也许使用 Nose)?我研究了unittest setUpClass
方法,但由于该方法必须是@classmethod
,测试用例实例的http请求实用程序当时尚不可用setUpClass
运行。
最佳答案
此类实现了我的解决方案:https://gist.github.com/emmett9001/5785018
进一步研究这一点让我意识到,像我希望的那样预先加载所有请求并没有多大意义。我实现了简单的缓存,确保每个请求仅发生一次:
responses = {}
def cache_response(self, key, response):
self.responses[key] = {}
self.responses[key]['response'] = response
self.responses[key]['time'] = dt.datetime.now()
def get_cached_url(self, path):
if path not in self.responses.keys():
self.http_client.fetch(self.get_url(path), self.stop)
self.cache_response(path, self.wait(timeout=30))
return self.responses[path]
关于python - 在 Tornado AsyncHTTPTestCase 中缓存 HTTP 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17115922/