我正在使用 unittest
来测试 Flask 应用程序,它是为 Python 3.5 编写的。我有一个 static
目录,其中包含将由我们的客户嵌入的 HTML 文件。根据请求来自哪个客户端,我添加了不同的 header (CORS、CSP 等)。
端点看起来像这样:
@app.route('/embed/<path:filename>', methods=['GET']):
def embed_static(filename):
response = flask.send_from_directory(app.config['EMBED_DIR'], filename)
# Do the header magic here
return response
……我为它写了一个测试:
def test_embed_static(self):
with unittest.mock.patch('flask.send_from_directory') as mocked:
page = app.test_client().get('/embed/test/index.html')
self.assertTrue(mocked.called)
最后一个断言总是失败。 unittest.mock.patch
在其他测试中就像魅力一样。
我是不是忽略了什么,或者这是我不知道的特例?
最佳答案
在进行测试 api 调用之前,您需要分配模拟对象的 return_value
。将您的代码更改为以下内容后,它就可以工作了:
def test_embed_static(self):
with unittest.mock.patch('flask.send_from_directory') as mocked:
mocked.return_value = "Test Mock"
page = app.test_client().get('/embed/test/index.html')
self.assertTrue(mocked.called)
关于python - 模拟 Flask 的 `send_from_directory` 用于测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208195/