Python 访问Cookie的能力“;“干净地”;在测试环境中
我将如何测试我的应用程序中的cookies,这些cookies是在请求过程中以类似pythonic的方式设置的?我目前的做法(有效)感觉不是很方便,但这里是:Python 访问Cookie的能力“;“干净地”;在测试环境中,python,cookies,flask,Python,Cookies,Flask,我将如何测试我的应用程序中的cookies,这些cookies是在请求过程中以类似pythonic的方式设置的?我目前的做法(有效)感觉不是很方便,但这里是: def test_mycookie(app, client): def getcookie(name): try: cookie = client.cookie_jar._cookies['mydomain.dev']['/'][name] except KeyError:
def test_mycookie(app, client):
def getcookie(name):
try:
cookie = client.cookie_jar._cookies['mydomain.dev']['/'][name]
except KeyError:
return None
else:
return cookie
with app.test_request_context():
client.get('/non-existing-path/')
assert getcookie('mycookie') is None
client.get('/')
assert getcookie('mycookie').value == '"xyz"'
使用flask.request.cookies
对我不起作用,因为它总是返回一个空的dict。也许我做错了
def test_mycookie2(app, client):
with app.test_request_context():
client.get('/non-existing-path/')
assert 'mycookie' not in request.cookies
client.get('/')
request.cookies['mycookie'] # Raises KeyError
这个怎么样?使用
app.test\u client
可以让我们将上下文保留更长的时间
with app.test_client() as tc:
tc.get('/non-existing-path/')
assert 'mycookie' not in request.cookies
tc.get('/')
print request.cookies['mycookie']
此外,请给我们一个最小的例子,可以工作,以便我们可以重现这个问题