【发布时间】:2016-04-01 06:21:11
【问题描述】:
我正在尝试使用烧瓶客户端测试烧瓶应用程序。
我的应用路由处理如下
@app.route('/', methods=['post', 'get'])
@app.route('/index', methods=['post', 'get'])
def index():
login_form = LoginForm(request.form)
logout_form = LogoutForm(request.form)
short_url_form = ShortURLForm(request.form)
if request.method == 'POST' and short_url_form.validate():
url = short_url_form.url.data
url_shortener_handler = urlShortener()
app.logger.debug('in post method to shorten Url(%s)', url)
# TODO have a mechanism for handling duplicate key error
short_url = url_shortener_handler.generateShortUrl()
if url_shortener_handler.saveUrl(short_url, url):
app.logger.debug('value of short url(%s) for url is (%s)', short_url, url)
return render_template('index.html',
login_form=login_form,
logout_form=logout_form,
shorturl_form=short_url_form,
shortURL=SITE_URL + '/' + short_url)
else:
app.logger.critical('Error in saving short url(%s) for url is (%s)', short_url, url)
flash('Internal error try again')
return render_template('index.html',
login_form=login_form,
logout_form=logout_form,
shorturl_form=short_url_form,
shortURL=None)
而short_url_form定义如下
class ShortURLForm(Form):
url = StringField('url', validators=[url(), data_required()])
submit = SubmitField('Shorten')
def __init__(self, *args, **kwargs):
Form.__init__(self, *args, **kwargs)
def validate(self):
""" performs validation of input """
if not Form.validate(self):
return False
return True
我正在使用测试用例进行如下测试
class TestBasicUrlShortener(unittest.TestCase):
def setUp(self):
self.client = app.test_client()
self.baseURL = 'http://localhost:5000'
def create_app(self):
""" this is one of the functions that must be implemented for flask testing. """
app = Flask(__name__)
app.config['TESTING'] = True
app.config['WTF_CSRF_ENABLED'] = False
WTF_CSRF_ENABLED = False
app.debug = True
self.baseURL = 'http://localhost:5000'
return app
当我使用客户端发送发布请求时,我收到 400 个错误请求。
def test_post_to_urlshortener(self):
""" When we send a post we expect it to return a output
containing the baseURL and short url """
# monkeypatch the generate shortURL so that we know
# the correct value to expect and perform validation
# accordingly
from app.models import urlshortener
urlshortener.urlShortener.generateShortUrl = self.generate_shortURL
data = dict(url='http://www.google.com/', submit='Shorten')
rv = self.client.post('/',
data=data,
follow_redirects=False)
print rv
self.assertEqual(rv.status_code, 200)
shorturl = self.baseURL + '/' + self.generate_shortURL()
# print rv.data
assert shorturl in str(rv.data)
# cleanup so next time it works
urlshort = urlshortener.urlShortener()
urlshort.removeUrl(self.generate_shortURL())
代码在我使用浏览器测试时有效,测试和浏览器中唯一缺少的参数是 csrf 令牌。但是我使用配置禁用了 csrf 保护(希望如此)
欢迎任何有助于缩小问题范围的指针。
【问题讨论】:
-
我没有看到你打电话给
create_app。您确定不使用您的全局应用吗? -
这有点道理。您能否展示一个在测试客户端中使用它来覆盖全局应用程序的小示例
标签: python flask flask-wtforms