我很难测试POST,在数据库中添加了一个类别,我已经使用Flask_WTF进行验证和CSRF保护。对于我的网站的CRUD操作。我使用过Flask,Flask_WTF和Flask-SQLAlchemy。这是我的第一个独立项目,我发现自己对如何测试Flask-WTForm validate_on_submit函数感到很遗憾。
以下是模型:
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'))
以下表格:
class CategoryForm(Form):
name = StringField(
'Name', [validators.Length(min=4, max=250, message="name problem")])
这是控制器:
@category.route('/category/add', methods=['GET', 'POST'])
@login_required
def addCategory():
""" Add a new category.
Returns: Redirect Home.
"""
# Initiate the form.
form = CategoryForm()
# On POST of a valid form, add the 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 Successfully Created' % category.name)
return redirect(url_for('category.showHome'))
else:
# Render the form to add the category.
return render_template('newCategory.html', form=form)
如何使用validate_on_submit函数编写if语句的测试?
答案 0 :(得分:2)
使用py {test和Delightful testing with pytest and SQLAlchemy推荐的conftest.py,这是一个确认添加类别的测试。
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()
请注意,新类别已分配给变量,然后用于创建表单。表格中的数据用于帖子中。
答案 1 :(得分:1)
您应该为应用程序配置不同的配置,具体取决于您是本地的/正在生产的/正在执行单元测试。您可以设置的一种配置是
WTF_CSRF_ENABLED = False