2015-02-10 124 views
1

我正在使用Pytest夹具与烧瓶。我的应用程序使用应用程序工厂实例化。如何测试Flask是否使用test_client而不是客户端?

#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 

我想验证我的灯具创建的应用程序使用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

我是什么我做错了?

测试不正确,或者夹具不正确?

回答

4

app.client已经是一个实例,你不应该再次调用它。最终,这个测试没有意义。当然,客户端是一个测试客户端,这就是你在夹具中创建它的方式。而且,客户永远不会平等,他们是不同的实例。

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) 
+0

啊,这使得分割它们更有意义。虽然你为什么不把“请求”传递给'app()'?我实际上不明白为什么请求需要通过,但我正在努力[这个例子](http://alexmic.net/flask-sqlalchemy-pytest/),它包括在内。 – 2015-02-10 23:14:14

+0

@JeffWidman我使用了新的'yield_fixture'而不是'fixture',所以我不需要在'request'上单独注册清理。对不起,如果这是令人困惑。 – davidism 2015-02-10 23:15:25

+0

哦,是的,我忘记了回调。谢谢! – 2015-02-10 23:18:43

相关问题