Accessing Flask test client session in pytest test when using an app factory Accessing Flask test client session in pytest test when using an app factory flask flask

Accessing Flask test client session in pytest test when using an app factory


The problem is with the way you use your test client.

First of all you don't have to create your client fixture. If you use pytest-flask, it offers a client fixture to use. If you still want to use your own client though (maybe because you don't want pytest-flask), your client fixture should act as a context processor to wrap your requests around.

So you need something like the following:

def test_value_set_in_session(client):    with client:        client.get('/set')        assert 'key' in session

information of the day: pytest-flask has a similar client fixture to yours. The difference is that pytest-flask uses a context manager to give you a client and that saves you 1 line per test

@pytest.yield_fixturedef client(app):    """A Flask test client. An instance of :class:`flask.testing.TestClient`    by default.    """    with app.test_client() as client:        yield client

your test with pytest-flask client

def test_value_set_in_session(client):    client.get('/set')    assert 'key' in session


Take a look at the following from conftest.py in cookiecutter-flask. It may give you some ideas.

@pytest.yield_fixture(scope='function')def app():    """An application for the tests."""    _app = create_app(TestConfig)    ctx = _app.test_request_context()    ctx.push()    yield _app    ctx.pop()@pytest.fixture(scope='function')def testapp(app):    """A Webtest app."""    return TestApp(app)