pytest-dev / pytest-flask

A set of pytest fixtures to test Flask applications
http://pytest-flask.readthedocs.org/en/latest/
MIT License
485 stars 90 forks source link

how to testing flask-login? #40

Open tanyewei opened 8 years ago

tanyewei commented 8 years ago

how to testing flask-login?

vitalk commented 8 years ago

What do you mean?

On Mon, 25 Jan 2016 5:38 am tanyewei notifications@github.com wrote:

how to testing flask-login?

— Reply to this email directly or view it on GitHub https://github.com/vitalk/pytest-flask/issues/40.

SBillion commented 8 years ago

I guess he has trouble with cookies because client doesn't have the expected scope. You can use a fixture to make an authentication and call this fixture in all your test functions for an authenticated user

vitalk commented 8 years ago

trouble with cookies because client doesn't have the expected scope

What is the expected scope? You can always explicitly create required scope by passing any headers into the client. Example of using get_auth_token method from Flask-Login documentation:

@pytest.fixture
def user():
    """Should return an user instance."""

@pytest.fixture
def credentials(user):
    return [('Authentication', user.get_auth_token())]

def test_endpoint(client, credentials):
    res = client.get(url_for('endpoint'), headers=credentials)
vitalk commented 8 years ago

If there's nothing else I'm closing this issue. @tanyewei feel free to reopen it.

tmehlinger commented 8 years ago

I suspect he's having trouble with login_user.

Say you have a fixture like this:

@pytest.fixture
def logged_in_user(request, test_user):
    flask_login.login_user(test_user)
    request.addfinalizer(flask_login.logout_user)

And a test like this:

@pytest.mark.usefixtures('logged_in_user')
def test_protected(client):
    resp = client.get('/protected')
    assert resp.status_code == 401

Because the pytest-flask test client pushes a new context, the flask_login.current_user proxy ends up returning the anonymous user and any tests that expect a logged-in user fail.

vitalk commented 8 years ago

@tmehlinger thank you for clarifications.

For now request context has been pushed to ensure the url_for can be used inside tests without any configuration. The same feature can be achieved if the SERVER_NAME is set and application context has been pushed. If this behaviour is appropriate and doesn't break anything, then your issue can be fixed.

tmehlinger commented 8 years ago

@vitalk, you're welcome. :)

@tanyewei, the way I would solve your problem is by disabling authentication when you're running unit tests. You could run any tests that explicitly require login functionality with a live application server using the live_server fixture.

hackrole commented 8 years ago

hi, everybody. I am facing the same problem. @tmehlinger . do you mean disable the view's auth while testing? to me this is really unexcepted. I sometime need to query something in the view throught the user id. for example get the user's order-list. annoy user would pass the view any way!!!

@vitalk, I am not really got what you mean. but I find that, use client.post('login') would work. but login_user(user) fails. I am new to flask, really confuse now. the false code: 2016-06-17-12 20 56-screenshot

the success code: 2016-06-17-12 21 12-screenshot

vitalk commented 8 years ago

Hi @hackrole!

