Commit 8a14ac45 authored by Jason Madden's avatar Jason Madden

100% coverage for the test_* files.

parent da42abf4
...@@ -7,3 +7,4 @@ exclude_lines = ...@@ -7,3 +7,4 @@ exclude_lines =
class I[A-Z]\w+\((Interface|I[A-Z].*)\): class I[A-Z]\w+\((Interface|I[A-Z].*)\):
raise NotImplementedError raise NotImplementedError
raise AssertionError raise AssertionError
if __name__ == '__main__':
...@@ -57,9 +57,9 @@ class TestPList(unittest.TestCase): ...@@ -57,9 +57,9 @@ class TestPList(unittest.TestCase):
uu1 = pl(u1) uu1 = pl(u1)
uu2 = pl(u2) uu2 = pl(u2)
v = pl(tuple(u)) pl(tuple(u))
v0 = pl(OtherList(u0)) pl(OtherList(u0))
vv = pl("this is also a sequence") pl("this is also a sequence")
# Test __repr__ # Test __repr__
eq = self.assertEqual eq = self.assertEqual
...@@ -68,46 +68,48 @@ class TestPList(unittest.TestCase): ...@@ -68,46 +68,48 @@ class TestPList(unittest.TestCase):
eq(repr(u1), repr(l1), "repr(u1) == repr(l1)") eq(repr(u1), repr(l1), "repr(u1) == repr(l1)")
# Test __cmp__ and __len__ # Test __cmp__ and __len__
try:
if PYTHON2: cmp
def mycmp(a, b): except NameError:
r = cmp(a, b) def cmp(a, b):
if r < 0: return -1 if a == b:
if r > 0: return 1 return 0
return r if a < b:
return -1
all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2] return 1
for a in all:
for b in all: def mycmp(a, b):
eq(mycmp(a, b), mycmp(len(a), len(b)), r = cmp(a, b)
"mycmp(a, b) == mycmp(len(a), len(b))") if r < 0:
return -1
if r > 0:
return 1
return r
to_test = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2]
for a in to_test:
for b in to_test:
eq(mycmp(a, b), mycmp(len(a), len(b)),
"mycmp(a, b) == mycmp(len(a), len(b))")
# Test __getitem__ # Test __getitem__
for i in range(len(u2)): for i, val in enumerate(u2):
eq(u2[i], i, "u2[i] == i") eq(val, i, "u2[i] == i")
# Test __setitem__ # Test __setitem__
uu2[0] = 0 uu2[0] = 0
uu2[1] = 100 uu2[1] = 100
try: with self.assertRaises(IndexError):
uu2[2] = 200 uu2[2] = 200
except IndexError:
pass
else:
raise TestFailed("uu2[2] shouldn't be assignable")
# Test __delitem__ # Test __delitem__
del uu2[1] del uu2[1]
del uu2[0] del uu2[0]
try: with self.assertRaises(IndexError):
del uu2[0] del uu2[0]
except IndexError:
pass
else:
raise TestFailed("uu2[0] shouldn't be deletable")
# Test __getslice__ # Test __getslice__
...@@ -198,12 +200,8 @@ class TestPList(unittest.TestCase): ...@@ -198,12 +200,8 @@ class TestPList(unittest.TestCase):
eq(u2.index(0), 0, "u2.index(0) == 0") eq(u2.index(0), 0, "u2.index(0) == 0")
eq(u2.index(1), 1, "u2.index(1) == 1") eq(u2.index(1), 1, "u2.index(1) == 1")
try: with self.assertRaises(ValueError):
u2.index(2) u2.index(2)
except ValueError:
pass
else:
raise TestFailed("expected ValueError")
# Test reverse # Test reverse
...@@ -220,23 +218,19 @@ class TestPList(unittest.TestCase): ...@@ -220,23 +218,19 @@ class TestPList(unittest.TestCase):
eq(u, u2, "u == u2") eq(u, u2, "u == u2")
# Test keyword arguments to sort # Test keyword arguments to sort
if PYTHON2: if PYTHON2: # pragma: no cover
u.sort(cmp=lambda x,y: cmp(y, x)) u.sort(cmp=lambda x, y: cmp(y, x))
eq(u, [1, 0], "u == [1, 0]") eq(u, [1, 0], "u == [1, 0]")
u.sort(key=lambda x:-x) u.sort(key=lambda x: -x)
eq(u, [1, 0], "u == [1, 0]") eq(u, [1, 0], "u == [1, 0]")
u.sort(reverse=True) u.sort(reverse=True)
eq(u, [1, 0], "u == [1, 0]") eq(u, [1, 0], "u == [1, 0]")
# Passing any other keyword arguments results in a TypeError # Passing any other keyword arguments results in a TypeError
try: with self.assertRaises(TypeError):
u.sort(blah=True) u.sort(blah=True)
except TypeError:
pass
else:
raise TestFailed("expected TypeError")
# Test extend # Test extend
...@@ -256,8 +250,7 @@ class TestPList(unittest.TestCase): ...@@ -256,8 +250,7 @@ class TestPList(unittest.TestCase):
def test_suite(): def test_suite():
return unittest.makeSuite(TestPList) return unittest.defaultTestLoader.loadTestsFromName(__name__)
if __name__ == "__main__": if __name__ == '__main__':
loader = unittest.TestLoader() unittest.main()
unittest.main(testLoader=loader)
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
############################################################################## ##############################################################################
import unittest import unittest
# pylint:disable=blacklisted-name, protected-access
class Test_default(unittest.TestCase): class Test_default(unittest.TestCase):
...@@ -25,15 +25,14 @@ class Test_default(unittest.TestCase): ...@@ -25,15 +25,14 @@ class Test_default(unittest.TestCase):
return self._getTargetClass()(func) return self._getTargetClass()(func)
def test___get___from_class(self): def test___get___from_class(self):
_called_with = []
def _test(inst): def _test(inst):
_called_with.append(inst) raise AssertionError("Must not be caled")
return '_test'
descr = self._makeOne(_test) descr = self._makeOne(_test)
class Foo(object): class Foo(object):
testing = descr testing = descr
self.assertTrue(Foo.testing is descr) self.assertIs(Foo.testing, descr)
self.assertEqual(_called_with, [])
def test___get___from_instance(self): def test___get___from_instance(self):
_called_with = [] _called_with = []
...@@ -86,9 +85,9 @@ class PersistentMappingTests(unittest.TestCase): ...@@ -86,9 +85,9 @@ class PersistentMappingTests(unittest.TestCase):
def __init__(self, initmapping): def __init__(self, initmapping):
self.__data = initmapping self.__data = initmapping
def items(self): def items(self):
return self.__data.items() raise AssertionError("Not called")
v0 = self._makeOne(OtherMapping(u0)) self._makeOne(OtherMapping(u0))
vv = self._makeOne([(0, 0), (1, 1)]) self._makeOne([(0, 0), (1, 1)])
# Test __repr__ # Test __repr__
eq = self.assertEqual eq = self.assertEqual
...@@ -97,24 +96,37 @@ class PersistentMappingTests(unittest.TestCase): ...@@ -97,24 +96,37 @@ class PersistentMappingTests(unittest.TestCase):
eq(repr(u1), repr(l1), "repr(u1) == repr(l1)") eq(repr(u1), repr(l1), "repr(u1) == repr(l1)")
# Test __cmp__ and __len__ # Test __cmp__ and __len__
try:
if PYTHON2: cmp
def mycmp(a, b): except NameError:
r = cmp(a, b) def cmp(a, b):
if r < 0: return -1 if a == b:
if r > 0: return 1 return 0
return r if hasattr(a, 'items'):
a = sorted(a.items())
all = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2] b = sorted(b.items())
for a in all: if a < b:
for b in all: return -1
eq(mycmp(a, b), mycmp(len(a), len(b)), return 1
"mycmp(a, b) == mycmp(len(a), len(b))")
def mycmp(a, b):
r = cmp(a, b)
if r < 0:
return -1
if r > 0:
return 1
return r
to_test = [l0, l1, l2, u, u0, u1, u2, uu, uu0, uu1, uu2]
for a in to_test:
for b in to_test:
eq(mycmp(a, b), mycmp(len(a), len(b)),
"mycmp(a, b) == mycmp(len(a), len(b))")
# Test __getitem__ # Test __getitem__
for i in range(len(u2)): for i, val in enumerate(u2):
eq(u2[i], i, "u2[i] == i") eq(val, i, "u2[i] == i")
# Test get # Test get
...@@ -136,12 +148,8 @@ class PersistentMappingTests(unittest.TestCase): ...@@ -136,12 +148,8 @@ class PersistentMappingTests(unittest.TestCase):
del uu2[1] del uu2[1]
del uu2[0] del uu2[0]
try: with self.assertRaises(KeyError):
del uu2[0] del uu2[0]
except KeyError:
pass
else:
raise TestFailed("uu2[0] shouldn't be deletable")
# Test __contains__ # Test __contains__
for i in u2: for i in u2:
...@@ -176,12 +184,8 @@ class PersistentMappingTests(unittest.TestCase): ...@@ -176,12 +184,8 @@ class PersistentMappingTests(unittest.TestCase):
eq(x, 1, "u2.pop(1) == 1") eq(x, 1, "u2.pop(1) == 1")
self.assertTrue(1 not in u2, "1 not in u2") self.assertTrue(1 not in u2, "1 not in u2")
try: with self.assertRaises(KeyError):
u2.pop(1) u2.pop(1)
except KeyError:
pass
else:
self.fail("1 should not be poppable from u2")
x = u2.pop(1, 7) x = u2.pop(1, 7)
eq(x, 7, "u2.pop(1, 7) == 7") eq(x, 7, "u2.pop(1, 7) == 7")
...@@ -230,8 +234,4 @@ class Test_legacy_PersistentDict(unittest.TestCase): ...@@ -230,8 +234,4 @@ class Test_legacy_PersistentDict(unittest.TestCase):
def test_suite(): def test_suite():
return unittest.TestSuite(( return unittest.defaultTestLoader.loadTestsFromName(__name__)
unittest.makeSuite(Test_default),
unittest.makeSuite(PersistentMappingTests),
unittest.makeSuite(Test_legacy_PersistentDict),
))
...@@ -24,9 +24,18 @@ _is_pypy3 = py_impl() == 'PyPy' and sys.version_info[0] > 2 ...@@ -24,9 +24,18 @@ _is_pypy3 = py_impl() == 'PyPy' and sys.version_info[0] > 2
_is_jython = py_impl() == 'Jython' _is_jython = py_impl() == 'Jython'
#pylint: disable=R0904,W0212,E1101 #pylint: disable=R0904,W0212,E1101
# pylint:disable=attribute-defined-outside-init,too-many-lines
# pylint:disable=blacklisted-name
# Hundreds of unused jar and OID vars make this useless
# pylint:disable=unused-variable
class _Persistent_Base(object): class _Persistent_Base(object):
# py2/3 compat
assertRaisesRegex = getattr(unittest.TestCase,
'assertRaisesRegex',
unittest.TestCase.assertRaisesRegexp)
def _getTargetClass(self): def _getTargetClass(self):
# concrete testcase classes must override # concrete testcase classes must override
raise NotImplementedError() raise NotImplementedError()
...@@ -79,10 +88,10 @@ class _Persistent_Base(object): ...@@ -79,10 +88,10 @@ class _Persistent_Base(object):
class _BrokenJar(object): class _BrokenJar(object):
def __init__(self): def __init__(self):
self.called = 0 self.called = 0
def register(self,ob): def register(self, ob):
self.called += 1 self.called += 1
raise NotImplementedError() raise NotImplementedError()
def setstate(self,ob): def setstate(self, ob):
raise NotImplementedError() raise NotImplementedError()
jar = _BrokenJar() jar = _BrokenJar()
...@@ -162,12 +171,10 @@ class _Persistent_Base(object): ...@@ -162,12 +171,10 @@ class _Persistent_Base(object):
def test_assign_p_jar_w_new_jar(self): def test_assign_p_jar_w_new_jar(self):
inst, jar, OID = self._makeOneWithJar() inst, jar, OID = self._makeOneWithJar()
new_jar = self._makeJar() new_jar = self._makeJar()
try:
with self.assertRaisesRegex(ValueError,
"can not change _p_jar of cached object"):
inst._p_jar = new_jar inst._p_jar = new_jar
except ValueError as e:
self.assertEqual(str(e), "can not change _p_jar of cached object")
else:
self.fail("Should raise ValueError")
def test_assign_p_jar_w_valid_jar(self): def test_assign_p_jar_w_valid_jar(self):
jar = self._makeJar() jar = self._makeJar()
...@@ -189,13 +196,9 @@ class _Persistent_Base(object): ...@@ -189,13 +196,9 @@ class _Persistent_Base(object):
def test_assign_p_oid_w_invalid_oid(self): def test_assign_p_oid_w_invalid_oid(self):
inst, jar, OID = self._makeOneWithJar() inst, jar, OID = self._makeOneWithJar()
try: with self.assertRaisesRegex(ValueError,
'can not change _p_oid of cached object'):
inst._p_oid = object() inst._p_oid = object()
except ValueError as e:
self.assertEqual(str(e), 'can not change _p_oid of cached object')
else:
self.fail("Should raise value error")
def test_assign_p_oid_w_valid_oid(self): def test_assign_p_oid_w_valid_oid(self):
from persistent.timestamp import _makeOctets from persistent.timestamp import _makeOctets
...@@ -299,7 +302,7 @@ class _Persistent_Base(object): ...@@ -299,7 +302,7 @@ class _Persistent_Base(object):
inst = self._makeOne() inst = self._makeOne()
inst._p_serial = SERIAL inst._p_serial = SERIAL
self.assertEqual(inst._p_serial, SERIAL) self.assertEqual(inst._p_serial, SERIAL)
del(inst._p_serial) del inst._p_serial
self.assertEqual(inst._p_serial, _INITIAL_SERIAL) self.assertEqual(inst._p_serial, _INITIAL_SERIAL)
def test_query_p_changed_unsaved(self): def test_query_p_changed_unsaved(self):
...@@ -623,15 +626,17 @@ class _Persistent_Base(object): ...@@ -623,15 +626,17 @@ class _Persistent_Base(object):
def test_assign_p_estimated_size_wrong_type(self): def test_assign_p_estimated_size_wrong_type(self):
inst = self._makeOne() inst = self._makeOne()
self.assertRaises(TypeError,
lambda : setattr(inst, '_p_estimated_size', None)) with self.assertRaises(TypeError):
inst._p_estimated_size = None
try: try:
long constructor = long
except NameError: except NameError:
pass constructor = str
else:
self.assertRaises(TypeError, with self.assertRaises(TypeError):
lambda : setattr(inst, '_p_estimated_size', long(1))) inst._p_estimated_size = constructor(1)
def test_assign_p_estimated_size_negative(self): def test_assign_p_estimated_size_negative(self):
inst = self._makeOne() inst = self._makeOne()
...@@ -723,7 +728,7 @@ class _Persistent_Base(object): ...@@ -723,7 +728,7 @@ class _Persistent_Base(object):
def __getattribute__(self, name): def __getattribute__(self, name):
if name == 'magic': if name == 'magic':
return 42 return 42
return super(Base,self).__getattribute__(name) return super(Base, self).__getattribute__(name) # pragma: no cover
self.assertEqual(getattr(Base(), 'magic'), 42) self.assertEqual(getattr(Base(), 'magic'), 42)
...@@ -921,7 +926,7 @@ class _Persistent_Base(object): ...@@ -921,7 +926,7 @@ class _Persistent_Base(object):
from persistent.persistence import _INITIAL_SERIAL from persistent.persistence import _INITIAL_SERIAL
inst = self._makeOne() inst = self._makeOne()
self.assertRaises((ValueError, TypeError), self.assertRaises((ValueError, TypeError),
inst.__setstate__, {'bogus': 1}) inst.__setstate__, {'bogus': 1})
self.assertEqual(inst._p_jar, None) self.assertEqual(inst._p_jar, None)
self.assertEqual(inst._p_oid, None) self.assertEqual(inst._p_oid, None)
self.assertEqual(inst._p_serial, _INITIAL_SERIAL) self.assertEqual(inst._p_serial, _INITIAL_SERIAL)
...@@ -1030,7 +1035,6 @@ class _Persistent_Base(object): ...@@ -1030,7 +1035,6 @@ class _Persistent_Base(object):
self.assertTrue(hasattr(inst1, 'foobar')) self.assertTrue(hasattr(inst1, 'foobar'))
def test___reduce__(self): def test___reduce__(self):
from persistent._compat import copy_reg
inst = self._makeOne() inst = self._makeOne()
first, second, third = inst.__reduce__() first, second, third = inst.__reduce__()
self.assertTrue(first is copy_reg.__newobj__) self.assertTrue(first is copy_reg.__newobj__)
...@@ -1038,7 +1042,6 @@ class _Persistent_Base(object): ...@@ -1038,7 +1042,6 @@ class _Persistent_Base(object):
self.assertEqual(third, None) self.assertEqual(third, None)
def test___reduce__w_subclass_having_getnewargs(self): def test___reduce__w_subclass_having_getnewargs(self):
from persistent._compat import copy_reg
class Derived(self._getTargetClass()): class Derived(self._getTargetClass()):
def __getnewargs__(self): def __getnewargs__(self):
return ('a', 'b') return ('a', 'b')
...@@ -1049,7 +1052,6 @@ class _Persistent_Base(object): ...@@ -1049,7 +1052,6 @@ class _Persistent_Base(object):
self.assertEqual(third, {}) self.assertEqual(third, {})
def test___reduce__w_subclass_having_getstate(self): def test___reduce__w_subclass_having_getstate(self):
from persistent._compat import copy_reg
class Derived(self._getTargetClass()): class Derived(self._getTargetClass()):
def __getstate__(self): def __getstate__(self):
return {} return {}
...@@ -1060,7 +1062,6 @@ class _Persistent_Base(object): ...@@ -1060,7 +1062,6 @@ class _Persistent_Base(object):
self.assertEqual(third, {}) self.assertEqual(third, {})
def test___reduce__w_subclass_having_getnewargs_and_getstate(self): def test___reduce__w_subclass_having_getnewargs_and_getstate(self):
from persistent._compat import copy_reg
class Derived(self._getTargetClass()): class Derived(self._getTargetClass()):
def __getnewargs__(self): def __getnewargs__(self):
return ('a', 'b') return ('a', 'b')
...@@ -1537,14 +1538,12 @@ class _Persistent_Base(object): ...@@ -1537,14 +1538,12 @@ class _Persistent_Base(object):
# object stays in the up-to-date state. # object stays in the up-to-date state.
# It shouldn't change to the modified state, because it won't # It shouldn't change to the modified state, because it won't
# be saved when the transaction commits. # be saved when the transaction commits.
from persistent._compat import _b
class P(self._getTargetClass()): class P(self._getTargetClass()):
def __init__(self): def __init__(self):
self.x = 0 self.x = 0
def inc(self):
self.x += 1
p = P() p = P()
p._p_oid = _b('1') p._p_oid = b'1'
p._p_jar = self._makeBrokenJar() p._p_jar = self._makeBrokenJar()
self.assertEqual(p._p_state, 0) self.assertEqual(p._p_state, 0)
self.assertEqual(p._p_jar.called, 0) self.assertEqual(p._p_jar.called, 0)
...@@ -1557,14 +1556,11 @@ class _Persistent_Base(object): ...@@ -1557,14 +1556,11 @@ class _Persistent_Base(object):
def test__p_activate_w_broken_jar(self): def test__p_activate_w_broken_jar(self):
# Make sure that exceptions that occur inside the data manager's # Make sure that exceptions that occur inside the data manager's
# ``setstate()`` method propagate out to the caller. # ``setstate()`` method propagate out to the caller.
from persistent._compat import _b
class P(self._getTargetClass()): class P(self._getTargetClass()):
def __init__(self): def __init__(self):
self.x = 0 self.x = 0
def inc(self):
self.x += 1
p = P() p = P()
p._p_oid = _b('1') p._p_oid = b'1'
p._p_jar = self._makeBrokenJar() p._p_jar = self._makeBrokenJar()
p._p_deactivate() p._p_deactivate()
self.assertEqual(p._p_state, -1) self.assertEqual(p._p_state, -1)
...@@ -1618,23 +1614,21 @@ class _Persistent_Base(object): ...@@ -1618,23 +1614,21 @@ class _Persistent_Base(object):
class subclass(self._getTargetClass()): class subclass(self._getTargetClass()):
_v_setattr_called = False _v_setattr_called = False
def __setattr__(self, name, value): def __setattr__(self, name, value):
object.__setattr__(self, '_v_setattr_called', True) raise AssertionError("Should not be called")
super(subclass,self).__setattr__(name, value)
inst = subclass() inst = subclass()
self.assertEqual(object.__getattribute__(inst,'_v_setattr_called'), False) self.assertEqual(object.__getattribute__(inst,'_v_setattr_called'), False)
def test_can_set__p_attrs_if_subclass_denies_setattr(self): def test_can_set__p_attrs_if_subclass_denies_setattr(self):
from persistent._compat import _b
# ZODB defines a PersistentBroken subclass that only lets us # ZODB defines a PersistentBroken subclass that only lets us
# set things that start with _p, so make sure we can do that # set things that start with _p, so make sure we can do that
class Broken(self._getTargetClass()): class Broken(self._getTargetClass()):
def __setattr__(self, name, value): def __setattr__(self, name, value):
if name.startswith('_p_'): if name.startswith('_p_'):
super(Broken,self).__setattr__(name, value) super(Broken, self).__setattr__(name, value)
else: else:
raise TypeError("Can't change broken objects") raise AssertionError("Can't change broken objects")
KEY = _b('123') KEY = b'123'
jar = self._makeJar() jar = self._makeJar()
broken = Broken() broken = Broken()
...@@ -1743,17 +1737,17 @@ class PyPersistentTests(unittest.TestCase, _Persistent_Base): ...@@ -1743,17 +1737,17 @@ class PyPersistentTests(unittest.TestCase, _Persistent_Base):
# pickle cache yet. # pickle cache yet.
# Nothing should blow up when this happens # Nothing should blow up when this happens
from persistent._compat import _b from persistent._compat import _b
KEY = _b('123') KEY = b'123'
jar = self._makeJar() jar = self._makeJar()
c1 = self._makeOne() c1 = self._makeOne()
c1._p_oid = KEY c1._p_oid = KEY
c1._p_jar = jar c1._p_jar = jar
orig_mru = jar._cache.mru
def mru(oid): def mru(oid):
# Mimic what the real cache does # Mimic what the real cache does
if oid not in jar._cache._mru: if oid not in jar._cache._mru:
raise KeyError(oid) raise KeyError(oid)
orig_mru(oid) raise AssertionError("Shold never get here")
jar._cache.mru = mru jar._cache.mru = mru
c1._p_accessed() c1._p_accessed()
self._checkMRU(jar, []) self._checkMRU(jar, [])
...@@ -1815,7 +1809,7 @@ _add_to_suite = [PyPersistentTests] ...@@ -1815,7 +1809,7 @@ _add_to_suite = [PyPersistentTests]
if not os.environ.get('PURE_PYTHON'): if not os.environ.get('PURE_PYTHON'):
try: try:
from persistent import cPersistence from persistent import cPersistence
except ImportError: except ImportError: # pragma: no cover
pass pass
else: else:
class CPersistentTests(unittest.TestCase, _Persistent_Base): class CPersistentTests(unittest.TestCase, _Persistent_Base):
...@@ -1846,12 +1840,7 @@ if not os.environ.get('PURE_PYTHON'): ...@@ -1846,12 +1840,7 @@ if not os.environ.get('PURE_PYTHON'):
self.assertRaises(TypeError, self._callFUT, '') self.assertRaises(TypeError, self._callFUT, '')
def test_w_type(self): def test_w_type(self):
import sys TO_CREATE = [type, list, tuple, object, dict]
TO_CREATE = [type, list, tuple, object]
# Python 3.3 segfaults when destroying a dict created via
# PyType_GenericNew. See http://bugs.python.org/issue16676
if sys.version_info < (3, 3):
TO_CREATE.append(dict)
for typ in TO_CREATE: for typ in TO_CREATE:
self.assertTrue(isinstance(self._callFUT(typ), typ)) self.assertTrue(isinstance(self._callFUT(typ), typ))
......
...@@ -24,6 +24,12 @@ _marker = object() ...@@ -24,6 +24,12 @@ _marker = object()
class PickleCacheTests(unittest.TestCase): class PickleCacheTests(unittest.TestCase):
# py2/3 compat
assertRaisesRegex = getattr(unittest.TestCase,
'assertRaisesRegex',
unittest.TestCase.assertRaisesRegexp)
def setUp(self): def setUp(self):
import persistent.picklecache import persistent.picklecache
self.orig_types = persistent.picklecache._CACHEABLE_TYPES self.orig_types = persistent.picklecache._CACHEABLE_TYPES
...@@ -98,12 +104,8 @@ class PickleCacheTests(unittest.TestCase): ...@@ -98,12 +104,8 @@ class PickleCacheTests(unittest.TestCase):
def test___setitem___non_string_oid_raises_TypeError(self): def test___setitem___non_string_oid_raises_TypeError(self):
cache = self._makeOne() cache = self._makeOne()
try: with self.assertRaises(TypeError):
cache[object()] = self._makePersist() cache[object()] = self._makePersist()
except TypeError:
pass
else:
self.fail("Didn't raise ValueError with non-string OID.")
def test___setitem___duplicate_oid_same_obj(self): def test___setitem___duplicate_oid_same_obj(self):
from persistent._compat import _b from persistent._compat import _b
...@@ -121,12 +123,8 @@ class PickleCacheTests(unittest.TestCase): ...@@ -121,12 +123,8 @@ class PickleCacheTests(unittest.TestCase):
cache[KEY] = original cache[KEY] = original
duplicate = self._makePersist(oid=KEY) duplicate = self._makePersist(oid=KEY)
try: with self.assertRaises(ValueError):
cache[KEY] = duplicate cache[KEY] = duplicate
except ValueError:
pass
else:
self.fail("Didn't raise KeyError with duplicate OID.")
def test___setitem___ghost(self): def test___setitem___ghost(self):
from persistent.interfaces import GHOST from persistent.interfaces import GHOST
...@@ -153,12 +151,8 @@ class PickleCacheTests(unittest.TestCase): ...@@ -153,12 +151,8 @@ class PickleCacheTests(unittest.TestCase):
cache = self._makeOne() cache = self._makeOne()
uptodate = self._makePersist(state=UPTODATE) uptodate = self._makePersist(state=UPTODATE)
try: with self.assertRaises(ValueError):
cache[KEY] = uptodate cache[KEY] = uptodate
except ValueError:
pass
else:
self.fail("Didn't raise ValueError when the key didn't match the OID")
def test___setitem___non_ghost(self): def test___setitem___non_ghost(self):
...@@ -201,24 +195,16 @@ class PickleCacheTests(unittest.TestCase): ...@@ -201,24 +195,16 @@ class PickleCacheTests(unittest.TestCase):
def test___delitem___non_string_oid_raises_TypeError(self): def test___delitem___non_string_oid_raises_TypeError(self):
cache = self._makeOne() cache = self._makeOne()
try: with self.assertRaises(TypeError):
del cache[object()] del cache[object()]
except TypeError:
pass
else:
self.fail("Didn't raise ValueError with non-string OID.")
def test___delitem___nonesuch_raises_KeyError(self): def test___delitem___nonesuch_raises_KeyError(self):
from persistent._compat import _b from persistent._compat import _b
cache = self._makeOne() cache = self._makeOne()
original = self._makePersist() original = self._makePersist()
try: with self.assertRaises(KeyError):
del cache[_b('nonesuch')] del cache[_b('nonesuch')]
except KeyError:
pass
else:
self.fail("Didn't raise KeyError with nonesuch OID.")
def test___delitem___w_persistent_class(self): def test___delitem___w_persistent_class(self):
from persistent._compat import _b from persistent._compat import _b
...@@ -878,22 +864,16 @@ class PickleCacheTests(unittest.TestCase): ...@@ -878,22 +864,16 @@ class PickleCacheTests(unittest.TestCase):
def test_setting_non_persistent_item(self): def test_setting_non_persistent_item(self):
cache = self._makeOne() cache = self._makeOne()
try: with self.assertRaisesRegex(TypeError,
"Cache values must be persistent objects."):
cache[None] = object() cache[None] = object()
except TypeError as e:
self.assertEqual(str(e), "Cache values must be persistent objects.")
else:
self.fail("Should raise TypeError")
def test_setting_without_jar(self): def test_setting_without_jar(self):
cache = self._makeOne() cache = self._makeOne()
p = self._makePersist(jar=None) p = self._makePersist(jar=None)
try: with self.assertRaisesRegex(ValueError,
"Cached object jar missing"):
cache[p._p_oid] = p cache[p._p_oid] = p
except ValueError as e:
self.assertEqual(str(e), "Cached object jar missing")
else:
self.fail("Should raise ValueError")
def test_setting_already_cached(self): def test_setting_already_cached(self):
cache1 = self._makeOne() cache1 = self._makeOne()
...@@ -902,12 +882,9 @@ class PickleCacheTests(unittest.TestCase): ...@@ -902,12 +882,9 @@ class PickleCacheTests(unittest.TestCase):
cache1[p._p_oid] = p cache1[p._p_oid] = p
cache2 = self._makeOne() cache2 = self._makeOne()
try: with self.assertRaisesRegex(ValueError,
"Object already in another cache"):
cache2[p._p_oid] = p cache2[p._p_oid] = p
except ValueError as e:
self.assertEqual(str(e), "Object already in another cache")
else:
self.fail("Should raise value error")
def test_cannot_update_mru_while_already_locked(self): def test_cannot_update_mru_while_already_locked(self):
cache = self._makeOne() cache = self._makeOne()
...@@ -972,7 +949,7 @@ class PickleCacheTests(unittest.TestCase): ...@@ -972,7 +949,7 @@ class PickleCacheTests(unittest.TestCase):
del p._p_deactivate del p._p_deactivate
self.assertEqual(cache.full_sweep(), 1) self.assertEqual(cache.full_sweep(), 1)
if _is_jython: if _is_jython: # pragma: no cover
def with_deterministic_gc(f): def with_deterministic_gc(f):
def test(self): def test(self):
old_flags = gc.getMonitorGlobal() old_flags = gc.getMonitorGlobal()
...@@ -1027,7 +1004,7 @@ class PickleCacheTests(unittest.TestCase): ...@@ -1027,7 +1004,7 @@ class PickleCacheTests(unittest.TestCase):
# It also shrank the measured size of the cache; # It also shrank the measured size of the cache;
# this would fail under PyPy if _SWEEP_NEEDS_GC was False # this would fail under PyPy if _SWEEP_NEEDS_GC was False
if force_collect: if force_collect: # pragma: no cover
gc.collect() gc.collect()
self.assertEqual(len(cache), 1) self.assertEqual(len(cache), 1)
...@@ -1053,12 +1030,11 @@ class PickleCacheTests(unittest.TestCase): ...@@ -1053,12 +1030,11 @@ class PickleCacheTests(unittest.TestCase):
def test_ring_impl(self): def test_ring_impl(self):
from .. import ring from .. import ring
if _is_pypy: expected = (ring._CFFIRing
self.assertIs(ring.Ring, ring._CFFIRing) if _is_pypy or ring._CFFIRing is not None or os.environ.get('USING_CFFI')
elif ring._CFFIRing is not None or os.environ.get('USING_CFFI'): else ring._DequeRing)
self.assertIs(ring.Ring, ring._CFFIRing) self.assertIs(ring.Ring, expected)
else:
self.assertIs(ring.Ring, ring._DequeRing)
class DummyPersistent(object): class DummyPersistent(object):
......
...@@ -31,7 +31,7 @@ class DummyPersistent(object): ...@@ -31,7 +31,7 @@ class DummyPersistent(object):
if oid is None: if oid is None:
self._p_oid = self._next_oid() self._p_oid = self._next_oid()
def __repr__(self): def __repr__(self): # pragma: no cover
return "<Dummy %r>" % self._p_oid return "<Dummy %r>" % self._p_oid
class _Ring_Base(object): class _Ring_Base(object):
......
...@@ -163,14 +163,20 @@ class pyTimeStampTests(unittest.TestCase): ...@@ -163,14 +163,20 @@ class pyTimeStampTests(unittest.TestCase):
# Check the corner cases when comparing non-comparable types # Check the corner cases when comparing non-comparable types
ts = self._makeOne(2011, 2, 16, 14, 37, 22.0) ts = self._makeOne(2011, 2, 16, 14, 37, 22.0)
def check_py2(op, passes): def check_common(op, passes):
if passes == 'neither': if passes == 'neither':
self.assertFalse(op(ts, None)) self.assertFalse(op(ts, None))
self.assertFalse(op(None, ts)) self.assertFalse(op(None, ts))
elif passes == 'both': return True
if passes == 'both':
self.assertTrue(op(ts, None)) self.assertTrue(op(ts, None))
self.assertTrue(op(None, ts)) self.assertTrue(op(None, ts))
elif passes == 'first': return True
return False
def check_py2(op, passes): # pragma: no cover
if passes == 'first':
self.assertTrue(op(ts, None)) self.assertTrue(op(ts, None))
self.assertFalse(op(None, ts)) self.assertFalse(op(None, ts))
else: else:
...@@ -178,15 +184,8 @@ class pyTimeStampTests(unittest.TestCase): ...@@ -178,15 +184,8 @@ class pyTimeStampTests(unittest.TestCase):
self.assertTrue(op(None, ts)) self.assertTrue(op(None, ts))
def check_py3(op, passes): def check_py3(op, passes):
if passes == 'neither': self.assertRaises(TypeError, op, ts, None)
self.assertFalse(op(ts, None)) self.assertRaises(TypeError, op, None, ts)
self.assertFalse(op(None, ts))
elif passes == 'both':
self.assertTrue(op(ts, None))
self.assertTrue(op(None, ts))
else:
self.assertRaises(TypeError, op, ts, None)
self.assertRaises(TypeError, op, None, ts)
check = check_py2 if PYTHON2 else check_py3 check = check_py2 if PYTHON2 else check_py3
...@@ -197,7 +196,8 @@ class pyTimeStampTests(unittest.TestCase): ...@@ -197,7 +196,8 @@ class pyTimeStampTests(unittest.TestCase):
('eq', 'neither'), ('eq', 'neither'),
('ne', 'both')): ('ne', 'both')):
op = getattr(operator, op_name) op = getattr(operator, op_name)
check(op, passes) if not check_common(op, passes):
check(op, passes)
class TimeStampTests(pyTimeStampTests): class TimeStampTests(pyTimeStampTests):
...@@ -223,7 +223,7 @@ class PyAndCComparisonTests(unittest.TestCase): ...@@ -223,7 +223,7 @@ class PyAndCComparisonTests(unittest.TestCase):
# it to test matching # it to test matching
yield self.now_ts_args yield self.now_ts_args
for i in range(2000): for i in range(2000):
yield self.now_ts_args[:-1] + (self.now_ts_args[-1] + (i % 60.0)/100.0 , ) yield self.now_ts_args[:-1] + (self.now_ts_args[-1] + (i % 60.0)/100.0, )
def _makeC(self, *args, **kwargs): def _makeC(self, *args, **kwargs):
from persistent.timestamp import TimeStamp from persistent.timestamp import TimeStamp
...@@ -304,7 +304,7 @@ class PyAndCComparisonTests(unittest.TestCase): ...@@ -304,7 +304,7 @@ class PyAndCComparisonTests(unittest.TestCase):
# in hash() on 32-bit platforms # in hash() on 32-bit platforms
if not self._is_jython: if not self._is_jython:
self.assertEqual(py.__hash__(), bit_64_hash) self.assertEqual(py.__hash__(), bit_64_hash)
else: else: # pragma: no cover
# Jython 2.7's ctypes module doesn't properly # Jython 2.7's ctypes module doesn't properly
# implement the 'value' attribute by truncating. # implement the 'value' attribute by truncating.
# (It does for native calls, but not visibly to Python). # (It does for native calls, but not visibly to Python).
...@@ -318,15 +318,13 @@ class PyAndCComparisonTests(unittest.TestCase): ...@@ -318,15 +318,13 @@ class PyAndCComparisonTests(unittest.TestCase):
MUT._MAXINT = orig_maxint MUT._MAXINT = orig_maxint
if orig_c_long is not None: if orig_c_long is not None:
MUT.c_long = orig_c_long MUT.c_long = orig_c_long
else: else: # pragma: no cover
del MUT.c_long del MUT.c_long
# These are *usually* aliases, but aren't required # These are *usually* aliases, but aren't required
# to be (and aren't under Jython 2.7). # to be (and aren't under Jython 2.7).
if is_32_bit_hash: expected_hash = bit_32_hash if is_32_bit_hash else bit_64_hash
self.assertEqual(py.__hash__(), bit_32_hash) self.assertEqual(py.__hash__(), expected_hash)
else:
self.assertEqual(py.__hash__(), bit_64_hash)
def test_hash_equal_constants(self): def test_hash_equal_constants(self):
# The simple constants make it easier to diagnose # The simple constants make it easier to diagnose
...@@ -350,46 +348,36 @@ class PyAndCComparisonTests(unittest.TestCase): ...@@ -350,46 +348,36 @@ class PyAndCComparisonTests(unittest.TestCase):
# overflow kicks in here on 32-bit platforms # overflow kicks in here on 32-bit platforms
c, py = self._make_C_and_Py(b'\x00\x00\x00\x00\x00\x01\x00\x00') c, py = self._make_C_and_Py(b'\x00\x00\x00\x00\x00\x01\x00\x00')
if is_32_bit: expected = -721379967 if is_32_bit else 1000006000001
self.assertEqual(hash(c), -721379967) self.assertEqual(hash(c), expected)
else:
self.assertEqual(hash(c), 1000006000001)
self.assertEqual(hash(c), hash(py)) self.assertEqual(hash(c), hash(py))
c, py = self._make_C_and_Py(b'\x00\x00\x00\x00\x01\x00\x00\x00') c, py = self._make_C_and_Py(b'\x00\x00\x00\x00\x01\x00\x00\x00')
if is_32_bit: expected = 583896275 if is_32_bit else 1000009000027000019
self.assertEqual(hash(c), 583896275) self.assertEqual(hash(c), expected)
else:
self.assertEqual(hash(c), 1000009000027000019)
self.assertEqual(hash(c), hash(py)) self.assertEqual(hash(c), hash(py))
# Overflow kicks in at this point on 64-bit platforms # Overflow kicks in at this point on 64-bit platforms
c, py = self._make_C_and_Py(b'\x00\x00\x00\x01\x00\x00\x00\x00') c, py = self._make_C_and_Py(b'\x00\x00\x00\x01\x00\x00\x00\x00')
if is_32_bit: expected = 1525764953 if is_32_bit else -4442925868394654887
self.assertEqual(hash(c), 1525764953) self.assertEqual(hash(c), expected)
else:
self.assertEqual(hash(c), -4442925868394654887)
self.assertEqual(hash(c), hash(py)) self.assertEqual(hash(c), hash(py))
c, py = self._make_C_and_Py(b'\x00\x00\x01\x00\x00\x00\x00\x00') c, py = self._make_C_and_Py(b'\x00\x00\x01\x00\x00\x00\x00\x00')
if is_32_bit: expected = -429739973 if is_32_bit else -3993531167153147845
self.assertEqual(hash(c), -429739973) self.assertEqual(hash(c), expected)
else:
self.assertEqual(hash(c), -3993531167153147845)
self.assertEqual(hash(c), hash(py)) self.assertEqual(hash(c), hash(py))
c, py = self._make_C_and_Py(b'\x01\x00\x00\x00\x00\x00\x00\x00') c, py = self._make_C_and_Py(b'\x01\x00\x00\x00\x00\x00\x00\x00')
if is_32_bit: expected = 263152323 if is_32_bit else -3099646879006235965
self.assertEqual(hash(c), 263152323) self.assertEqual(hash(c), expected)
else:
self.assertEqual(hash(c), -3099646879006235965)
self.assertEqual(hash(c), hash(py)) self.assertEqual(hash(c), hash(py))
def test_ordering(self): def test_ordering(self):
small_c = self._makeC(b'\x00\x00\x00\x00\x00\x00\x00\x01') small_c = self._makeC(b'\x00\x00\x00\x00\x00\x00\x00\x01')
big_c = self._makeC(b'\x01\x00\x00\x00\x00\x00\x00\x00')
small_py = self._makePy(b'\x00\x00\x00\x00\x00\x00\x00\x01') small_py = self._makePy(b'\x00\x00\x00\x00\x00\x00\x00\x01')
big_c = self._makeC(b'\x01\x00\x00\x00\x00\x00\x00\x00')
big_py = self._makePy(b'\x01\x00\x00\x00\x00\x00\x00\x00') big_py = self._makePy(b'\x01\x00\x00\x00\x00\x00\x00\x00')
self.assertTrue(small_py < big_py) self.assertTrue(small_py < big_py)
...@@ -423,7 +411,7 @@ def test_suite(): ...@@ -423,7 +411,7 @@ def test_suite():
try: try:
from persistent.timestamp import pyTimeStamp from persistent.timestamp import pyTimeStamp
from persistent.timestamp import TimeStamp from persistent.timestamp import TimeStamp
except ImportError: except ImportError: # pragma: no cover
pass pass
else: else:
if pyTimeStamp != TimeStamp: if pyTimeStamp != TimeStamp:
......
...@@ -315,9 +315,9 @@ class PersistentWeakKeyDictionaryTests(unittest.TestCase): ...@@ -315,9 +315,9 @@ class PersistentWeakKeyDictionaryTests(unittest.TestCase):
target = self._makeOne(None) target = self._makeOne(None)
target.update(source) target.update(source)
self.assertTrue(target[key] is value) self.assertTrue(target[key] is value)
def _makeTarget(oid='OID', **kw):
def _makeTarget(oid='OID'):
from persistent import Persistent from persistent import Persistent
from persistent._compat import _b from persistent._compat import _b
class Derived(Persistent): class Derived(Persistent):
...@@ -325,11 +325,9 @@ def _makeTarget(oid='OID', **kw): ...@@ -325,11 +325,9 @@ def _makeTarget(oid='OID', **kw):
return hash(self._p_oid) return hash(self._p_oid)
def __eq__(self, other): def __eq__(self, other):
return self._p_oid == other._p_oid return self._p_oid == other._p_oid
def __repr__(self): def __repr__(self): # pragma: no cover
return 'Derived: %s' % self._p_oid return 'Derived: %s' % self._p_oid
derived = Derived() derived = Derived()
for k, v in kw.items():
setattr(derived, k, v)
derived._p_oid = _b(oid) derived._p_oid = _b(oid)
return derived return derived
...@@ -341,7 +339,4 @@ def _makeJar(): ...@@ -341,7 +339,4 @@ def _makeJar():
return _Jar() return _Jar()
def test_suite(): def test_suite():
return unittest.TestSuite(( return unittest.defaultTestLoader.loadTestsFromName(__name__)
unittest.makeSuite(WeakRefTests),
unittest.makeSuite(PersistentWeakKeyDictionaryTests),
))
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment