2015-11-04 58 views
0

我该如何去测试我的应用程序是否已经在pythonic的请求中设置了cookie?我现在做的方式(工作)不会觉得很方便,但在这里它是:能够在测试环境中“干净地”访问cookie

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对我不起作用,因为它总是会返回一个空的字典。也许我做错了?

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 

回答

0

这个怎么样?使用app.test_client将让我们保持较长的上下文。

with app.test_client() as tc: 
    tc.get('/non-existing-path/') 
    assert 'mycookie' not in request.cookies 
    tc.get('/') 
    print request.cookies['mycookie'] 

另外,请给我们一个最小的例子,可以工作,以便我们可以重现这个问题。