As mentioned above, the client fixture pushes a new request context, so the 1st example doesn’t work because the current_user is anonymous. The alternate approach is explicitly pass propper headers to client (as per https://github.com/vitalk/pytest-flask/issues/40#issuecomment-184774553)

matt-sm commented 7 years ago

As of flask-login release 0.4.0 the get_auth_token() function has been removed.

shepherdjay commented 5 years ago

Struggling with this as well - Is there a method or setup I can do to make sure the client does a post to the login part of our site such as client_authenticated

doanguyen commented 5 years ago

Hi guys,

I was also struggling with testing with authenticated user for flask-login, and here is my working snippet:

@pytest.fixture()
def test_with_authenticated_user(app):
    @login_manager.request_loader
    def load_user_from_request(request):
        return User.query.first()
zoltan-fedor commented 5 years ago

I was struggling with this too. My solution ended up being to dynamically overwrite the login_manager.request_loader and returning the user I want to be authenticated when calling the protected endpoint.

def test_authentication(app, client):
    with app.test_request_context():
        test_user = User.get(username=USERS['testuser']['username'])

        @app.login_manager.request_loader
        def load_user_from_request(request):
            return test_user

        resp = client.get('/auth/request-token/')

WARNING: Be careful with this approach if you share the app between multiple tests - like when you are using a fixture with scope session, as the overwritten login_manager.request_loader will not get reset. One of my tests was failing somewhat randomly when using pytest-xdist and it took me a while to realize that it is due to the 'residual' of the login_manager.request_loader

In the end when I wanted to do an unauthenticated call after overwriting the '@app.login_manager.request_loader' to return the test user, I needed to overwrite it again, so it doesn't return anything, making it work for the unauthenticated user scenario:

    @app.login_manager.request_loader
    def load_user_from_request(request):
        return None
stevenmanton commented 5 years ago

I did something similar to @zoltan-fedor but with a slight twist. Here are the relevant parts:


@pytest.fixture
def app():
    app = create_app('TestConfig')
    with app.app_context():
        yield app

@pytest.fixture
def authenticated_request(app):
    with app.test_request_context():
        # Here we're not overloading the login manager, we're just directly logging in a user
        # with whatever parameters we want. The user should only be logged in for the test,
        # so you're not polluting the other tests.
        yield flask_login.login_user(User('a', 'username', 'c', 'd'))

@pytest.mark.usefixtures("authenticated_request")
def test_empty_predicates():
    # The logic of your test goes here
johndiego commented 4 years ago

Someone solutions? I 'm same problem!! =(

libremente commented 4 years ago

Hi all, since I am struggling with the issue as well, which is the best way to approach it? I need to test some features which are available just to some user levels so disabling auth is a no go for me. Thanks!

avikam commented 4 years ago

The way I understand the guidelines, as documented here, the suggested approach (don't know if it's the best one) was already mentioned by @stevenmanton

Namely, if this is your view:

@login_required
def secured_view():
    arg = request.get_json()['arg']
    ...

your test would, within a request context, manually log in a user and then call the view function

def test_secured_view():
    with app.test_request_context("route", json={"arg": "val"}):
        flask_login.login_user(User(...))
        secured_view()

unfortunately, you can't use the client fixture because it simulates a full request, meaning you can't control the request context it generates. Hope that helps.

shlomiLan commented 4 years ago

I can't get this to work. I want to run my test like a regular user (see only the user data, denied access to some views). Usually, I use:

from slots_tracker_server import app as flask_app

@pytest.fixture(scope="session", autouse=True)
def client():
    flask_client = flask_app.test_client()

to initialize my app and DB.

Why cann't I use something like:

flask_login.login_user(Users.objects().first())

or

flask_client.login_user(Users.objects().first())

in order to simulate a user?

also, I'm using

@app.before_request

in order to force most views to be protected.

can you please help? thanks.

jab commented 3 years ago

I hit this too, in tests trying to simulate an AJAX client that first hits a GET /csrf endpoint to fetch a CSRF token that it then includes in a CSRF header when making the desired request. To work around this, I ended up creating my own client fixture with a longer scope (e.g. "module" or "session" both work) rather than using pytest-flask, which doesn't currently allow customization of its client fixture's scope. In case this helps anyone else!

dongweiming commented 2 years ago

The fixture scope mentioned by @jab is the cause of the incorrect login status.

I have a complete example here, the problem lies in the cleanup work done in the app fixture:

@pytest.fixture
def app():
    print('Hit')
    _app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'

    with _app.app_context():
        db.create_all()
    yield _app

    os.remove('test.db')

In this case, the default fixture scope is 'function', which means that each test case will be re-executed once, If you use pytest -s, you can see that Hit is output three times, which is equal to the number of test cases, that is, each case is executed once.

So that the database is rebuilt , the data created in other places is lost, so the user cannot be queried here, so the status is not logged in yet.

To fix it, just modify the value of a larger scope, such as session, package or module:

@pytest.fixture(scope='package')
#@pytest.fixture
def app():
    _app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'

    with _app.app_context():
        db.create_all()
    yield _app

    os.remove('test.db')
Colelyman commented 1 month ago

This ended up working for me:

@pytest.fixture(scope='function')
def admin_client(app, db):
    with app.test_request_context(), app.test_client() as _admin_context:
        admin = User(
            name='Test Admin',
            username='test_admin',
            email='test@example.com',
            role='Admin',
        )
        db.session.add(admin)
        db.session.commit()

        login_user(admin)

        yield _admin_context

        logout_user()

This gives you a context where the admin user is signed in.