Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask login_user doesn't work with pytest

I'm new to Pytest. I want to test my views which require login (decorated with @login_required).
I have following test function:

def test_add_new_post(self, client, user):
    login_user(user)
    assert current_user == user
    data = {
        'title': 'This is test post',
        'body': 'This is test body'
    }
    client.post(url_for('posts.add_new'), data=data)
    assert Post.query.count() == 1

where the client is:

@pytest.fixture(scope='session')
def client(request, app):
    return app.test_client()

The assert current_user == user returns True, but the client.post returns the login page, because the login_required redirects to a login page. Why is this happening and what is the correct way of doing this?

like image 372
moriesta Avatar asked Dec 07 '14 08:12

moriesta


1 Answers

This worked for me (based on this comment):

def test_with_authenticated_user(app):
    @app.login_manager.request_loader
    def load_user_from_request(request):
        return User.query.first()
    # now you can call client.post or similar methods
like image 86
dusan Avatar answered Oct 08 '22 10:10

dusan