| 1 | import pytest |
| 2 | |
| 3 | from beaker.middleware import SessionMiddleware |
| 4 | from beaker import crypto |
| 5 | |
| 6 | webtest = pytest.importorskip("webtest") |
| 7 | |
| 8 | pytest.mark.skipif(not crypto.get_crypto_module('default').has_aes, |
| 9 | reason="No AES library is installed, can't test " + |
| 10 | "cookie-only Sessions") |
| 11 | |
| 12 | |
| 13 | def simple_app(environ, start_response): |
| 14 | session = environ['beaker.session'] |
| 15 | if 'value' not in session: |
| 16 | session['value'] = 0 |
| 17 | session['value'] += 1 |
| 18 | domain = environ.get('domain') |
| 19 | if domain: |
| 20 | session.domain = domain |
| 21 | if not environ['PATH_INFO'].startswith('/nosave'): |
| 22 | session.save() |
| 23 | start_response('200 OK', [('Content-type', 'text/plain')]) |
| 24 | msg = 'The current value is: %d and cookie is %s' % (session['value'], session) |
| 25 | return [msg.encode('utf-8')] |
| 26 | |
| 27 | |
| 28 | def test_increment(): |
| 29 | options = {'session.validate_key':'hoobermas', |
| 30 | 'session.type':'cookie'} |
| 31 | app = webtest.TestApp(SessionMiddleware(simple_app, **options)) |
| 32 | res = app.get('/') |
| 33 | assert 'current value is: 1' in res |
| 34 | |
| 35 | res = app.get('/', extra_environ=dict(domain='.hoop.com', |
| 36 | HTTP_HOST='www.hoop.com')) |
| 37 | assert 'current value is: 1' in res |
| 38 | assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] |
| 39 | |
| 40 | res = app.get('/', extra_environ=dict(HTTP_HOST='www.hoop.com')) |
| 41 | assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] |
| 42 | assert 'current value is: 2' in res |
| 43 | |
| 44 | |
| 45 | def test_cookie_attributes_are_preserved(): |
| 46 | options = {'session.type': 'memory', |
| 47 | 'session.httponly': True, |
| 48 | 'session.secure': True, |
| 49 | 'session.cookie_path': '/app', |
| 50 | 'session.cookie_domain': 'localhost'} |
| 51 | app = webtest.TestApp(SessionMiddleware(simple_app, **options)) |
| 52 | res = app.get('/app', extra_environ=dict( |
| 53 | HTTP_COOKIE='beaker.session.id=oldsessid', domain='.hoop.com')) |
| 54 | cookie = res.headers['Set-Cookie'] |
| 55 | assert 'domain=.hoop.com' in cookie.lower() |
| 56 | assert 'path=/app' in cookie.lower() |
| 57 | assert 'secure' in cookie.lower() |
| 58 | assert 'httponly' in cookie.lower() |
| 59 | assert 'samesite=lax' in cookie.lower() |
| 60 | |
| 61 | |
| 62 | if __name__ == '__main__': |
| 63 | from paste import httpserver |
| 64 | wsgi_app = SessionMiddleware(simple_app, {}) |
| 65 | httpserver.serve(wsgi_app, host='127.0.0.1', port=8080) |