python - 如何测试 Flask 使用的是 test_client 而不是 client?

标签 python python-3.x flask pytest

我在 Flask 中使用 Pytest fixtures。我的应用程序是使用应用程序工厂实例化的。

#conftest.py

@pytest.fixture(scope='session')
def app(request):
    '''Session-wide test application'''
    app = create_app('testing')
    app.client = app.test_client()
    app_context = app.app_context()
    app_context.push()


    def teardown():
        app_context.pop()

    request.addfinalizer(teardown)
    return app

我想验证由我的 fixture 创建的应用程序是否使用 Flask's built-in test_client ,所以我写了一个测试:

#test_basics.py

def test_app_client_is_testing(app):
    assert app.client() == app.test_client()

当我运行这个测试时,我得到:TypeError: 'FlaskClient' object is not callable

我做错了什么?

是测试不正确,还是 fixture 不正确?

最佳答案

app.client 已经是一个实例,你不应该再次调用它。最终,这个测试毫无意义。 client当然是测试客户端,刚才在fixture中就是这么创建的。此外,客户端永远不会相等,它们是不同的实例。

from flask.testing import FlaskClient

assert app.client == app.test_client()  # different instances, never true
assert isinstance(app.client, app.test_client_class or FlaskClient)  # still pointless, but correct

您可能需要两个固定装置:appclient,而不是在应用程序上创建客户端。

@pytest.yield_fixture
def app():
    a = create_app('testing')
    a.testing = True

    with a.app_context():
        yield a

@pytest.yield_fixture
def client(app):
    with app.test_client() as c:
        yield c

from flask.testing import FlaskClient

def test_app_client_is_client(app, client):
    # why?
    assert isinstance(client, app.test_client_class or FlaskClient)

关于python - 如何测试 Flask 使用的是 test_client 而不是 client?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443549/

相关文章:

python - 一个大正则表达式是否比一堆小正则表达式更有效?

python-3.x - 将 Python 3 与 AWS lambda 结合使用

python - 模板文件更改时重新加载 Flask 应用程序

python - 如何将 csv 文件转换为 python 中的列表列表

mysql - 如何从 select 语句向表中插入信息?

使用 Openshift 时出现 Python Rest Http 错误 (Flask)

templates - Go 模板扩展和 super ?

javascript - 通过对 Flask 的函数调用更新值

python - zip 变量首次使用后为空

python - 使用 Python 中的单个键合并两个不同长度的字典列表