Testing a POST that uses Flask-WTF validate_on_submit

后端 未结 2 494
误落风尘
误落风尘 2021-01-18 00:26

I am stumped on testing a POST to add a category to the database where I\'ve used Flask_WTF for validation and CSRF protection. For the CRUD operations pm my website. I\'ve

相关标签:
2条回答
  • 2021-01-18 01:12

    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.

    0 讨论(0)
  • 2021-01-18 01:16

    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 = "test@test.org"
        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.

    0 讨论(0)
提交回复
热议问题