| 1 | from beaker.middleware import SessionMiddleware |
| 2 | from unittest import SkipTest |
| 3 | try: |
| 4 | from webtest import TestApp as WebTestApp |
| 5 | except ImportError: |
| 6 | raise SkipTest("webtest not installed") |
| 7 | |
| 8 | def teardown_module(): |
| 9 | import shutil |
| 10 | shutil.rmtree('./cache', True) |
| 11 | |
| 12 | def simple_app(environ, start_response): |
| 13 | session = environ['beaker.session'] |
| 14 | domain = environ.get('domain') |
| 15 | if domain: |
| 16 | session.domain = domain |
| 17 | if 'value' not in session: |
| 18 | session['value'] = 0 |
| 19 | session['value'] += 1 |
| 20 | if not environ['PATH_INFO'].startswith('/nosave'): |
| 21 | session.save() |
| 22 | start_response('200 OK', [('Content-type', 'text/plain')]) |
| 23 | msg = 'The current value is: %s, session id is %s' % (session.get('value', 0), |
| 24 | session.id) |
| 25 | return [msg.encode('utf-8')] |
| 26 | |
| 27 | |
| 28 | def test_same_domain(): |
| 29 | options = {'session.data_dir':'./cache', |
| 30 | 'session.secret':'blah', |
| 31 | 'session.cookie_domain': '.hoop.com'} |
| 32 | app = WebTestApp(SessionMiddleware(simple_app, **options)) |
| 33 | res = app.get('/', extra_environ=dict(HTTP_HOST='subdomain.hoop.com')) |
| 34 | assert 'current value is: 1' in res |
| 35 | assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] |
| 36 | res = app.get('/', extra_environ=dict(HTTP_HOST='another.hoop.com')) |
| 37 | assert 'current value is: 2' in res |
| 38 | assert [] == res.headers.getall('Set-Cookie') |
| 39 | res = app.get('/', extra_environ=dict(HTTP_HOST='more.subdomain.hoop.com')) |
| 40 | assert 'current value is: 3' in res |
| 41 | |
| 42 | |
| 43 | def test_different_domain(): |
| 44 | options = {'session.data_dir':'./cache', |
| 45 | 'session.secret':'blah'} |
| 46 | app = WebTestApp(SessionMiddleware(simple_app, **options)) |
| 47 | res = app.get('/', extra_environ=dict(domain='.hoop.com', |
| 48 | HTTP_HOST='www.hoop.com')) |
| 49 | res = app.get('/', extra_environ=dict(domain='.hoop.co.uk', |
| 50 | HTTP_HOST='www.hoop.com')) |
| 51 | assert 'Domain=.hoop.co.uk' in res.headers['Set-Cookie'] |
| 52 | assert 'current value is: 2' in res |
| 53 | |
| 54 | res = app.get('/', extra_environ=dict(domain='.hoop.co.uk', |
| 55 | HTTP_HOST='www.test.com')) |
| 56 | assert 'current value is: 1' in res |
| 57 | |
| 58 | |
| 59 | if __name__ == '__main__': |
| 60 | from paste import httpserver |
| 61 | wsgi_app = SessionMiddleware(simple_app, {}) |
| 62 | httpserver.serve(wsgi_app, host='127.0.0.1', port=8080) |