python - 在 Tornado AsyncHTTPTestCase 中缓存 HTTP 响应

标签 python tornado nose

我有一个扩展 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/

相关文章:

python - 如何使用 python 使用回归模型将预测值转换为 NaN 输入值

python - Matplotlib。无法更改第二个 y 轴上的刻度

python - 如何使 Python 3 的打印适合命令提示符的大小?

python - 如何将变量传递给 IPython 中的魔术“运行”函数

python - Tornado https ssl 错误

python - 如何使用 Tornado 实现时间线(实时 - 就像 Twitter 的)?

python - django doctests 没有运行

python - Tornado :get_argument——我应该自己转义输入吗?

python - 在 python 中显示覆盖率的命令行选项

python - 如何让 nose 将案例输出记录到单独的文件中?