python-3.x - 我可以在测试 Flask 应用程序功能时使用模拟吗?

标签 python-3.x unit-testing flask mocking

我正在尝试在我的 Flask 应用程序上测试一些调用外部 API 的路由,我想模拟这些路由。

路由设置如下:

@app.route('/url/<string::arg>')
def route_function(arg):
    data = external_api(arg)
    response = make_response(data)
    # configure response
    return response

我最初尝试过这样的事情:
class TestFlaskApp(unittest.TestCase):
    def setUp(self):
        self.app = app.test_client()

    @patch('external_api',
           side_effect=mock_api)
    def test_flask_route(self, api):
        result = app.get('/url/arg')
        self.assertEqual(result.status_code, 200)
        api.assert_called_once_with('arg')

...失败了。没有调用模拟 API 函数,因为我认为模拟不适用于应用程序上下文。

我也试过这个,认为我可以直接测试路由功能,从而避免使用应用程序上下文:
class TestAppFunctions(unittest.TestCase):
    @patch('external_api',
           side_effect=mock_api)
    def test_flask_function(self, api):
        result = my_flask_app.route_function('arg')
        self.assertEqual(result.status_code, 200)
        api.assert_called_once_with('arg')

...但这也不起作用,因为要做出回应,route_function需要应用上下文。

那么有没有办法在应用程序上下文中进行模拟?我还能如何在不触发外部 API 调用的情况下测试这些路由?

最佳答案

Oluwafemi Sule是对的......我只需要在使用它的地方修补函数,而不是在定义它的地方。

You need to pass the object path to the patch function so that it can be resolved and replaced with the mock at runtime. For example if external_api function is called in a module named routes which is in turn contained in a package named my_shining_app, patch will be passed as my_shining_app.routes.external_api

Note that the path should be where the function is called (i.e. where it's to be replaced with the mock) and not where it's defined

关于python-3.x - 我可以在测试 Flask 应用程序功能时使用模拟吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50686703/

相关文章:

python - 从多个拆分单个

docker - 如何让两个运行 flask 服务和 golang 服务的 docker 容器相互通信?

python - 在启动 flask 之前如何检查 redis 是否正在运行(如果没有则启动它)?

python - Pytorch BCELoss 对相同输入使用不同的输出

python - 测试多个数字的整除性

python-3.x - 理解数学

java - 如何对方法调用返回的对象的结构进行单元测试?

unit-testing - 如何编写一个测试来检查 chai 中的多种类型

python - 为什么 (3.3==np.asarray([3.3])) 等于 [True] 而不是 False?

python - 未知的 MS 编译器版本 1916 - 我尝试使用 Flask 运行 Python 并收到此错误