Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port testing from nose to pytest. #192

Merged
merged 6 commits into from
Jul 30, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ python:
install:
- pip install -e .[testsuite]
script:
- nosetests -v -d --with-coverage --cover-package=beaker
- pytest -vv
2 changes: 1 addition & 1 deletion beaker/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion beaker/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__
Expand Down
2 changes: 1 addition & 1 deletion setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#tag_build = dev
#tag_svn_revision = false

[nosetests]
[tool:pytest]
where=tests
verbose=True
detailed-errors=True
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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]
Expand Down
16 changes: 8 additions & 8 deletions tests/test_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -202,19 +202,19 @@ 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('/')
assert 'current value is: 2' in res
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
Expand Down Expand Up @@ -300,6 +300,6 @@ def _test_upgrade_setitem(dir):
assert cache['foo'] == 'bar'


def teardown():
def teardown_module():
import shutil
shutil.rmtree('./cache', True)
5 changes: 2 additions & 3 deletions tests/test_cache_decorator.py
Original file line number Diff line number Diff line change
@@ -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)

Expand Down
10 changes: 5 additions & 5 deletions tests/test_cachemanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -119,15 +119,15 @@ 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
_cache_obj.invalidate(func, 'loader', name, key_length=8000)

result3 = func(name)
assert result3 == result2

# And now this should invalidate it
_cache_obj.invalidate(func, 'loader', name)
result4 = func(name)
Expand Down Expand Up @@ -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)
assert msg2 != msg3, (msg2, msg3)
43 changes: 22 additions & 21 deletions tests/test_container.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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."""

Expand All @@ -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):
Expand All @@ -176,6 +178,5 @@ def create():
assert value.get_value() == 2


def teardown():
import shutil
def teardown_module():
shutil.rmtree('./cache', True)
25 changes: 10 additions & 15 deletions tests/test_cookie_domain_only.py
Original file line number Diff line number Diff line change
@@ -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')
Expand All @@ -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

Expand All @@ -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']
Expand Down
5 changes: 2 additions & 3 deletions tests/test_cookie_expires.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from beaker.middleware import SessionMiddleware
from beaker.session import Session
from nose.tools import *
import datetime
import re

Expand All @@ -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]
Expand All @@ -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):
Expand Down
Loading