Skip to content

Instantly share code, notes, and snippets.

@wolf0403
Created April 30, 2013 11:36
Show Gist options
  • Save wolf0403/5488165 to your computer and use it in GitHub Desktop.
Save wolf0403/5488165 to your computer and use it in GitHub Desktop.
Tornado AsyncHTTPTestCase client doesn't handle Cookies within itself thus can't be used to test session based scenarios. This code provides basic support for that.
TEST_URL='/resource'
LOGIN_URL='/login'
LOGOUT_URL='/logout'
application = tornado.web.Application([
(LOGIN_URL, LoginHandler),
(LOGOUT_URL, LogoutHandler),
(TEST_URL, ResourceHandler),
], cookie_secret='cookie_secret', login_url=LOGIN_URL)
class LoginTest(tornado.testing.AsyncHTTPTestCase):
def __init__(self, *rest):
self.cookies = Cookie.SimpleCookie()
tornado.testing.AsyncHTTPTestCase.__init__(self, *rest)
def get_app(self):
return application
def _update_cookies(self, headers):
'''
from
https://github.com/peterbe/tornado-utils/blob/master/tornado_utils/http_test_client.py
'''
try:
sc = headers['Set-Cookie']
cookies = escape.native_str(sc)
self.cookies.update(Cookie.SimpleCookie(cookies))
while True:
self.cookies.update(Cookie.SimpleCookie(cookies))
if ',' not in cookies:
break
cookies = cookies[cookies.find(',') + 1:]
except KeyError:
return
def setUp(self):
tornado.testing.AsyncHTTPTestCase.setUp(self)
resp = self.fetch(TEST_URL, follow_redirects=False)
self.assertEqual(302, resp.code) # redir to LOGIN_URL
def fetch(self, url, *r, **kw):
if 'follow_redirects' not in kw:
kw['follow_redirects'] = False
header = {}
hs = self.cookies.output()
if hs != '':
hs = hs.split(':')[1]
header['Cookie'] = hs
#print "URL: {}, Cookie: {}".format(url, header['Cookie'])
resp = tornado.testing.AsyncHTTPTestCase.fetch(self, url, headers=header, *r, **kw)
self._update_cookies(resp.headers)
return resp
def test_login(self):
resp = self.fetch(LOGIN_URL, method='POST', body=urllib.urlencode({'u' : 'user', 'p' : 'pass'}), follow_redirects=False)
self.assertEqual(200, resp.code)
resp = self.fetch(TEST_URL, follow_redirects=False)
self.assertEqual(200, resp.code)
resp = self.fetch(LOGOUT_URL, follow_redirects=False)
self.assertEqual(200, resp.code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment