diff --git a/.travis.yml b/.travis.yml index dfc32726..e363d0ad 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,4 +21,4 @@ python: install: - pip install -e .[testsuite] script: - - nosetests -v -d --with-coverage --cover-package=beaker + - pytest -vv diff --git a/beaker/cache.py b/beaker/cache.py index 5fe85a23..5a1ad6a4 100644 --- a/beaker/cache.py +++ b/beaker/cache.py @@ -176,7 +176,7 @@ def load(cls, search_term, limit, offset): :param region: String name of the region corresponding to the desired caching arguments, established in :attr:`.cache_regions`. - :param \*args: Optional ``str()``-compatible arguments which will uniquely + :param *args: Optional ``str()``-compatible arguments which will uniquely identify the key used by this decorated function, in addition to the positional arguments passed to the function itself at call time. This is recommended as it is needed to distinguish between any two functions diff --git a/beaker/util.py b/beaker/util.py index cb818954..fcb9912e 100644 --- a/beaker/util.py +++ b/beaker/util.py @@ -50,7 +50,7 @@ def skip_if(predicate, reason=None): """Skip a test if predicate is true.""" reason = reason or predicate.__name__ - from nose import SkipTest + from unittest import SkipTest def decorate(fn): fn_name = fn.__name__ diff --git a/setup.cfg b/setup.cfg index f5fc244a..9fea0244 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,7 +2,7 @@ #tag_build = dev #tag_svn_revision = false -[nosetests] +[tool:pytest] where=tests verbose=True detailed-errors=True diff --git a/setup.py b/setup.py index c0263731..efe063c0 100644 --- a/setup.py +++ b/setup.py @@ -23,7 +23,7 @@ INSTALL_REQUIRES.append('funcsigs') -TESTS_REQUIRE = ['nose', 'Mock', 'pycryptodome'] +TESTS_REQUIRE = ['pytest', 'Mock', 'pycryptodome'] if py_version == (2, 6): TESTS_REQUIRE.append('WebTest<2.0.24') @@ -94,7 +94,7 @@ 'cryptography': ['cryptography'], 'testsuite': [TESTS_REQUIRE] }, - test_suite='nose.collector', + test_suite='tests', tests_require=TESTS_REQUIRE, entry_points=""" [paste.filter_factory] diff --git a/tests/test_cache.py b/tests/test_cache.py index 4c6f4ebe..cbdb92c0 100644 --- a/tests/test_cache.py +++ b/tests/test_cache.py @@ -10,15 +10,15 @@ from beaker.middleware import CacheMiddleware from beaker import util from beaker.cache import Cache -from nose import SkipTest +from unittest import SkipTest from beaker.util import skip_if import base64 import zlib try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: - TestApp = None + WebTestApp = None # Tarballs of the output of: # >>> from beaker.cache import Cache @@ -202,9 +202,9 @@ def create_func(): assert 'howdy' == cache.get_value('key2', createfunc=create_func) assert called == {} -@skip_if(lambda: TestApp is None, "webtest not installed") +@skip_if(lambda: WebTestApp is None, "webtest not installed") def test_increment(): - app = TestApp(CacheMiddleware(simple_app)) + app = WebTestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.type':type, 'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') @@ -212,9 +212,9 @@ def test_increment(): res = app.get('/') assert 'current value is: 3' in res -@skip_if(lambda: TestApp is None, "webtest not installed") +@skip_if(lambda: WebTestApp is None, "webtest not installed") def test_cache_manager(): - app = TestApp(CacheMiddleware(cache_manager_app)) + app = WebTestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res @@ -300,6 +300,6 @@ def _test_upgrade_setitem(dir): assert cache['foo'] == 'bar' -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) diff --git a/tests/test_cache_decorator.py b/tests/test_cache_decorator.py index 5de944d7..7dc09c44 100644 --- a/tests/test_cache_decorator.py +++ b/tests/test_cache_decorator.py @@ -1,14 +1,13 @@ import time from datetime import datetime -import beaker.cache as cache from beaker.cache import CacheManager, cache_region, region_invalidate from beaker import util -from nose import SkipTest +from unittest import SkipTest defaults = {'cache.data_dir':'./cache', 'cache.type':'dbm', 'cache.expire': 2} -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) diff --git a/tests/test_cachemanager.py b/tests/test_cachemanager.py index 493d0084..a8a98176 100644 --- a/tests/test_cachemanager.py +++ b/tests/test_cachemanager.py @@ -8,7 +8,7 @@ defaults = {'cache.data_dir':'./cache', 'cache.type':'dbm', 'cache.expire': 2} -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) @@ -58,7 +58,7 @@ def test_parse_doesnt_allow_empty_region_name(): def test_decorators(): for func in (make_region_cached_func, make_cached_func): - yield check_decorator, func() + check_decorator(func()) def check_decorator(func): result = func('Fred') @@ -119,7 +119,7 @@ def test_long_name(): name = 'Fred' * 250 result = func(name) assert name in result - + result2 = func(name) assert result == result2 # This won't actually invalidate it since the key won't be sha'd @@ -127,7 +127,7 @@ def test_long_name(): result3 = func(name) assert result3 == result2 - + # And now this should invalidate it _cache_obj.invalidate(func, 'loader', name) result4 = func(name) @@ -217,4 +217,4 @@ def load_with_str_expire(person): msg3 = load_with_str_expire('fred') assert msg == msg2, (msg, msg2) - assert msg2 != msg3, (msg2, msg3) \ No newline at end of file + assert msg2 != msg3, (msg2, msg3) diff --git a/tests/test_container.py b/tests/test_container.py index 45bd5634..8480fbd8 100644 --- a/tests/test_container.py +++ b/tests/test_container.py @@ -1,6 +1,11 @@ import os +import pickle import random +import shutil +import sys import time +import pytest + from beaker.container import * from beaker.synchronization import _synchronizers from beaker.cache import clsmap @@ -34,10 +39,10 @@ def run(self): if threadlocal: localvalue = Value( - 'test', - cls('test', data_dir='./cache'), - createfunc=CachedWidget, - expiretime=expiretime, + 'test', + cls('test', data_dir='./cache'), + createfunc=CachedWidget, + expiretime=expiretime, starttime=starttime) localvalue.clear_value() else: @@ -60,10 +65,10 @@ def run(self): if not threadlocal: value = Value( - 'test', - cls('test', data_dir='./cache'), - createfunc=CachedWidget, - expiretime=expiretime, + 'test', + cls('test', data_dir='./cache'), + createfunc=CachedWidget, + expiretime=expiretime, starttime=starttime) value.clear_value() else: @@ -124,6 +129,9 @@ def test_file_container_3(): def test_file_container_tlocal(): test_file_container(expiretime=15, delay=2, threadlocal=True) + +@pytest.mark.skipif(sys.version_info < (3, 6), + reason="Cryptography not supported on Python 3 lower than 3.6") def test_file_open_bug(): """ensure errors raised during reads or writes don't lock the namespace open.""" @@ -137,35 +145,29 @@ def test_file_open_bug(): f.write("BLAH BLAH BLAH") f.close() - # TODO: do we have an assertRaises() in nose to use here ? - try: + with pytest.raises(pickle.UnpicklingError): value.set_value("y") - assert False - except: - pass _synchronizers.clear() value = Value('test', clsmap['file']('reentrant_test', data_dir='./cache')) # TODO: do we have an assertRaises() in nose to use here ? - try: + with pytest.raises(pickle.UnpicklingError): value.set_value("z") - assert False - except: - pass def test_removing_file_refreshes(): """test that the cache doesn't ignore file removals""" x = [0] + def create(): x[0] += 1 return x[0] - value = Value('test', - clsmap['file']('refresh_test', data_dir='./cache'), + value = Value('test', + clsmap['file']('refresh_test', data_dir='./cache'), createfunc=create, starttime=time.time() ) if os.path.exists(value.namespace.file): @@ -176,6 +178,5 @@ def create(): assert value.get_value() == 2 -def teardown(): - import shutil +def teardown_module(): shutil.rmtree('./cache', True) diff --git a/tests/test_cookie_domain_only.py b/tests/test_cookie_domain_only.py index 800da7fd..711e7115 100644 --- a/tests/test_cookie_domain_only.py +++ b/tests/test_cookie_domain_only.py @@ -1,23 +1,18 @@ -import re -import os +import pytest -import beaker.session from beaker.middleware import SessionMiddleware -from nose import SkipTest +from beaker import crypto -try: - from webtest import TestApp -except ImportError: - raise SkipTest("webtest not installed") +webtest = pytest.importorskip("webtest") + +pytest.mark.skipif(not crypto.get_crypto_module('default').has_aes, + reason="No AES library is installed, can't test " + + "cookie-only Sessions") -from beaker import crypto -if not crypto.get_crypto_module('default').has_aes: - raise SkipTest("No AES library is installed, can't test cookie-only " - "Sessions") def simple_app(environ, start_response): session = environ['beaker.session'] - if not session.has_key('value'): + if 'value' not in session: session['value'] = 0 session['value'] += 1 domain = environ.get('domain') @@ -33,7 +28,7 @@ def simple_app(environ, start_response): def test_increment(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = webtest.TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res @@ -53,7 +48,7 @@ def test_cookie_attributes_are_preserved(): 'session.secure': True, 'session.cookie_path': '/app', 'session.cookie_domain': 'localhost'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = webtest.TestApp(SessionMiddleware(simple_app, **options)) res = app.get('/app', extra_environ=dict( HTTP_COOKIE='beaker.session.id=oldsessid', domain='.hoop.com')) cookie = res.headers['Set-Cookie'] diff --git a/tests/test_cookie_expires.py b/tests/test_cookie_expires.py index 3423dadd..890155ce 100644 --- a/tests/test_cookie_expires.py +++ b/tests/test_cookie_expires.py @@ -1,6 +1,5 @@ from beaker.middleware import SessionMiddleware from beaker.session import Session -from nose.tools import * import datetime import re @@ -18,7 +17,7 @@ def app(*args, **kw): datetime.timedelta(minutes=5), now] expected = [datetime.timedelta(seconds=300), - datetime.timedelta(seconds=300), + datetime.timedelta(seconds=300), True, True, True, True, False, False, False, False, datetime.timedelta(minutes=5), now] @@ -31,7 +30,7 @@ def app(*args, **kw): val = s.options['cookie_expires'] except: val = None - assert_equal(val, expected[pos]) + assert val == expected[pos] def cookie_expiration(session): diff --git a/tests/test_cookie_only.py b/tests/test_cookie_only.py index e30c11e2..a93557a6 100644 --- a/tests/test_cookie_only.py +++ b/tests/test_cookie_only.py @@ -1,6 +1,6 @@ -import datetime, time +import datetime +import time import re -import os import json import beaker.session @@ -8,9 +8,9 @@ from beaker.session import SignedCookie from beaker._compat import b64decode from beaker.middleware import SessionMiddleware -from nose import SkipTest +from unittest import SkipTest try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: raise SkipTest("webtest not installed") @@ -21,7 +21,7 @@ def simple_app(environ, start_response): session = environ['beaker.session'] - if not session.has_key('value'): + if 'value' not in session: session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): @@ -32,7 +32,7 @@ def simple_app(environ, start_response): def test_increment(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -43,7 +43,7 @@ def test_increment(): def test_invalid_cookie(): # This is not actually a cookie only session, but we still test the cookie part. options = {'session.validate_key':'hoobermas'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res @@ -59,7 +59,7 @@ def test_invalid_cookie(): def test_invalid_cookie_cookietype(): # This is not actually a cookie only session, but we still test the cookie part. options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res @@ -74,7 +74,7 @@ def test_invalid_cookie_cookietype(): def test_json_serializer(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': 'json'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res @@ -91,7 +91,7 @@ def test_json_serializer(): def test_pickle_serializer(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': 'pickle'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res @@ -119,7 +119,7 @@ def dumps(self, data): serializer = CustomSerializer() options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'data_serializer': serializer} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res @@ -139,15 +139,15 @@ def dumps(self, data): def test_expires(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie', 'session.cookie_expires': datetime.timedelta(days=1)} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'expires=' in res.headers.getall('Set-Cookie')[0] assert 'current value is: 1' in res def test_different_sessions(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) - app2 = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) + app2 = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') @@ -161,7 +161,7 @@ def test_different_sessions(): def test_nosave(): options = {'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/nosave') assert 'current value is: 1' in res assert [] == res.headers.getall('Set-Cookie') @@ -177,7 +177,7 @@ def test_nosave(): def test_increment_with_encryption(): options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -188,8 +188,8 @@ def test_increment_with_encryption(): def test_different_sessions_with_encryption(): options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) - app2 = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) + app2 = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') @@ -204,7 +204,7 @@ def test_different_sessions_with_encryption(): def test_nosave_with_encryption(): options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/nosave') assert 'current value is: 1' in res assert [] == res.headers.getall('Set-Cookie') @@ -220,7 +220,7 @@ def test_nosave_with_encryption(): def test_cookie_id(): options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert "_id':" in res @@ -239,7 +239,7 @@ def invalidate_session_app(environ, start_response): options = {'session.encrypt_key':'666a19cf7f61c64c', 'session.validate_key':'hoobermas', 'session.type':'cookie'} - app = TestApp(SessionMiddleware(invalidate_session_app, **options)) + app = WebTestApp(SessionMiddleware(invalidate_session_app, **options)) res = app.get('/') assert 'expires=' not in res.headers.getall('Set-Cookie')[0] @@ -252,7 +252,7 @@ def test_changing_encrypt_key_with_timeout(): 'session.timeout': 300, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'The current value is: 1' in res, res @@ -264,7 +264,7 @@ def test_changing_encrypt_key_with_timeout(): 'session.timeout': 300, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', headers={'Cookie': cookies}) assert 'The current value is: 2' in res, res @@ -274,7 +274,7 @@ def test_changing_encrypt_key_with_timeout(): 'session.timeout': 300, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', headers={'Cookie': cookies}) # Let's check it created a new session as the old one is invalid @@ -289,7 +289,7 @@ def test_cookie_properly_expires(): 'session.timeout': 1, 'session.validate_key': 'hoobermas', 'session.type': 'cookie'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'The current value is: 1' in res, res @@ -308,7 +308,7 @@ def test_cookie_attributes_are_preserved(): 'session.httponly': True, 'session.secure': True, 'session.samesite': 'Strict'} - app = TestApp(SessionMiddleware(simple_app, options)) + app = WebTestApp(SessionMiddleware(simple_app, options)) res = app.get('/') cookie = res.headers['Set-Cookie'] assert 'secure' in cookie.lower() @@ -324,7 +324,7 @@ def test_cookie_path_properly_set_after_init(): 'session.type': 'cookie', 'session.cookie_path': COOKIE_PATH, } - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/app') cookie = res.headers['Set-Cookie'] @@ -339,7 +339,7 @@ def test_cookie_path_properly_set_after_load(): 'session.type': 'cookie', 'session.cookie_path': COOKIE_PATH, } - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) # Perform one request to set the cookie res = app.get('/app') # Perform another request to load the previous session from the cookie @@ -363,7 +363,7 @@ def delete_session_app(environ, start_response): 'session.type': 'cookie', 'session.cookie_path': COOKIE_PATH, } - app = TestApp(SessionMiddleware(delete_session_app, **options)) + app = WebTestApp(SessionMiddleware(delete_session_app, **options)) res = app.get('/app') cookie = res.headers['Set-Cookie'] diff --git a/tests/test_database.py b/tests/test_database.py index 47cc1119..202cac52 100644 --- a/tests/test_database.py +++ b/tests/test_database.py @@ -4,12 +4,12 @@ from beaker.cache import clsmap, Cache, util from beaker.exceptions import InvalidCacheBackendError from beaker.middleware import CacheMiddleware -from nose import SkipTest +from unittest import SkipTest try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: - TestApp = None + WebTestApp = None try: @@ -57,30 +57,30 @@ def test_has_key(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value("test", o) - assert cache.has_key("test") assert "test" in cache - assert not cache.has_key("foo") + assert "test" in cache + assert "foo" not in cache assert "foo" not in cache cache.remove_value("test") - assert not cache.has_key("test") + assert "test" not in cache def test_has_key_multicache(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value("test", o) - assert cache.has_key("test") + assert "test" in cache assert "test" in cache cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') - assert cache.has_key("test") + assert "test" in cache cache.remove_value('test') def test_clear(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') o = object() cache.set_value("test", o) - assert cache.has_key("test") + assert "test" in cache cache.clear() - assert not cache.has_key("test") + assert "test" not in cache def test_unicode_keys(): cache = Cache('test', data_dir='./cache', url=db_url, type='ext:database') @@ -91,9 +91,9 @@ def test_unicode_keys(): cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_increment(): - app = TestApp(CacheMiddleware(simple_app)) + app = WebTestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') @@ -101,9 +101,9 @@ def test_increment(): res = app.get('/') assert 'current value is: 3' in res -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_cache_manager(): - app = TestApp(CacheMiddleware(cache_manager_app)) + app = WebTestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res diff --git a/tests/test_domain_setting.py b/tests/test_domain_setting.py index da7d2930..8e0cc782 100644 --- a/tests/test_domain_setting.py +++ b/tests/test_domain_setting.py @@ -1,14 +1,11 @@ -import re -import os - from beaker.middleware import SessionMiddleware -from nose import SkipTest +from unittest import SkipTest try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: raise SkipTest("webtest not installed") -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) @@ -17,7 +14,7 @@ def simple_app(environ, start_response): domain = environ.get('domain') if domain: session.domain = domain - if not session.has_key('value'): + if 'value' not in session: session['value'] = 0 session['value'] += 1 if not environ['PATH_INFO'].startswith('/nosave'): @@ -32,7 +29,7 @@ def test_same_domain(): options = {'session.data_dir':'./cache', 'session.secret':'blah', 'session.cookie_domain': '.hoop.com'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', extra_environ=dict(HTTP_HOST='subdomain.hoop.com')) assert 'current value is: 1' in res assert 'Domain=.hoop.com' in res.headers['Set-Cookie'] @@ -46,7 +43,7 @@ def test_same_domain(): def test_different_domain(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/', extra_environ=dict(domain='.hoop.com', HTTP_HOST='www.hoop.com')) res = app.get('/', extra_environ=dict(domain='.hoop.co.uk', diff --git a/tests/test_increment.py b/tests/test_increment.py index 7d374abb..bcfabbd2 100644 --- a/tests/test_increment.py +++ b/tests/test_increment.py @@ -1,15 +1,14 @@ import re -import os +import unittest from beaker.middleware import SessionMiddleware -from nose import SkipTest try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: - raise SkipTest("webtest not installed") + raise unittest.SkipTest("webtest not installed") -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) @@ -60,7 +59,7 @@ def simple_auto_app(environ, start_response): def test_no_save(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(no_save_app, **options)) + app = WebTestApp(SessionMiddleware(no_save_app, **options)) res = app.get('/') assert 'current value is: None' in res assert [] == res.headers.getall('Set-Cookie') @@ -68,7 +67,7 @@ def test_no_save(): def test_increment(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -78,7 +77,7 @@ def test_increment(): def test_increment_auto(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) + app = WebTestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -89,8 +88,8 @@ def test_increment_auto(): def test_different_sessions(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_app, **options)) - app2 = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) + app2 = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') @@ -104,8 +103,8 @@ def test_different_sessions(): def test_different_sessions_auto(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) - app2 = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) + app = WebTestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) + app2 = WebTestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) res = app.get('/') assert 'current value is: 1' in res res = app2.get('/') @@ -119,7 +118,7 @@ def test_different_sessions_auto(): def test_nosave(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/nosave') assert 'current value is: 1' in res res = app.get('/nosave') @@ -132,7 +131,7 @@ def test_nosave(): def test_revert(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) + app = WebTestApp(SessionMiddleware(simple_auto_app, auto=True, **options)) res = app.get('/nosave') assert 'current value is: 0' in res res = app.get('/nosave') @@ -152,7 +151,7 @@ def test_revert(): def test_load_session_by_id(): options = {'session.data_dir':'./cache', 'session.secret':'blah'} - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -161,7 +160,7 @@ def test_load_session_by_id(): old_id = re.sub(r'^.*?session id is (\S+)$', r'\1', res.body.decode('utf-8'), re.M) # Clear the cookies and do a new request - app = TestApp(SessionMiddleware(simple_app, **options)) + app = WebTestApp(SessionMiddleware(simple_app, **options)) res = app.get('/') assert 'current value is: 1' in res diff --git a/tests/test_managers/base.py b/tests/test_managers/base.py index 815c104e..3f1fd9ed 100644 --- a/tests/test_managers/base.py +++ b/tests/test_managers/base.py @@ -9,7 +9,7 @@ from beaker._compat import u_ from beaker.cache import Cache from beaker.middleware import SessionMiddleware, CacheMiddleware -from webtest import TestApp +from webtest import TestApp as WebTestApp class CacheManagerBaseTests(unittest.TestCase): @@ -99,7 +99,7 @@ def setUp(self): Cache('test', **self.CACHE_ARGS).clear() def test_session(self): - app = TestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS)) + app = WebTestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -108,13 +108,13 @@ def test_session(self): assert 'current value is: 3' in res def test_session_invalid(self): - app = TestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS)) + app = WebTestApp(SessionMiddleware(self.simple_session_app, **self.CACHE_ARGS)) res = app.get('/invalid', headers=dict( Cookie='beaker.session.id=df7324911e246b70b5781c3c58328442; Path=/')) assert 'current value is: 2' in res def test_session_timeout(self): - app = TestApp(SessionMiddleware(self.simple_session_app, timeout=1, **self.CACHE_ARGS)) + app = WebTestApp(SessionMiddleware(self.simple_session_app, timeout=1, **self.CACHE_ARGS)) session = app.app._get_session() session.save() @@ -197,7 +197,7 @@ def test_spaces_in_keys(self): assert 42 == cache.get_value("hasspace") def test_increment(self): - app = TestApp(CacheMiddleware(self.simple_app)) + app = WebTestApp(CacheMiddleware(self.simple_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 1' in res res = app.get('/') @@ -205,7 +205,7 @@ def test_increment(self): res = app.get('/') assert 'current value is: 3' in res - app = TestApp(CacheMiddleware(self.simple_app)) + app = WebTestApp(CacheMiddleware(self.simple_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 1' in res res = app.get('/') @@ -214,13 +214,13 @@ def test_increment(self): assert 'current value is: 3' in res def test_cache_manager(self): - app = TestApp(CacheMiddleware(self.cache_manager_app)) + app = WebTestApp(CacheMiddleware(self.cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res def test_store_none(self): - app = TestApp(CacheMiddleware(self.using_none_app)) + app = WebTestApp(CacheMiddleware(self.using_none_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 10' in res res = app.get('/') diff --git a/tests/test_memcached.py b/tests/test_memcached.py index 1895a79e..7cdb7dd2 100644 --- a/tests/test_memcached.py +++ b/tests/test_memcached.py @@ -2,34 +2,32 @@ from beaker._compat import u_ import mock -import os -from beaker.cache import clsmap, Cache, CacheManager, util +from beaker.cache import Cache, CacheManager, util from beaker.middleware import CacheMiddleware, SessionMiddleware from beaker.exceptions import InvalidCacheBackendError from beaker.util import parse_cache_config_options -from nose import SkipTest import unittest try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: - TestApp = None + WebTestApp = None try: from beaker.ext import memcached client = memcached._load_client() except InvalidCacheBackendError: - raise SkipTest("an appropriate memcached backend is not installed") + raise unittest.SkipTest("an appropriate memcached backend is not installed") mc_url = '127.0.0.1:11211' c =client.Client([mc_url]) c.set('x', 'y') if not c.get('x'): - raise SkipTest("Memcached is not running at %s" % mc_url) + raise unittest.SkipTest("Memcached is not running at %s" % mc_url) -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) @@ -122,9 +120,9 @@ def cache_manager_app(environ, start_response): )).encode('utf-8') -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_session(): - app = TestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url)) + app = WebTestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url)) res = app.get('/') assert 'current value is: 1' in res res = app.get('/') @@ -133,9 +131,9 @@ def test_session(): assert 'current value is: 3' in res -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_session_invalid(): - app = TestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url)) + app = WebTestApp(SessionMiddleware(simple_session_app, data_dir='./cache', type='ext:memcached', url=mc_url)) res = app.get('/invalid', headers=dict(Cookie='beaker.session.id=df7324911e246b70b5781c3c58328442; Path=/')) assert 'current value is: 2' in res @@ -230,9 +228,9 @@ def test_spaces_in_keys(): assert cache.has_key("hasspace") assert 42 == cache.get_value("hasspace") -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_increment(): - app = TestApp(CacheMiddleware(simple_app)) + app = WebTestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 1' in res.text res = app.get('/') @@ -240,7 +238,7 @@ def test_increment(): res = app.get('/') assert 'current value is: 3' in res.text - app = TestApp(CacheMiddleware(simple_app)) + app = WebTestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 1' in res res = app.get('/') @@ -248,16 +246,16 @@ def test_increment(): res = app.get('/') assert 'current value is: 3' in res -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_cache_manager(): - app = TestApp(CacheMiddleware(cache_manager_app)) + app = WebTestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res.text assert 'test_key cleared' in res.text -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_store_none(): - app = TestApp(CacheMiddleware(using_none_app)) + app = WebTestApp(CacheMiddleware(using_none_app)) res = app.get('/', extra_environ={'beaker.clear':True}) assert 'current value is: 10' in res.text res = app.get('/') @@ -286,8 +284,8 @@ def reserve(self): def test_uses_pylibmc_client(self): from beaker.ext import memcached - cache = Cache('test', data_dir='./cache', - memcache_module='pylibmc', + cache = Cache('test', data_dir='./cache', + memcache_module='pylibmc', url=mc_url, type="ext:memcached") assert isinstance(cache.namespace, memcached.PyLibMCNamespaceManager) @@ -301,7 +299,7 @@ def test_dont_use_pylibmc_client(self): assert isinstance(cache.namespace, memcached.MemcachedNamespaceManager) def test_client(self): - cache = Cache('test', data_dir='./cache', url=mc_url, type="ext:memcached", + cache = Cache('test', data_dir='./cache', url=mc_url, type="ext:memcached", protocol='binary') o = object() cache.set_value("test", o) @@ -314,22 +312,22 @@ def test_client(self): def test_client_behaviors(self): config = { - 'cache.lock_dir':'./lock', - 'cache.data_dir':'./cache', - 'cache.type':'ext:memcached', + 'cache.lock_dir':'./lock', + 'cache.data_dir':'./cache', + 'cache.type':'ext:memcached', 'cache.url':mc_url, - 'cache.memcache_module':'pylibmc', - 'cache.protocol':'binary', - 'cache.behavior.ketama': 'True', - 'cache.behavior.cas':False, + 'cache.memcache_module':'pylibmc', + 'cache.protocol':'binary', + 'cache.behavior.ketama': 'True', + 'cache.behavior.cas':False, 'cache.behavior.receive_timeout':'3600', - 'cache.behavior.send_timeout':1800, + 'cache.behavior.send_timeout':1800, 'cache.behavior.tcp_nodelay':1, 'cache.behavior.auto_eject':"0" } cache_manager = CacheManager(**parse_cache_config_options(config)) cache = cache_manager.get_cache('test_behavior', expire=6000) - + with cache.namespace.pool.reserve() as mc: assert "ketama" in mc.behaviors assert mc.behaviors["ketama"] == 1 diff --git a/tests/test_namespacing.py b/tests/test_namespacing.py index 93deed71..005b5bf7 100644 --- a/tests/test_namespacing.py +++ b/tests/test_namespacing.py @@ -2,7 +2,7 @@ import sys -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) diff --git a/tests/test_session.py b/tests/test_session.py index 468cd26c..49c3fb28 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -8,13 +8,13 @@ import unittest import warnings -from nose import SkipTest, with_setup +import pytest from beaker.container import MemoryNamespaceManager from beaker.crypto import get_crypto_module from beaker.exceptions import BeakerException from beaker.session import CookieSession, Session, SessionObject -from beaker.util import assert_raises, deserialize +from beaker.util import deserialize def get_session(**kwargs): @@ -25,6 +25,8 @@ def get_session(**kwargs): COOKIE_REQUEST = {} + + def setup_cookie_request(): COOKIE_REQUEST.clear() @@ -38,8 +40,8 @@ def get_cookie_session(**kwargs): return CookieSession(COOKIE_REQUEST, **options) -@with_setup(setup_cookie_request) def test_session(): + setup_cookie_request() for test_case in ( check_save_load, check_save_load_encryption, @@ -50,9 +52,9 @@ def test_session(): check_invalidate, check_timeout, ): - for session_getter in (get_session, get_cookie_session,): + for session_getter in (get_session, get_cookie_session,): setup_cookie_request() - yield test_case, session_getter + test_case(session_getter) def check_save_load(session_getter): @@ -73,10 +75,9 @@ def check_save_load(session_getter): assert session[u_('Deutchland')] == u_('Sebastian Vettel') +@pytest.mark.skipif(not get_crypto_module('default').has_aes) def check_save_load_encryption(session_getter): """Test if the data is actually persistent across requests""" - if not get_crypto_module('default').has_aes: - raise SkipTest() session = session_getter(encrypt_key='666a19cf7f61c64c', validate_key='hoobermas') session[u_('Suomi')] = u_('Kimi Räikkönen') @@ -95,15 +96,15 @@ def check_save_load_encryption(session_getter): assert session[u_('Deutchland')] == u_('Sebastian Vettel') +# cryptography only works for py3.3+, so skip for python 3.2 +@pytest.mark.skipif(sys.version_info[0] == 3 and sys.version_info[1] < 3, + reason="Cryptography not supported on Python 3 lower than 3.3") def check_save_load_encryption_cryptography(session_getter): """Test if the data is actually persistent across requests""" - # cryptography only works for py3.3+, so skip for python 3.2 - if sys.version_info[0] == 3 and sys.version_info[1] < 3: - raise SkipTest("Cryptography not supported on Python 3 lower than 3.3") try: get_crypto_module('cryptography').has_aes except BeakerException: - raise SkipTest() + raise unittest.SkipTest() session = session_getter( encrypt_key='666a19cf7f61c64c', validate_key='hoobermas', @@ -126,10 +127,9 @@ def check_save_load_encryption_cryptography(session_getter): assert session[u_('Deutchland')] == u_('Sebastian Vettel') +@pytest.mark.skipif(not get_crypto_module('default').has_aes) def check_decryption_failure(session_getter): """Test if the data fails without the right keys""" - if not get_crypto_module('default').has_aes: - raise SkipTest() session = session_getter(encrypt_key='666a19cf7f61c64c', validate_key='hoobermas') session[u_('Suomi')] = u_('Kimi Räikkönen') @@ -196,10 +196,10 @@ def check_invalidate(session_getter): assert u_('Deutchland') not in session -@with_setup(setup_cookie_request) def test_regenerate_id(): """Test :meth:`Session.regenerate_id`""" # new session & save + setup_cookie_request() session = get_session() orig_id = session.id session[u_('foo')] = u_('bar') @@ -260,44 +260,42 @@ def check_timeout(session_getter): assert u_('Deutchland') not in session -@with_setup(setup_cookie_request) def test_timeout_requires_accessed_time(): """Test that it doesn't allow setting save_accessed_time to False with timeout enabled """ + setup_cookie_request() get_session(timeout=None, save_accessed_time=True) # is ok get_session(timeout=None, save_accessed_time=False) # is ok - assert_raises(BeakerException, - get_session, - timeout=2, - save_accessed_time=False) + with pytest.raises(BeakerException): + get_session(timeout=2, save_accessed_time=False) -@with_setup(setup_cookie_request) def test_cookies_enabled(): """ Test if cookies are sent out properly when ``use_cookies`` is set to ``True`` """ + setup_cookie_request() session = get_session(use_cookies=True) assert 'cookie_out' in session.request - assert session.request['set_cookie'] == False + assert not session.request['set_cookie'] session.domain = 'example.com' session.path = '/example' - assert session.request['set_cookie'] == True + assert session.request['set_cookie'] assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] assert 'Domain=example.com' in session.request['cookie_out'] assert 'Path=/' in session.request['cookie_out'] session = get_session(use_cookies=True) session.save() - assert session.request['set_cookie'] == True + assert session.request['set_cookie'] assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] session = get_session(use_cookies=True, id=session.id) session.delete() - assert session.request['set_cookie'] == True + assert session.request['set_cookie'] assert 'beaker.session.id=%s' % session.id in session.request['cookie_out'] assert 'expires=' in session.request['cookie_out'] @@ -310,6 +308,7 @@ def test_cookies_enabled(): class ShowWarning(object): def __init__(self): self.msg = None + def __call__(self, message, category, filename, lineno, file=None, line=None): self.msg = str(message) orig_sw = warnings.showwarning @@ -324,6 +323,7 @@ def __call__(self, message, category, filename, lineno, file=None, line=None): assert 'httponly' in cookie, cookie warnings.showwarning = orig_sw + def test_cookies_disabled(): """ Test that no cookies are sent when ``use_cookies`` is set to ``False`` @@ -345,12 +345,12 @@ def test_cookies_disabled(): assert 'cookie_out' not in session.request -@with_setup(setup_cookie_request) def test_file_based_replace_optimization(): """Test the file-based backend with session, which includes the 'replace' optimization. """ + setup_cookie_request() session = get_session(use_cookies=False, type='file', data_dir='./cache') @@ -390,8 +390,8 @@ def test_file_based_replace_optimization(): assert 'test' not in session.namespace session.namespace.do_close() -@with_setup(setup_cookie_request) def test_use_json_serializer_without_encryption_key(): + setup_cookie_request() so = get_session(use_cookies=False, type='file', data_dir='./cache', data_serializer='json') so['foo'] = 'bar' so.save() @@ -404,10 +404,10 @@ def test_use_json_serializer_without_encryption_key(): assert 'foo' in data -@with_setup(setup_cookie_request) def test_invalidate_corrupt(): + setup_cookie_request() session = get_session(use_cookies=False, type='file', - data_dir='./cache') + data_dir='./cache') session['foo'] = 'bar' session.save() @@ -415,12 +415,9 @@ def test_invalidate_corrupt(): f.write("crap") f.close() - assert_raises( - (pickle.UnpicklingError, EOFError, TypeError, binascii.Error), - get_session, - use_cookies=False, type='file', - data_dir='./cache', id=session.id - ) + with pytest.raises((pickle.UnpicklingError, EOFError, TypeError, binascii.Error,)): + get_session(use_cookies=False, type='file', + data_dir='./cache', id=session.id) session = get_session(use_cookies=False, type='file', invalidate_corrupt=True, @@ -428,8 +425,8 @@ def test_invalidate_corrupt(): assert "foo" not in dict(session) -@with_setup(setup_cookie_request) def test_invalidate_empty_cookie(): + setup_cookie_request() kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' @@ -440,8 +437,8 @@ def test_invalidate_empty_cookie(): assert "foo" not in dict(session) -@with_setup(setup_cookie_request) def test_unrelated_cookie(): + setup_cookie_request() kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' @@ -452,8 +449,8 @@ def test_unrelated_cookie(): assert "foo" in dict(session) -@with_setup(setup_cookie_request) def test_invalidate_invalid_signed_cookie(): + setup_cookie_request() kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' @@ -465,16 +462,12 @@ def test_invalidate_invalid_signed_cookie(): COOKIE_REQUEST['cookie_out'][25:] ) - assert_raises( - BeakerException, - get_cookie_session, - id=session.id, - invalidate_corrupt=False, - ) + with pytest.raises(BeakerException): + get_cookie_session(id=session.id, invalidate_corrupt=False) -@with_setup(setup_cookie_request) def test_invalidate_invalid_signed_cookie_invalidate_corrupt(): + setup_cookie_request() kwargs = {'validate_key': 'test_key', 'encrypt_key': 'encrypt'} session = get_cookie_session(**kwargs) session['foo'] = 'bar' @@ -489,6 +482,7 @@ def test_invalidate_invalid_signed_cookie_invalidate_corrupt(): session = get_cookie_session(id=session.id, invalidate_corrupt=True, **kwargs) assert "foo" not in dict(session) + class TestSaveAccessedTime(unittest.TestCase): # These tests can't use the memory session type since it seems that loading # winds up with references to the underlying storage and makes changes to @@ -517,7 +511,6 @@ def test_saves_if_session_written_and_accessed_time_false(self): '%r is not greater than %r' % (session.last_accessed, last_accessed)) - def test_saves_if_session_not_written_and_accessed_time_true(self): session = get_session(data_dir='./cache', save_accessed_time=True) # New sessions are treated a little differently so save the session @@ -535,7 +528,6 @@ def test_saves_if_session_not_written_and_accessed_time_true(self): '%r is not greater than %r' % (session.last_accessed, last_accessed)) - def test_doesnt_save_if_session_not_written_and_accessed_time_false(self): session = get_session(data_dir='./cache', save_accessed_time=False) # New sessions are treated a little differently so save the session diff --git a/tests/test_sqla.py b/tests/test_sqla.py index 2667b15d..d3ae5aaf 100644 --- a/tests/test_sqla.py +++ b/tests/test_sqla.py @@ -3,12 +3,12 @@ from beaker.cache import clsmap, Cache, util from beaker.exceptions import InvalidCacheBackendError from beaker.middleware import CacheMiddleware -from nose import SkipTest +from unittest import SkipTest try: - from webtest import TestApp + from webtest import TestApp as WebTestApp except ImportError: - TestApp = None + WebTestApp = None try: clsmap['ext:sqla']._init_dependencies() @@ -102,9 +102,9 @@ def test_unicode_keys(): cache.remove_value(u_('hiŏ')) assert u_('hiŏ') not in cache -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_increment(): - app = TestApp(CacheMiddleware(simple_app)) + app = WebTestApp(CacheMiddleware(simple_app)) res = app.get('/', extra_environ={'beaker.clear': True}) assert 'current value is: 1' in res res = app.get('/') @@ -112,9 +112,9 @@ def test_increment(): res = app.get('/') assert 'current value is: 3' in res -@util.skip_if(lambda: TestApp is None, "webtest not installed") +@util.skip_if(lambda: WebTestApp is None, "webtest not installed") def test_cache_manager(): - app = TestApp(CacheMiddleware(cache_manager_app)) + app = WebTestApp(CacheMiddleware(cache_manager_app)) res = app.get('/') assert 'test_key is: test value' in res assert 'test_key cleared' in res diff --git a/tests/test_synchronizer.py b/tests/test_synchronizer.py index 32369c73..6bae038d 100644 --- a/tests/test_synchronizer.py +++ b/tests/test_synchronizer.py @@ -3,7 +3,7 @@ # TODO: spawn threads, test locking. -def teardown(): +def teardown_module(): import shutil shutil.rmtree('./cache', True) diff --git a/tests/test_unicode_cache_keys.py b/tests/test_unicode_cache_keys.py index daf53949..9f81672d 100644 --- a/tests/test_unicode_cache_keys.py +++ b/tests/test_unicode_cache_keys.py @@ -1,14 +1,16 @@ # coding: utf-8 -"""If we try to use a character not in ascii range as a cache key, we get an -unicodeencode error. See +"""If we try to use a character not in ascii range as a cache key, we get an +unicodeencode error. See https://bitbucket.org/bbangert/beaker/issue/31/cached-function-decorators-break-when-some for more on this """ -from nose.tools import * from beaker._compat import u_ from beaker.cache import CacheManager +def eq_(a, b, msg=''): + assert a == b, msg + memory_cache = CacheManager(type='memory') @memory_cache.cache('foo') @@ -47,11 +49,11 @@ def test_B_replacing_non_ascii(): the function distinguishes between the two it should not return the past value """ - assert_false(foo(u_('Espaáol'))==u_('Español')) + assert foo(u_('Espaáol')) != u_('Español') eq_(foo(u_('Espaáol')), u_('Espaáol')) def test_C_more_unicode(): - """We again test the same stuff but this time we use + """We again test the same stuff but this time we use http://tools.ietf.org/html/draft-josefsson-idn-test-vectors-00#section-5 as keys""" keys = [