jarus / flask-testing

Unittest extensions for Flask
http://pythonhosted.org/Flask-Testing/
Other
501 stars 110 forks source link

Logging In #63

Closed samcraigjohnson closed 10 years ago

samcraigjohnson commented 10 years ago

I attempted to follow a workflow with logging in as described in the Flask testing documentation . It seems to not be persisting the user login. I am not sure if this has to do with the scoped sessions or perhaps some trick that I am not aware of.

My '/login' endpoint works normally when running the server. API calls are being executed with the @login_required decorator during functional testing, but using this framework I am unable to test my @login_required calls. Let me know if I am missing something. Thanks

joehand commented 10 years ago

@sjohnson540 I figured this out after much frustration. I don't know your specifics, but there were a couple key points:

All together, my login stuff looked like:

from flask.testing import FlaskClient
from flask_fillin import FormWrapper

def setUp(self):
    ...
    self.app = self.create_app()
    self.client = FlaskClient(self.app, response_wrapper=FormWrapper)
    ...

def _login(self, email=None, password=None):
    r = self.get('/login')
    if len(r.forms):
        self.csrf_token = r.form.fields['csrf_token']
    email = email or self.user.email
    password = password or 'password'
    return self.post('/login', data={'email': email, 'password': password},
                         follow_redirects=True)

Then when you want to login: self._login(). And it works!

samcraigjohnson commented 10 years ago

@joehand thanks for the help! I actually figured out that Flask-WTF (I am using for my form submission) has a config option that allows to turn off CSRF for testing which ended up fixing my problem.