python - Testing a POST that uses Flask-WTF validate_on_submit -


i stumped on testing post add category database i've used flask_wtf validation , csrf protection. crud operations pm website. i've used flask, flask_wtf , flask-sqlalchemy. first independent project, , find myself little @ lost on how test flask-wtform validate_on_submit function.

here's models:

class users(db.model):     id = db.column(db.integer, primary_key=true, unique=true)     name = db.column(db.string(80), nullable=false)     email = db.column(db.string(250), unique=true)  class category(db.model):     id = db.column(db.integer, primary_key=true, unique=true)     name = db.column(db.string(250), nullable=false, unique=true)     users_id = db.column(db.integer, db.foreignkey('users.id')) 

here's form:

class categoryform(form):     name = stringfield(         'name', [validators.length(min=4, max=250, message="name problem")]) 

and here's controller:

@category.route('/category/add', methods=['get', 'post']) @login_required def addcategory():     """ add new category.         returns: redirect home.     """     # initiate form.     form = categoryform()     # on post of valid form, add new category.     if form.validate_on_submit():         category = category(             form.name.data, login_session['users_id'])         db.session.add(category)         db.session.commit()         flash('new category %s created' % category.name)         return redirect(url_for('category.showhome'))     else:         # render form add category.         return render_template('newcategory.html', form=form) 

how write test if statement validate_on_submit function?

using py.test , conftest.py recommended delightful testing pytest , sqlalchemy, here's test confirms added category.

def test_add_category_post(app, session):     """does add category post 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)     app.test_client() c:         c.session_transaction() 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 new category assigned variable , used create form. form's data used in post.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo