Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test a form submission with csrf token

When creating a new account, I redirect the user to the summary of his personal information.
But not redirected if validate_on_submit don't return True.

Validated if CSRF_TOKEN matched.

How to create and append a csrf_token in a test environment with pytest ?

This is my test:

@pytest.fixture
def client():
    app = create_app({"TESTING": True})

    with app.test_client() as cl:
        yield cl

def test_new_first(client):
    rv = client.post("/signup", data={
        "username": "John Doe",
        "email": "[email protected]",
        "password": "11111111",
    }, follow_redirects=True)

    assert b"Summary" in rv.data

The problem is: even that follow_redirects=True it stay on the signup page and "Summary" is not in rv.data.
I should put csrf_token in the data.

How can I generate a csrf_token ?

like image 622
Unviray Avatar asked Oct 24 '25 18:10

Unviray


1 Answers

I'm able to test my forms containing CSRF tokens based on the work of this gist. For convenience sake I added a generic post_csrf method:

# configure test_client to handle CSRF tokens properly
# according to https://gist.github.com/singingwolfboy/2fca1de64950d5dfed72

# Flask's assumptions about an incoming request don't quite match up with
# what the test client provides in terms of manipulating cookies, and the
# CSRF system depends on cookies working correctly. This little class is a
# fake request that forwards along requests to the test client for setting
# cookies.
class RequestShim(object):
    """
    A fake request that proxies cookie-related methods to a Flask test client.
    """
    def __init__(self, client):
        self.client = client
        self.vary = set({})

    def set_cookie(self, key, value='', *args, **kwargs):
        """Set the cookie on the Flask test client."""
        server_name = flask.current_app.config['SERVER_NAME'] or 'localhost'
        return self.client.set_cookie(
            server_name, key=key, value=value, *args, **kwargs
        )

    def delete_cookie(self, key, *args, **kwargs):
        """Delete the cookie on the Flask test client."""
        server_name = flask.current_app.config['SERVER_NAME'] or 'localhost'
        return self.client.delete_cookie(
            server_name, key=key, *args, **kwargs
        )


# We're going to extend Flask's built-in test client class, so that it knows
# how to look up CSRF tokens for you!
class FlaskClient(BaseFlaskClient):
    @property
    def csrf_token(self):
        # First, we'll wrap our request shim around the test client, so that
        # it will work correctly when Flask asks it to set a cookie.
        request = RequestShim(self)
        # Next, we need to look up any cookies that might already exist on
        # this test client, such as the secure cookie that powers `flask.session`,
        # and make a test request context that has those cookies in it.
        environ_overrides = {}
        self.cookie_jar.inject_wsgi(environ_overrides)
        with flask.current_app.test_request_context(
                '/auth/login', environ_overrides=environ_overrides,
            ):
            # Now, we call Flask-WTF's method of generating a CSRF token...
            csrf_token = generate_csrf()
            # ...which also sets a value in `flask.session`, so we need to
            # ask Flask to save that value to the cookie jar in the test
            # client. This is where we actually use that request shim we made!
            flask.current_app.session_interface.save_session(flask.current_app, flask.session, request)
            # And finally, return that CSRF token we got from Flask-WTF.
            return csrf_token

    # Feel free to define other methods on this test client. You can even
    # use the `csrf_token` property we just defined, like we're doing here!
    def login(self, username='test', password='test'):
        # use post_csrf instead of code of linked gist
        return self.post_csrf('/auth/login', username=username, password=password, remember_me=False)

    def logout(self):
        return self.get('/auth/logout', follow_redirects=True)


def post_csrf(self, url, **kwargs):
    """Generic post with csrf_token to test all form submissions of my flask app"""
    data = kwargs.pop("data", {})
    data["csrf_token"] = self.csrf_token
    follow_redirects = kwargs.pop("follow_redirects", True)

    return self.post(url, data=data, follow_redirects=follow_redirects, **kwargs)


@pytest.fixture
def app():
    """Create and configure a new app instance for each test."""
    app = create_app(TestConfig)
    app.test_client_class = FlaskClient
    
    # rest omitted for brevity


@pytest.fixture
def client(app):
    """A test client for the app."""
    return app.test_client()

A test then looks like this:

def test_remove_nonexisting_user_fails_gracefully(client):
    u = User(username='alice', password='pass')
    db.session.add(u)
    db.session.commit()

    client.login()
    response = client.post_csrf('/users/delete/bob')
    assert response.status_code == 200
    assert len(user.query.all()) == 1
    assert b'user bob not found' in response.data
like image 144
oschlueter Avatar answered Oct 26 '25 16:10

oschlueter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!