我是 Python 和 Flask 的新手,但我正在逐渐掌握它。我已经构建了一个应用程序,现在我想我应该开始一些单元测试。不过,我真的无法理解它。我已经阅读了各种文档、帖子和示例,但我似乎无法将其转移到我自己的代码中。我希望如果有人可以向我展示如何为我的一个功能编写测试,那么事情就会落实到位。在这个阶段很容易忽略它并继续构建我的应用程序。
@app.route('/user/<nickname>/create_bike', methods = ['GET', 'POST'] )
@login_required
def create_bike(nickname):
user = User.query.filter_by(nickname = nickname).first()
bikes = user.bikes.all()
bikecount = user.bikes.count()
form = CreateBike()
if form.validate_on_submit():
if bikecount < user.bike_allowance:
# let user create a bike
newbike = Bikes(bikename = form.bikename.data,
user_id = g.user.id, shared = SHARED )
db.session.add(newbike)
db.session.commit()
flash('Your new bike has been created')
return redirect(url_for('create_bike', nickname = nickname))
else:
flash("You have too many bikes")
return render_template('create_bike.html',
user = user,
form = form
)
更新 - 这是我的工作测试
def test_create_bike(self):
u = User(nickname = 'john', email = 'john@example.com', account_type = "tester")
db.session.add(u)
db.session.commit()
# login user
with self.app as c:
with c.session_transaction() as sess:
sess['user_id'] = int(u.get_id())
# http://pythonhosted.org/Flask-Login/#fresh-logins
sess['_fresh'] = True
rv = c.post('/user/john/create_bike', data = dict(
bikename = 'your new bike',
user_id = sess['user_id'],
shared = 1
), follow_redirects = True)
assert 'Your new bike has been created' in rv.data