我是新來的Python和燒瓶,但我正在逐漸掌握它。我到目前爲止已經構建了一個應用程序,現在我想我應該開始一些單元測試。儘管如此,我確實無法理解。我已閱讀各種文檔,帖子和示例,但我似乎無法將此轉換爲我自己的代碼。我希望如果有人能告訴我如何爲我的一項功能編寫測試,那麼事情就會落實到位。在這個階段非常有誘惑力,可以忽略它並按下我的應用程序。單元測試燒瓶功能(使用登錄用戶)
@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 = '[email protected]', 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
這確實是問題所在,我現在正在進行測試。謝謝你的回答。 – bobwal