Testing a POST that uses Flask-WTF validate_on_submit

You should have different configurations for your app, depending if you are local / in production / executing unit tests. One configuration you can set is

WTF_CSRF_ENABLED = False

See flask-wtforms documentation.


Using py.test and a conftest.py recommended by Delightful testing with pytest and SQLAlchemy, here's a test that confirms the added category.

def test_add_category_post(app, session):
    """Does add category post a new category?"""
    TESTEMAIL = "[email protected]"
    TESTUSER = "Joe Test"
    user = Users.query.filter(Users.email==TESTEMAIL).first()
    category = Category(name="Added Category", users_id=user.id)
    form = CategoryForm(formdata=None, obj=category)
    with app.test_client() as c:
        with c.session_transaction() as sess:
            sess['email'] = TESTEMAIL
            sess['username'] = TESTUSER 
            sess['users_id'] = user.id
            response = c.post(
                '/category/add', data=form.data, follow_redirects=True)
    assert response.status_code == 200
    added_category = Category.query.filter(
        Category.name=="Added Category").first()
    assert added_category
    session.delete(added_category)
    session.commit()

Note that the new category is assigned to a variable and then used to create a form. The form's data is used in the post.