summaryrefslogtreecommitdiff
path: root/bps/tests
diff options
context:
space:
mode:
authorEli Collins <elic@assurancetechnologies.com>2011-01-06 01:11:16 +0000
committerEli Collins <elic@assurancetechnologies.com>2011-01-06 01:11:16 +0000
commit0dd599bbb323387991cd8a3565ea87f36ff0892f (patch)
tree26705624c861c0725d1e8fd8555f84705775e1c2 /bps/tests
downloadpasslib-0dd599bbb323387991cd8a3565ea87f36ff0892f.tar.gz
cloning bps to passlib trunk
Diffstat (limited to 'bps/tests')
-rw-r--r--bps/tests/__init__.py5
-rw-r--r--bps/tests/_logs_parse_config_sample1.ini10
-rw-r--r--bps/tests/test_basic.py319
-rwxr-xr-xbps/tests/test_fs.py1321
-rw-r--r--bps/tests/test_host.py142
-rw-r--r--bps/tests/test_logs.py309
-rw-r--r--bps/tests/test_logs_apply_config.py190
-rw-r--r--bps/tests/test_logs_capture.py306
-rw-r--r--bps/tests/test_logs_parse_config.py537
-rw-r--r--bps/tests/test_meta.py678
-rw-r--r--bps/tests/test_misc.py179
-rw-r--r--bps/tests/test_numeric.py771
-rwxr-xr-xbps/tests/test_security_bcrypt.py210
-rw-r--r--bps/tests/test_security_policy.py1710
-rw-r--r--bps/tests/test_security_pwgen.py109
-rw-r--r--bps/tests/test_security_pwhash.py1220
-rw-r--r--bps/tests/test_stream.py33
-rw-r--r--bps/tests/test_text.py927
-rw-r--r--bps/tests/test_text_format.py1118
-rw-r--r--bps/tests/test_types.py278
-rw-r--r--bps/tests/test_unstable_ansi.py344
-rw-r--r--bps/tests/test_warndep.py480
-rw-r--r--bps/tests/utils.py384
23 files changed, 11580 insertions, 0 deletions
diff --git a/bps/tests/__init__.py b/bps/tests/__init__.py
new file mode 100644
index 0000000..7cbcb8f
--- /dev/null
+++ b/bps/tests/__init__.py
@@ -0,0 +1,5 @@
+"""bps.tests -- unittests for BPS
+
+This package contains the unittests for BPS.
+The files names "test_xxx" roughly correspond to "bps.xxx" module tests.
+"""
diff --git a/bps/tests/_logs_parse_config_sample1.ini b/bps/tests/_logs_parse_config_sample1.ini
new file mode 100644
index 0000000..7571124
--- /dev/null
+++ b/bps/tests/_logs_parse_config_sample1.ini
@@ -0,0 +1,10 @@
+#sample logging config file used by test_logs_parse_config
+
+[logging:options]
+capture_warnings = True
+warning_fmt = %(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s
+reset_loggers = True
+not_an_option = ignored options should be ignored
+
+[logging:levels]
+<root> = WARNING
diff --git a/bps/tests/test_basic.py b/bps/tests/test_basic.py
new file mode 100644
index 0000000..8acdd19
--- /dev/null
+++ b/bps/tests/test_basic.py
@@ -0,0 +1,319 @@
+"""tests for bps.text -- (c) Assurance Technologies 2003-2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+from array import array
+import os.path
+#site
+#pkg
+from bps.basic import *
+from bps.meta import Params as ak
+#module
+from bps.tests.utils import TestCase
+#=========================================================
+#
+#=========================================================
+from bps.unstable import smart_list_iter
+class SmartListIterTest(TestCase):
+ def test_basic(self):
+ source=[5,6,100,2,3,40,8]
+ target=list(source)
+ out = []
+ itr = smart_list_iter(target)
+ for elem in itr:
+ out.append(elem)
+ self.assertEquals(out, source)
+ self.assertEquals(target, source)
+
+ def test_enum(self):
+ source=[5,6,100,2,3,40,8]
+ target=list(source)
+ out = []
+ itr = smart_list_iter(target, enum=True)
+ for elem in itr:
+ out.append(elem)
+ self.assertEquals(out, list(enumerate(source)))
+ self.assertEquals(target, source)
+
+ def test_delete(self):
+ source=[5,6,100,2,3,40,8]
+ target=list(source)
+ out = []
+ itr = smart_list_iter(target)
+ for elem in itr:
+ out.append(elem)
+ if elem > 30:
+ itr.delete()
+ self.assertEquals(out, source)
+ self.assertEquals(target, [5, 6, 2, 3, 8])
+
+ def test_double_delete(self):
+ source=[5,6,100,2,3,40,8]
+ target=list(source)
+ out = []
+ itr = smart_list_iter(target)
+ for elem in itr:
+ out.append(elem)
+ if elem > 30:
+ itr.delete()
+ itr.delete()
+ self.assertEquals(out, [5, 6, 100, 3, 40])
+ self.assertEquals(target, [5, 6, 3])
+
+ def test_insert(self):
+ source=[5,6,100,2,3,40,8]
+ target=list(source)
+ out = []
+ itr = smart_list_iter(target)
+ for elem in itr:
+ out.append(elem)
+ if elem == 6:
+ itr.delete()
+ itr.insert(0, 666)
+ elif elem == 100:
+ itr.delete()
+ itr.insert(0, 111, relative=True)
+ elif elem == 2:
+ itr.insert(2, 222)
+ itr.insert(2, 2221, relative=True)
+ elif elem == 3:
+ itr.insert(1, 333, relative=True)
+ self.assertEquals(out, [5, 6, 100, 111, 2, 3, 333, 2221, 40, 8])
+ self.assertEquals(target, [666, 5, 222, 111, 2, 3, 333, 2221, 40, 8])
+
+ def test_eol_delete(self):
+ source=[5,6,100,2,3,40,8]
+ target=list(source)
+ out = []
+ itr = smart_list_iter(target)
+ for elem in itr:
+ out.append(elem)
+ if elem == 8:
+ itr.delete()
+ self.assertRaises(IndexError, itr.delete)
+ self.assertEquals(out, source)
+ self.assertEquals(target, [5, 6, 100, 2, 3, 40])
+
+ #TODO: test various other insert/pop code
+ #TODO: test next_pos, __length__
+
+from bps.unstable import filter_in_place
+
+class FilterInPlaceTest(TestCase):
+
+ def test_list(self):
+ def ff(elem):
+ return elem in (3,9,7)
+
+ #test empty
+ a = []
+ filter_in_place(ff, a)
+ self.assertEquals(a,[])
+
+ #test all removed
+ a = [1,5,13,11]
+ filter_in_place(ff, a)
+ self.assertEquals(a,[])
+
+ #test none removed
+ a = [3,7,9]
+ filter_in_place(ff, a)
+ self.assertEquals(a,[3,7,9])
+
+ #test some removed
+ a = [1,3,5,7,9,11]
+ filter_in_place(ff, a)
+ self.assertEquals(a,[3,7,9])
+
+ #test some removed + invert
+ a = [1,3,5,7,9,11]
+ filter_in_place(ff, a, invert=True)
+ self.assertEquals(a,[1,5,11])
+
+ def test_array(self):
+ def ff(elem):
+ return elem in ("3","9","7")
+
+ #test empty
+ a = array('c')
+ filter_in_place(ff, a)
+ self.assertEquals(a.tostring(),'')
+
+ #test all removed
+ a = array('c','158')
+ filter_in_place(ff, a)
+ self.assertEquals(a.tostring(),'')
+
+ #test none removed
+ a = array('c','379')
+ filter_in_place(ff, a)
+ self.assertEquals(a.tostring(),'379')
+
+ #test some removed
+ a = array('c','135987')
+ filter_in_place(ff, a)
+ self.assertEquals(a.tostring(),'397')
+
+ #test some removed + invert
+ a = array('c','135987')
+ filter_in_place(ff, a, invert=True)
+ self.assertEquals(a.tostring(),'158')
+
+ def test_set(self):
+ def ff(elem):
+ return elem in (3,9,7)
+
+ #test empty
+ a = set()
+ filter_in_place(ff, a)
+ self.assertEquals(a,set())
+
+ #test all removed
+ a = set([1,5,13,11])
+ filter_in_place(ff, a)
+ self.assertEquals(a,set())
+
+ #test none removed
+ a = set([3,7,9])
+ filter_in_place(ff, a)
+ self.assertEquals(a,set([3,7,9]))
+
+ #test some removed
+ a = set([1,3,5,7,9,11])
+ filter_in_place(ff, a)
+ self.assertEquals(a,set([3,7,9]))
+
+ #test some removed + invert
+ a = set([1,3,5,7,9,11])
+ filter_in_place(ff, a, invert=True)
+ self.assertEquals(a,set([1,5,11]))
+
+ def test_dict(self):
+ def ff(elem):
+ return elem in (3,9,7)
+
+ #test empty
+ a = {}
+ filter_in_place(ff, a)
+ self.assertEquals(a,{})
+
+ #test all removed
+ a = {1:2, 5:6, 13:8, 11:12}
+ filter_in_place(ff, a)
+ self.assertEquals(a,{})
+
+ #test none removed
+ a = {3:2, 7:6, 9:8}
+ filter_in_place(ff, a)
+ self.assertEquals(a,{3:2, 7:6, 9:8})
+
+ #test some removed
+ a = {1:2, 5:6, 13:8, 11:12, 3:2, 7:6, 9:8}
+ filter_in_place(ff, a)
+ self.assertEquals(a,{3:2, 7:6, 9:8})
+
+ #test some removed + invert
+ a = {1:2, 5:6, 13:8, 11:12, 3:2, 7:6, 9:8}
+ filter_in_place(ff, a, invert=True)
+ self.assertEquals(a,{1:2, 5:6, 13:8, 11:12})
+
+ def test_bad_types(self):
+ def ff(elem):
+ return elem in (3,9,7)
+ a = [1,3,6]
+ self.assertRaises(TypeError, filter_in_place, ff, iter(a))
+ self.assertRaises(TypeError, filter_in_place, ff, (1,3,5,7))
+ self.assertRaises(TypeError, filter_in_place, ff, "1357")
+ self.assertRaises(TypeError, filter_in_place, ff, frozenset((1,3,5,7)))
+
+class MiscTest(TestCase):
+ intersect_cases = [
+ ([],[],False),
+ ([],[1],False),
+ ([1],[2],False),
+ ([1,3,5],[2,4,6],False),
+ ([1,3,7],[2,3,1],True),
+ ([1,2,3],[3,2,1],True),
+ ([1,3,3],[2,3,4],True),
+ ]
+ intersect_classes = [ list, tuple, set, frozenset ]
+
+ def test_intersects(self):
+ "test intersects() helper"
+ from bps.basic import intersects
+ for a,b,real in self.intersect_cases:
+ for ac in self.intersect_classes:
+ ao = ac(a)
+ for bc in self.intersect_classes:
+ bo = bc(b)
+ result = intersects(ao,bo)
+ self.assertEquals(result, real, "intersects(%r, %r):" % (ao,bo))
+
+ def test_enum_slice(self):
+ from bps.basic import enum_slice
+ def func(*a, **k):
+ return list(enum_slice(*a, **k))
+ self.check_function_results(func, [
+ #without arguments
+ ak([],''),
+ ak([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')],
+ 'abcdef'),
+
+ #with stop
+ ak([],
+ 'abcdef', 0),
+ ak([(0, 'a')],
+ 'abcdef', 1),
+ ak([(0, 'a'), (1, 'b')],
+ 'abcdef', 2),
+ ak([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')],
+ 'abcdef', -2),
+
+ #with start+no stop
+ ak([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')],
+ 'abcdef', None, None),
+ ak([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')],
+ 'abcdef', 0, None),
+ ak([(1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')],
+ 'abcdef', 1, None),
+ ak([(2, 'c'), (3, 'd'), (4, 'e'), (5, 'f')],
+ 'abcdef', 2, None),
+ ak([(4, 'e'), (5, 'f')],
+ 'abcdef', -2, None),
+
+ #with start+stop
+ ak([(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')],
+ 'abcdef', 0, -1),
+ ak([(1, 'b'), (2, 'c'), (3, 'd')],
+ 'abcdef', 1, 4),
+ ak([(2, 'c'), (3, 'd'), (4, 'e')],
+ 'abcdef', 2, 5),
+ ak([(2, 'c'), (3, 'd')],
+ 'abcdef', -4, 4),
+
+ #with postive step
+ ak([(1, 'b'), (3, 'd'), (5, 'f')],
+ 'abcdef', 1, None, 2),
+
+ #with negative step
+ ak([],
+ 'abcdef', 2, -1, -1),
+ ak([],
+ 'abcdef', 2, 3, -1),
+ ak([(2, 'c'), (1, 'b'), (0, 'a')],
+ 'abcdef', 2, None, -1),
+ ak([(4, 'e'), (3, 'd'), (2, 'c'), (1, 'b'), (0, 'a')],
+ 'abcdef', 4, None, -1),
+ ak([(4, 'e'), (3, 'd'), (2, 'c'), (1, 'b')],
+ 'abcdef', 4, 0, -1),
+ ak([(4, 'e'), (2, 'c'), (0, 'a')],
+ 'abcdef', 4, None, -2),
+ ak([(4, 'e'), (2, 'c')],
+ 'abcdef', 4, 0, -2),
+ ])
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_fs.py b/bps/tests/test_fs.py
new file mode 100755
index 0000000..85120b3
--- /dev/null
+++ b/bps/tests/test_fs.py
@@ -0,0 +1,1321 @@
+"""bps3.fs unittest script"""
+
+#TODO: test filesystem property methods
+#TODO: test file manipulation methods
+#TODO: test dir manipulation methods
+#TODO: test symlink manipulation methods
+#TODO: test expand() method & shortcut functions
+
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import time
+import os.path
+import stat
+from functools import partial
+SEP = os.path.sep
+PAR = os.path.pardir
+CUR = os.path.curdir
+#package
+from bps.error import types as errors
+from bps.fs import filepath, FilePath, is_filepath, os_has_symlinks, parse_mode_mask, repr_mode_mask, chmod
+from bps.tests.utils import TestCase, get_tmp_path, ak
+#local
+if SEP == "/":
+ def local(path):
+ return path
+else:
+ def local(path):
+ return path.replace("/", SEP)
+
+#=========================================================
+#filepath function
+#=========================================================
+class ConstructorTest(TestCase):
+ "test filepath() constructor"
+ def test_none(self):
+ "test None behavior"
+ self.assertIs(filepath(None), None)
+
+ various_data = [
+ #arg1 [ arg2 ... ] result
+
+ #single element
+ ("", ""),
+ ("a", "a"),
+ (CUR, CUR),
+ (PAR, PAR),
+
+ #multiple element
+ ("a", "a", "a" + SEP + "a"),
+ ("a", "b", "c", "a" + SEP + "b" + SEP + "c"),
+
+ #elements containing seps
+ ("a" + SEP + "b", "c", "a" + SEP + "b" + SEP + "c"),
+ ("a" + SEP + "b" + SEP, "c", "a" + SEP + "b" + SEP + "c"),
+
+ ]
+
+ def test_various(self):
+ "test assorted inputs"
+ for row in self.various_data:
+ path = filepath(*row[:-1])
+ self.assert_(isinstance(path, FilePath))
+ self.assert_(is_filepath(path))
+ self.assertEqual(path, row[-1])
+
+ def test_duplicate(self):
+ "test filepath caching"
+ for row in self.various_data:
+ self.assertIs(filepath(*row[:-1]), filepath(*row[:-1]))
+
+#=========================================================
+#test path composition
+#=========================================================
+
+#we need somewhere to use as a base for the abspath tests
+cwd = os.path.abspath(os.getcwd())
+if os.name == "nt":
+ cwdcan = os.path.normcase(cwd)
+ abase = "c:\\dev"
+else:
+ cwdcan = os.path.realpath(cwd)
+ abase = "/testing"
+assert os.path.isdir(cwd)
+assert not cwd.endswith(SEP)
+
+class PathTest(TestCase):
+ "test filesystem-independant FilePath methods"
+
+ #=========================================================
+ #test filepath component attrs
+ #=========================================================
+ component_data = [
+ # path = dir + name = root + ext
+ # name = base + ext
+
+ #paths w/o dir part
+ dict(source=["a"], dir="",
+ name="a", base="a", ext="", root="a"),
+ dict(source=["a.jpg"], dir="",
+ name="a.jpg", base="a", ext=".jpg", root="a"),
+ dict(source=[".private"], dir="",
+ name=".private", base=".private", ext="", root=".private"),
+ dict(source=[".private.png"],
+ dir="", name=".private.png", base=".private", ext=".png", root=".private"),
+
+ #paths w/ dir part
+ dict(source=["aaa","bbb",".private.png"],
+ path="aaa" + SEP + "bbb" + SEP + ".private.png",
+ dir="aaa" + SEP + "bbb",
+ name=".private.png",
+ base="aaa" + SEP + "bbb" + SEP + ".private",
+ ext=".png",
+ root=".private"),
+ ]
+
+ def test_components(self):
+ "test parsing of path components"
+ self._run_attr_test(self.component_data)
+
+ #=========================================================
+ #test normpath & parentpath
+ #=========================================================
+ np_data = [
+ dict(source=['aaa', 'bbb', '.private.png'],
+ parentpath="aaa" + SEP + "bbb",
+ normpath="aaa" + SEP + "bbb" + SEP + ".private.png",
+ ),
+
+ dict(source=[PAR, 'aaa', 'bbb'],
+ parentpath=PAR + SEP + 'aaa',
+ normpath=PAR + SEP + 'aaa' + SEP + 'bbb'
+ ),
+
+ dict(source=['aaa', PAR, 'bbb'],
+ parentpath=CUR,
+ normpath='bbb',
+ ),
+
+ dict(source=[''], #empty path - poorly defined what this is.
+ #can't open it as a file anywhere.
+ #windows treats it as a dir(can list, norm=CUR) ,
+ #unix leaves it alone (norm='', no list or open).
+ #until overriding reason is found to force one behavior,
+ #just going w/ os-specific here
+ parentpath=CUR,
+ normpath=CUR,
+ dir='', name='', ext='', root='', base='',
+ ),
+
+ dict(source=[CUR], #cur dir - should return parent dir
+ parentpath=PAR,
+ normpath=CUR,
+ dir='', name=CUR, ext='', root=CUR, base=CUR,
+ ),
+
+ dict(source=[PAR], #par dir - should return parent / parent
+ parentpath=PAR + SEP + PAR,
+ normpath=PAR,
+ dir='', name=PAR, ext='', root=PAR, base=PAR,
+ ),
+
+ dict(source=[PAR, 'xxx'], #par dir - should return parent / parent
+ parentpath=PAR,
+ normpath=PAR + SEP + 'xxx',
+ dir=PAR, name='xxx', ext='', root='xxx', base=PAR + SEP + 'xxx',
+ ),
+ ]
+
+ def test_np(self):
+ "test normpath & parentpath"
+ self._run_attr_test(self.np_data)
+
+ def test_contained_in_path(self):
+ "test filepath.contained_in_path()"
+ source = filepath("x", "y")
+ target = source / "z"
+ self.assert_(target.contained_in_path(source))
+ self.assert_(target.contained_in_path(source, strict=True))
+
+ self.assert_(target.contained_in_path(target))
+ self.assert_(not target.contained_in_path(target, strict=True))
+
+ self.assert_(not source.contained_in_path(target))
+ self.assert_(not source.contained_in_path(target, strict=True))
+
+ #=========================================================
+ #test derived path attrs
+ #=========================================================
+ derived_data = [
+ dict(source=["a"],
+ normpath="a",
+ abspath=cwd + SEP + "a",
+ parentpath=CUR,
+ canonpath=cwdcan + SEP + "a",
+ ),
+
+ #CUR/PAR combinations
+ dict(source="", normpath=CUR, parentpath=CUR, abspath=cwd), #XXX: this treats "" like a file. is that right?
+ dict(source=[CUR], normpath=CUR, parentpath=PAR),
+ dict(source=[PAR], normpath=PAR, parentpath=PAR + SEP + PAR),
+ dict(source=[PAR, CUR], normpath=PAR, parentpath=PAR + SEP + PAR),
+ ]
+ def test_derived(self):
+ "test derived paths"
+ os.chdir(cwd) #so abspath will work
+ self._run_attr_test(self.derived_data)
+
+ gap_data = [
+ ("a", None, cwd + SEP + "a"),
+ ("a", cwd, cwd + SEP + "a"),
+ ("a", "xxx", cwd + SEP + 'xxx' + SEP + "a"),
+ (abase, None, abase),
+ (abase, "xxx", abase),
+ ]
+
+ def test_getabspath(self):
+ for source, start, value in self.gap_data:
+ result = filepath(source).getabspath(start)
+ self.assertEqual(result, value, "source=%r start=%r:" % (source, start))
+
+ def test_getrelpath(self):
+ "test filepath.getrelpath()"
+ for path, start, result in [
+ (['a', 'b'], ['a'], ['b']),
+ (['a', 'b'], ['a', 'd'], [PAR, 'b']),
+ (['a', 'b', 'c'], ['a', 'd', 'e'], [PAR, PAR, 'b', 'c']),
+ (['a', 'b', 'c'], ['x', 'y', 'z'], [PAR, PAR, PAR, 'a', 'b', 'c']),
+ (['a', 'b', 'c'], ['x', 'y', 'z', 'q'], [PAR, PAR, PAR, PAR, 'a', 'b', 'c']),
+ ]:
+
+ path = SEP.join(path)
+ start = SEP.join(start)
+ result = SEP.join(result)
+ out = filepath(path).getrelpath(start)
+ print [path, start, out, result]
+ self.assertEqual(out, result, "path=%r start=%r:"% (path, start))
+
+ def test_samepath(self):
+ #TODO: write real test for samepath
+ filepath(cwd).samepath(cwd)
+ filepath(cwd).samepath(cwd + SEP + "xxx")
+
+ #=========================================================
+ #expand tests
+ #=========================================================
+ def test_expand(self):
+ #TODO: write real test for expand
+
+ path = filepath(cwd)
+ #just make sure this doesn't throw errors for now
+ new = path.expand(all=True)
+
+ #=========================================================
+ #test string & joining operators
+ #=========================================================
+ def test_stringop(self):
+ "test string operations"
+ ax = "ax"
+ ab = "a" + SEP + "b"
+ abx = "a" + SEP + "bx"
+
+ #test __add__
+ self.assert_(isinstance(filepath("a") + "x", FilePath))
+ self.assertEqual(filepath("a") + "x", ax)
+
+ self.assertEqual(filepath("a") / "b" + "x", abx)
+
+ #test __radd__
+ self.assert_(isinstance("x" + filepath("a"), FilePath))
+ self.assertEqual("x" + filepath("a"), "xa")
+
+ def test_joiners(self):
+ "test div and joinXXX operations"
+ ab = "a" + SEP + "b"
+ abc = "a" + SEP + "b" + SEP + "c"
+
+ #test __div__
+ self.assertEqual(filepath("a") / "b", ab)
+ self.assertEqual(filepath("a") / ("b", "c"), abc)
+
+ #test __div__ w/ strings & filepaths mixed
+ self.assertEqual(filepath("a") / filepath("b"), ab)
+ self.assertEqual(filepath("a") / (filepath("b"), "c"), abc)
+
+ #test chained div
+ self.assertEqual(filepath("a") / filepath("b") / filepath("c"), abc)
+ self.assertEqual(filepath("a") / "b" / filepath("c"), abc)
+
+ #test joinsep .. since it's called by __div__, don't need much separate testing.
+ self.assertEqual(filepath("a").joinsep("b"), ab)
+ self.assertEqual(filepath("a").joinsep("b", "c"), abc)
+
+ #=========================================================
+ #helpers
+ #=========================================================
+
+ def _run_attr_test(self, data):
+ "helper for test_derived / test_components etc"
+ for row in data:
+ source = row['source']
+ if isinstance(source, (list, tuple)):
+ path = filepath(*source)
+ else:
+ path = filepath(source)
+ for key in row:
+ if key == "path":
+ self.assertEqual(path, row[key])
+ elif key != "source":
+ value = getattr(path, key)
+ real = row[key]
+ self.assertEqual(value, real, "source=%r attr=%r ... got=%r expected=%r" % (source, key, value, real))
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#fs interaction
+#=========================================================
+class _InteractionTest(TestCase):
+ "base class for fs interaction tests"
+ #=========================================================
+ #setup/teardown - create a tmp path for each test to use if needed
+ #=========================================================
+ def setUp(self):
+ self._paths = []
+
+ def tearDown(self):
+ for path in self._paths:
+ path.discard()
+
+ #=========================================================
+ #path creation funcs
+ #=========================================================
+ def create_path(self):
+ """create new path whose parent dir exists, but it doesn't.
+ automatically cleaned up after test completes"""
+ path = get_tmp_path()
+ assert not path.lexists
+ assert path.parentpath.isdir
+ self._paths.append(path)
+ return path
+
+ def create_noparent(self):
+ "return path whose parent doesn't exist"
+ base = self.create_path()
+ self.assert_(base.ismissing)
+ path = base / "notapath"
+ self.assert_(path.ismissing)
+ return path
+
+ def create_missing(self):
+ "return path whose parentdir exists, but path doesn't"
+ path = self.create_path()
+ self.assert_(path.parentpath.isdir)
+ return path
+
+ def create_file(self, content="qwerty"):
+ "return path which is a file"
+ path = self.create_path()
+ path.set(content)
+ self.assert_(path.isfile and path.get() == content)
+ return path
+
+ def create_parentfile(self):
+ "return path whose parent is a file"
+ base = self.create_file()
+ path = base / "notpath"
+ self.assert_(path.ismissing)
+ return path
+
+ def create_dir(self):
+ "create path which is a dir"
+ path = self.create_path()
+ path.mkdir()
+ self.assert_(path.isdir)
+ return path
+
+ #=========================================================
+ #preset creation & testing funcs (used by move/copy)
+ #=========================================================
+ def create_file_style1(self):
+ return self.create_file("qwerty")
+
+ def check_file_style1(self, path):
+ self.check_file(path, "qwerty", 1)
+
+ def create_dir_style1(self):
+ "create path which is a dir and has content (1 file and 1 dir)"
+ # path/
+ # test.file: qwerty
+ # test.dir/
+ # test.txt: hello world
+ # test.link> test.txt
+ # broken.link> ../notafile.notthere
+ path = self.create_path()
+ path.mkdir()
+ self.assert_(path.isdir)
+ (path / "test.file").set("qwerty")
+ (path / "test.dir").mkdir()
+ (path / "test.dir" / "test.txt").set("hello world")
+ if os_has_symlinks:
+ (path / "test.dir" / "test.link").mklink("../test.file")
+ (path / "test.dir" / "broken.link").mklink("../notafile.notthere")
+ return path
+
+ def check_dir_style1(self, path, copy_symlinks=True):
+ self.check_dir(path, ['test.file', 'test.dir'])
+ self.check_file(path / "test.file", 'qwerty')
+ if os_has_symlinks:
+ if copy_symlinks:
+ self.check_dir(path / 'test.dir', ['test.txt', 'test.link', 'broken.link'])
+ self.check_file_link(path / 'test.dir' / 'test.link', '../test.file', 'qwerty')
+ self.check_link(path / "test.dir" / "broken.link", "../notafile.notthere", broken=True)
+ else:
+ self.check_dir(path / 'test.dir', ['test.txt', 'test.link'])
+ self.check_file(path / 'test.dir' / 'test.link', 'qwerty')
+ else:
+ self.check_dir(path / 'test.dir', ['test.txt'])
+ self.check_file(path / 'test.dir' / 'test.txt', 'hello world')
+
+ #=========================================================
+ #check funcs - verify properties are reported correctly
+ # for various types of files
+ #=========================================================
+
+ #-----------------------------------------------
+ #missing
+ #-----------------------------------------------
+ def check_missing(self, path, link=False):
+ "check missing path properties"
+ self.assertEqual(path.filetype, "missing")
+ self.assertEqual(path.lfiletype, "link" if link else "missing")
+ self.assertEqual(path.exists, False)
+ self.assertEqual(path.lexists, link)
+ self.assertEqual(path.isdir, False)
+ self.assertEqual(path.isfile, False)
+ self.assertEqual(path.islink, link)
+ self.assertEqual(path.ismissing, True)
+ self.assertEqual(path.ismount, False)
+ self.assertAttrRaises(errors.MissingPathError, path, "atime")
+ self.assertAttrRaises(errors.MissingPathError, path, "ctime")
+ self.assertAttrRaises(errors.MissingPathError, path, "mtime")
+ self.assertAttrRaises(errors.MissingPathError, path, "size")
+ self.assertAttrRaises(errors.MissingPathError, path, "linecount")
+ self.assertAttrRaises(errors.MissingPathError, path, "dircount")
+
+ #-----------------------------------------------
+ #dir
+ #-----------------------------------------------
+ def check_empty_dir(self, path, **kwds):
+ self.check_dir(path, [], **kwds)
+
+ def check_dir(self, path, content=None, created=None, link=False):
+ "check various dir-readers, given directory path and (correct) contents"
+
+ #check filetypes
+ self.assertEqual(path.filetype, "dir")
+ self.assertEqual(path.lfiletype, "link" if link else "dir")
+ self.assertEqual(path.exists, True)
+ self.assertEqual(path.lexists, True)
+ self.assertEqual(path.isdir, True)
+ self.assertEqual(path.isfile, False)
+ self.assertEqual(path.islink, link)
+ self.assertEqual(path.ismissing, False)
+ self.assertEqual(path.ismount, False)
+
+ #check times
+ path.atime #just make sure it works, can't be sure it'll be honored
+ path.ctime
+ path.mtime
+ if created:
+ tick_start, tick_stop = created
+ self.assert_(tick_start <= path.ctime <= tick_stop)
+ self.assert_(tick_start <= path.mtime <= tick_stop)
+
+ #check relative listdir
+ if content is not None:
+ self.assertElementsEqual(path.listdir(), content)
+ self.assertElementsEqual(list(path.iterdir()), content)
+
+ #check full listdir
+ if content is not None:
+ content = [ path / elem for elem in content ]
+ self.assertElementsEqual(path.listdir(full=True), content)
+ self.assertElementsEqual(list(path.iterdir(full=True)), content)
+
+ #check other
+ path.size #what should this report for various OSes?
+ if content is not None:
+ self.assertEqual(path.dircount, len(content))
+ else:
+ self.assert_(path.dircount >= 0)
+ path.linecount #NOTE: in future, should raise ExpectedFileError
+
+ #-----------------------------------------------
+ #file
+ #-----------------------------------------------
+ def check_file(self, path, content=None, lines=None, created=None, link=False):
+ "check file properties"
+
+ #check filetypes
+ self.assertEqual(path.filetype, "file")
+ self.assertEqual(path.lfiletype, "link" if link else "file")
+ self.assertEqual(path.exists, True)
+ self.assertEqual(path.lexists, True)
+ self.assertEqual(path.isdir, False)
+ self.assertEqual(path.isfile, True)
+ self.assertEqual(path.islink, link)
+ self.assertEqual(path.ismissing, False)
+ self.assertEqual(path.ismount, False)
+
+ #check times
+ path.atime #just make sure it works, can't be sure it'll be honored
+ path.ctime
+ path.mtime
+ if created:
+ tick_start, tick_stop = created
+ self.assert_(tick_start <= path.ctime <= tick_stop)
+ self.assert_(tick_start <= path.mtime <= tick_stop)
+
+ #check other
+ if content is None:
+ self.assert_(path.size >= 0)
+ else:
+ self.assertEqual(path.size, len(content))
+ self.assertAttrRaises(errors.ExpectedDirError, path, "dircount")
+ if lines is not None:
+ self.assertEqual(path.linecount, lines)
+ else:
+ self.assert_(path.linecount >= 0)
+
+ #check content
+ if content is not None:
+ self.assertEqual(path.get(), content)
+
+ #-----------------------------------------------
+ #links
+ #-----------------------------------------------
+ def check_link(self, path, target=None, broken=None):
+ self.assert_(path.lexists)
+ self.assertEqual(path.lfiletype, "link")
+ if broken:
+ self.assertEqual(path.filetype, "missing")
+ self.assert_(path.ismissing)
+ elif broken is False:
+ self.assertNotEqual(path.filetype, "missing")
+ self.assert_(path.exists)
+
+ if broken is False:
+ path.atime
+ path.ctime
+ path.mtime
+ if path.isdir:
+ path.dircount
+ elif path.isfile:
+ path.linecount
+
+ if target is not None:
+ self.assertEqual(path.ltarget, target)
+
+ def check_file_link(self, path, target, content=None, broken=None):
+ self.check_link(path, target, broken=broken)
+ self.check_file(path, content, link=True)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#TODO: test filepath.walk() - esp followlinks behavior (since it's not available under py25)
+#TODO: test filepath.mode, filepath.modestr
+
+class _MoveCopyTest(_InteractionTest):
+ "common tests used by both move_to and copy_to"
+ copy = False
+ copy_symlinks = True
+
+ def gf(self, path):
+ if self.copy:
+ if not self.copy_symlinks:
+ return partial(path.copy_to, followlinks=True)
+ else:
+ return path.copy_to
+ else:
+ return path.move_to
+
+ def check_output_dir_style1(self, *a, **k):
+ if not self.copy_symlinks:
+ k['copy_symlinks'] = False
+ return self.check_dir_style1(*a, **k)
+
+ #=========================================================
+ #test boundary cases
+ #=========================================================
+ def test_bad_mode(self):
+ "test invalid mode value"
+ source = self.create_file()
+ target = self.create_path()
+ self.assertRaises(ValueError, self.gf(source), target, mode="not a mode")
+
+
+ #=========================================================
+ #test source/target errors common to all modes
+ #=========================================================
+ def test_source_missing(self):
+ "test handling of missing source, for all target types and move modes"
+ source = self.create_missing()
+ for target in (self.create_noparent(), self.create_missing(), self.create_file(), self.create_dir()):
+ for mode in ("exact", "child", "smart"):
+ self.assertRaises(errors.MissingPathError, self.gf(source), target, mode=mode)
+
+ def test_target_noparent(self):
+ "test handling of target's parent dir being missing, for all source types and move modes"
+ target = self.create_noparent()
+ for source in (self.create_file(), self.create_dir(), self.create_dir_style1()):
+ for mode in ("exact", "child", "smart"):
+ self.assertRaises(errors.MissingPathError, self.gf(source), target, mode=mode)
+
+ def test_target_file(self):
+ "test handling of file located as target, for all source types and move modes (except child)"
+ for mode in ("exact", "smart"):
+ for source in (self.create_file(), self.create_dir(), self.create_dir_style1()):
+ target = self.create_file()
+ #move should raise error
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode=mode,
+ __msg__="source=%r mode=%r:" % (source.filetype, mode))
+ #but this one should be successful
+ st = source.filetype
+ self.gf(source)(target, mode=mode, force=True)
+ if self.copy:
+ self.assertEqual(source.filetype, st)
+ else:
+ self.assertEqual(source.filetype, "missing")
+ self.assertEqual(target.filetype, st)
+
+ def test_child_target_file(self):
+ "test handling of file located as target, for child mode"
+ for source in (self.create_file(), self.create_dir(), self.create_dir_style1()):
+ target = self.create_file()
+ self.assertRaises(errors.ExpectedDirError, self.gf(source), target, mode="child",
+ __msg__="source=%r:" % (source.filetype, ))
+
+ #=========================================================
+ #exact mode
+ #=========================================================
+ #source: file, (full) dir
+ #target: missing, dir
+
+ def test_exact_file_missing(self):
+ source = self.create_file_style1()
+ target = self.create_missing()
+
+ self.gf(source)(target)
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(target)
+
+ def test_exact_file_dir(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target)
+ self.check_file_style1(source)
+ self.check_dir(target, [])
+
+ self.gf(source)(target, force=True)
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(target)
+
+ def test_exact_dir_missing(self):
+ source = self.create_dir_style1()
+ target = self.create_missing()
+
+ self.gf(source)(target)
+ if self.copy:
+ self.check_dir_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(target)
+
+ def test_exact_dir_dir(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ temp = target / 'xxx'
+ temp.set("yyy")
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target)
+ self.check_dir_style1(source)
+ self.check_dir(target, ['xxx'])
+
+ self.gf(source)(target, force=True)
+ if self.copy:
+ self.check_dir_style1(source)
+ self.check_file(temp, 'yyy'); temp.remove()
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(target)
+
+ #=========================================================
+ #child mode
+ #=========================================================
+ #source: file, (full) dir
+ #target: missing, dir, dir with source in the way
+
+ def test_child_file_missing(self):
+ source = self.create_file_style1()
+ target = self.create_missing()
+
+ self.assertRaises(errors.MissingPathError, self.gf(source), target, mode="child")
+ self.check_file_style1(source)
+ self.check_missing(target)
+
+ def test_child_file_dir(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+ result = target / source.name
+
+ self.gf(source)(target, mode="child")
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(result)
+
+ def test_child_file_dir_occupied_file(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.set("xxx")
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="child")
+ self.check_file_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_file(result, 'xxx')
+
+ self.gf(source)(target, mode="child", force=True)
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(result)
+
+ def test_child_file_dir_occupied_dir(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.mkdir()
+ temp = result / 'xxx'
+ temp.set('yyy')
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="child")
+ self.check_file_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_dir(result, ['xxx'])
+ self.check_file(temp, 'yyy')
+
+ self.gf(source)(target, mode="child", force=True)
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(result)
+
+ def test_child_dir_missing(self):
+ source = self.create_dir_style1()
+ target = self.create_missing()
+
+ self.assertRaises(errors.MissingPathError, self.gf(source), target, mode="child")
+ self.check_dir_style1(source)
+ self.check_missing(target)
+
+ def test_child_dir_dir(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ result = target / source.name
+
+ self.gf(source)(target, mode="child")
+ if self.copy:
+ self.check_dir_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(result)
+
+ def test_child_dir_dir_occupied_file(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.set('xxx')
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="child")
+ self.check_dir_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_file(result, 'xxx')
+
+ self.gf(source)(target, mode="child", force=True)
+ if self.copy:
+ self.check_dir_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(result)
+
+ def test_child_dir_dir_occupied_dir(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.mkdir()
+ temp = result / 'xxx'
+ temp.set('yyy')
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="child")
+ self.check_dir_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_dir(result, ['xxx'])
+ self.check_file(temp, 'yyy')
+
+ self.gf(source)(target, mode="child", force=True)
+ if self.copy:
+ self.check_dir_style1(source)
+ self.check_file(temp, 'yyy'); temp.remove()
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(result)
+
+ #=========================================================
+ #smart mode
+ #=========================================================
+ #source: file, (full) dir
+ #target: missing, dir, dir with source in the way
+
+ def test_smart_file_missing(self):
+ source = self.create_file_style1()
+ target = self.create_missing()
+
+ self.gf(source)(target, mode="smart")
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(target)
+
+ def test_smart_file_dir(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+ result = target / source.name
+
+ self.gf(source)(target, mode="smart")
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(result)
+
+ def test_smart_file_dir_occupied_file(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.set("xxx")
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="smart")
+ self.check_file_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_file(result, 'xxx')
+
+ self.gf(source)(target, mode="smart", force=True)
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(result)
+
+ def test_smart_file_dir_occupied_dir(self):
+ source = self.create_file_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.mkdir()
+ temp = result / 'xxx'
+ temp.set('yyy')
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="smart")
+ self.check_file_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_dir(result, ['xxx'])
+ self.check_file(temp, 'yyy')
+
+ self.gf(source)(target, mode="smart", force=True)
+ if self.copy:
+ self.check_file_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_file_style1(result)
+
+ def test_smart_dir_missing(self):
+ source = self.create_dir_style1()
+ target = self.create_missing()
+
+ self.gf(source)(target, mode="smart")
+ if self.copy:
+ self.check_dir_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(target)
+
+ def test_smart_dir_dir(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ result = target / source.name
+
+ self.gf(source)(target, mode="smart")
+ if self.copy:
+ self.check_dir_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(result)
+
+ def test_smart_dir_dir_occupied_file(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.set('xxx')
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="smart")
+ self.check_dir_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_file(result, 'xxx')
+
+ self.gf(source)(target, mode="smart", force=True)
+ if self.copy:
+ self.check_dir_style1(source)
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(result)
+
+ def test_smart_dir_dir_occupied_dir(self):
+ source = self.create_dir_style1()
+ target = self.create_dir()
+ result = target / source.name
+ result.mkdir()
+ temp = result / 'xxx'
+ temp.set('yyy')
+
+ self.assertRaises(errors.PathExistsError, self.gf(source), target, mode="smart")
+ self.check_dir_style1(source)
+ self.check_dir(target, [source.name])
+ self.check_dir(result, ['xxx'])
+ self.check_file(temp, 'yyy')
+
+ self.gf(source)(target, mode="smart", force=True)
+ if self.copy:
+ self.check_dir_style1(source)
+ self.check_file(temp, 'yyy'); temp.remove()
+ else:
+ self.check_missing(source)
+ self.check_output_dir_style1(result)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+class MoveTest(_MoveCopyTest):
+ """test PathType.move_to():
+
+ for each mode, behavior should be checked for all combinations
+ of source over the range of values:
+ missing - source missing
+ dir - source is a dir
+ file - source is a file
+ and for target over the range of values:
+ pfile - target is missing, parent is not a dir
+ noparent - target & parent dir missing
+ missing - target missing, parent dir exists
+ file - target is file
+ dir - target is dir
+
+ exact mode:
+ noparent, missing file dir
+ pfile
+
+ missing error error error error
+
+ file error success error error
+
+ dir error success error error
+
+ child mode:
+ noparent, missing file dir
+ pfile
+
+ missing error error error error
+
+ file error error error success
+
+ dir error error error success
+
+ smart mode:
+ noparent, missing file dir
+ pfile
+
+ missing error error error error
+
+ file error success error success
+
+ dir error success error success
+
+ Thus source missing, target noparent, and target file should always raise an error.
+ The others are dependant on the mode.
+ Each test is thus named "test_{mode}_{source type}_{target type}"
+ """
+ _prefix = "PathType.move_to()"
+ copy = False
+
+ def test_target_in_source(self):
+ "test target in source detection"
+ source = self.create_dir()
+ target = source / "z"
+ self.assertRaises(ValueError, self.gf(source), target)
+ self.assertRaises(ValueError, self.gf(source), source)
+
+class CopyTest(_MoveCopyTest):
+ #MoveTest class handles copy_test as well, copy=True flag makes it change behavior
+ _prefix = "path.copy_to()"
+ copy = True
+ copy_symlinks = False
+
+ def test_target_in_source(self):
+ "test target in source"
+ source = self.create_dir()
+ self.assertRaises(ValueError, self.gf(source), source)
+
+ target = source / "z"
+ self.gf(source)(target)
+ self.check_dir(source, ['z'])
+ self.check_dir(target, [])
+
+ def test_force_recursion(self):
+ #make sure force flag is preserved during recursion (bug fixed r7192)
+ source = self.create_dir_style2()
+ target = self.create_dir_style2a()
+ source.copy_to(target, force=True)
+ self.check_dir_style2(source)
+ self.check_dir_style2(target)
+
+ def create_dir_style2(self, content='xxx'):
+ "dir structure used by test_force_recursion to detect deep failure of force kwd"
+ source = self.create_dir()
+ stemp = source / 'test.dir' / 'really'
+ stemp.mkdir(parents=True)
+ stemp2 = stemp / 'test.txt'
+ stemp2.set(content)
+ return source
+
+ def check_dir_style2(self,path,content='xxx'):
+ self.check_dir(path,['test.dir'])
+ self.check_dir(path / 'test.dir',['really'])
+ self.check_dir(path / 'test.dir' / 'really',['test.txt'])
+ self.check_file(path / 'test.dir' / 'really' / 'test.txt',content)
+
+ def create_dir_style2a(self):
+ return self.create_dir_style2(content='yyy')
+
+ def check_dir_style2a(self, path):
+ self.check_dir_style2(path,content='yyy')
+
+class CopySymTest(_MoveCopyTest):
+ _prefix = "path.copy_to(symlinks=True)"
+ copy = True
+
+#=========================================================
+#scripts
+#=========================================================
+class ScriptTest(_InteractionTest):
+ "composite fs interaction tests"
+
+ def test_00_script(self):
+ "run through some file creation tests"
+ base = get_tmp_path()
+ self.check_missing(base)
+ self._paths.append(base)
+
+ #--------------------------------------------------------------
+ #make a directory
+ #--------------------------------------------------------------
+ assert base.parentpath.isdir, "parent directory missing"
+ tick_start = int(time.time())
+ base.mkdir()
+ tick_stop = max(tick_start+1, int(time.time()))
+
+ #check fs properties of a directory
+ self.check_empty_dir(base, created=[tick_start, tick_stop])
+ orig_mtime = base.mtime
+ time.sleep(1) #wait a second, so file's mtime will be different
+
+ #--------------------------------------------------------------
+ #make a file
+ #--------------------------------------------------------------
+ fname = "imafile.txt"
+ fpath = base / fname
+ self.assertEqual(fpath, base + SEP + fname)
+ self.assertEqual(fpath.filetype, "missing")
+ tick_start = int(time.time())
+ with fpath.open(mode="wb") as fh:
+ fh.write("123\x00")
+ tick_stop = max(tick_start+1, int(time.time()))
+
+ #check we can read it
+ self.check_file(fpath, "123\x00", 1, created=[tick_start, tick_stop])
+
+ #check dir properties
+ self.assert_(base.mtime > orig_mtime) #xxx: only true if os honors dir_mtime
+ self.check_dir(base, [fname])
+
+ #--------------------------------------------------------------
+ #truncate a file
+ #--------------------------------------------------------------
+ fpath.clear()
+ self.check_file(fpath, '')
+
+ #--------------------------------------------------------------
+ #test get/set
+ #--------------------------------------------------------------
+ fpath.set("a\r\nb\nc")
+ self.assertEqual(fpath.get(text=True), "a\nb\nc")
+ self.assertEqual(fpath.get(), "a\r\nb\nc")
+
+ #--------------------------------------------------------------
+ #test remove
+ #--------------------------------------------------------------
+ self.assert_(fpath.exists)
+ fpath.remove()
+ self.check_missing(fpath)
+ self.assertRaises(errors.MissingPathError, fpath.remove)
+
+ #TODO: test removing a symlink to a dir removes just the link
+
+ #test discard w/o path
+ fpath.discard()
+
+ #test discard w/ path
+ fpath.set("")
+ self.assert_(fpath.exists)
+ fpath.discard()
+
+ #--------------------------------------------------------------
+ #test dir's clear
+ #--------------------------------------------------------------
+ fpath.set("")
+ self.check_dir(base, [fname])
+ base.clear()
+ self.check_dir(base, [])
+ base.clear()
+
+ #--------------------------------------------------------------
+ #remove base dir
+ #--------------------------------------------------------------
+ base.remove()
+ self.assertEqual(base.filetype, "missing")
+ self.assertRaises(errors.MissingPathError, base.remove)
+ base.mkdir()
+ self.assertEqual(base.filetype, "dir")
+ base.discard()
+ self.assertEqual(base.filetype, "missing")
+ base.discard()
+
+#=========================================================
+#
+#=========================================================
+class ModeTest(TestCase):
+ """test chmod support"""
+ #TODO: chmod testing
+ # mode, mode+dirmode, mode+filemode
+ # followlinks
+ #called on file, called on dir
+
+
+ def test_parse_mode_mask(self):
+ for value in [
+ -1,
+ 1+07777,
+ (1+07777, 0),
+ (0, 1+07777),
+ (457, 3639),
+ "x", "u",
+ "v=",
+ "u=q", "u=g",
+ "a+r,o",
+ ]:
+ self.assertRaises(ValueError, parse_mode_mask, value, __msg__="%r:" % (value, ))
+
+ for input, bits, preserve in [
+ #integers
+ ((0, 0), 0, 0),
+ ((0, 123), 0, 123),
+ (456, 456, 0),
+
+ #simple
+ ("", 0, 07777),
+ ("a+", 0, 07777),
+ ("a-", 0, 07777),
+
+ ("a=", 0, 0),
+ ("u=,g=,o=", 0, 0),
+ ("ugo=", 0, 0),
+
+ #random ones
+ ("u+r,g=w,o=t", 784, 2240),
+ ("u+tr,g=w,o=t", 784, 2240),
+ ]:
+ result = parse_mode_mask(input)
+ self.assertEqual(result, (bits, preserve), "%r:" % (input, ))
+
+ def test_repr_mode_mask(self):
+ self.check_function_results(repr_mode_mask, [
+ ak("u=w,g=rw", "ug=w,g+r"),
+ ak("u=rw,g=r", "ug=rw,g-wx"),
+ ak("ug+r,o+r-x", "a+r,o-x"),
+ ak("ug=rwx,o=r", "u=rwx,g=rwx,o=r"),
+ ak("a=w", "u=w,g=w,o=rwx,a-rx"),
+ ak("", ""),
+ ak("a=", "a="),
+
+ ak("0444", "a=r", octal="prefer"),
+ ak("0444", "a=r", octal="always"),
+ ak("a+r", "a+r", octal="prefer"),
+
+ #real cases
+ ak("u=rw,g=r,o=", "u=rw,g=r,o="),
+ ak("ug+x", "ug+x"),
+ ak("ug=rw,o=", "ug=rw,o="),
+ ak("u+x,g+xs", "u+x,g+xs"),
+ ])
+ self.assertRaises(ValueError, repr_mode_mask, "a+r", octal="always")
+
+##
+## chmod(target, dict(all=all_mode, file=file_mode, dir=dir_mode), recursive=True)
+##
+## #config - app_group can read, root is real owner
+## #NOTE: could make sure parent dirs of home have o+rx
+## prepare(
+## target=[cfg.config_dir, cfg.home_dir],
+## user=root_user, group=app_group,
+## all_mode="u=rw,g=r,o=", dir_mode="ug+x",
+## )
+##
+## #state_dir, cache_dir - app user only!
+## paths = [cfg.state_dir, cfg.run_dir, cfg.cache_dir, log_dir]
+## prepare(paths, app_user, app_group, all_mode="ug=rw,o=", dir_mode="ug+x")
+##
+## #mail dir - owned by app user, but let share_group rw it as well (used by external apps)
+## prepare(cfg.mail_dir, app_user, share_group, all_mode="ug=rw,o=", dir_mode="ug+x,g+s")
+
+def ChangeModeTest(_InteractionTest):
+
+ # path/
+ # test.file: qwerty
+ # test.dir/
+ # test.txt: hello world
+ # test.link> test.txt
+ # broken.link> ../notafile.notthere
+
+ def assert_mode(self, path, mode):
+ self.assertEqual(path.modestr, mode)
+
+ def reset_mode(self, path):
+ chmod(path, "a=", recursive=True)
+
+ def assert_clear_style1(self, path, reset=False):
+ if reset:
+ self.clear_mode(path)
+ am = self.assert_mode
+ am(path, "a=")
+ am(path / 'test.file', "a=")
+ am(path / 'test.dir', 'a=')
+ am(path / 'test.dir' / 'test.txt', 'a=')
+ if os_has_symlinks:
+ am(path / 'test.dir' / 'test.link', 'a=')
+
+ def assert_style1(self, path, dm, fm):
+ am = self.assert_mode
+ am(path, dm)
+ am(path / 'test.file', fm)
+ am(path / 'test.dir', dm)
+ am(path / 'test.dir' / 'test.txt', fm)
+ if os_has_symlinks:
+ am(path / 'test.dir' / 'test.link', fm)
+
+ def test_script1(self):
+ am = self.assert_mode
+
+ #create dir to test
+ path = self.create_dir_style1()
+ self.assert_clear_style1(path, True)
+
+ #call chmod with some weird params, but no recursion
+ chmod(path, mode="ug+r,u+w", dirmode="+x", filemode="o+r")
+ dm = "u=rwx,g=rx,o=rx"
+ fm = "u=rw,g=r,o=rx"
+ self.assert_mode(path, dm)
+ path.mode = "a="
+ self.assert_clear_style1(path)
+
+ #call chmod with some weird params and recursion
+ self.assert_clear_style1(path, True)
+ chmod(path, mode="ug+r,u+w", dirmode="+x", filemode="o+r", recursive=True)
+ self.assert_style1(path, dm, fm)
+
+ #test removal
+ chmod(path, mode="og-x+w", recursive=True)
+ dm = "u=rwx,go=rw"
+ fm = "u=rw,go=rw"
+ self.assert_style1(path, dm, fm)
+
+#=========================================================
+#eof
+#=========================================================
diff --git a/bps/tests/test_host.py b/bps/tests/test_host.py
new file mode 100644
index 0000000..9195f86
--- /dev/null
+++ b/bps/tests/test_host.py
@@ -0,0 +1,142 @@
+"""bps3.hosts unittest script.
+
+.. warning::
+ In order to test the host detection properly,
+ this module does some heavy monkeypatching to the ``os`` module.
+ If something goes wrong, it may leave the ``os`` module seriously
+ messed up for the rest of the process' lifetime.
+ By seriously, I mean ``os.name`` reporting ``nt`` when under ``posix`` :)
+
+FIXME: should rewrite this to just run an os-specific set of checks
+for whatever os it's being run under.
+"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os.path
+import sys
+from unittest import TestCase
+from logging import getLogger
+from warnings import warn
+import warnings
+#site
+#pkg
+from bps.fs import filepath
+from bps.tests.utils import get_tmp_path, catch_warnings
+#module
+log = getLogger(__name__)
+
+#=========================================================
+#
+#=========================================================
+class EnvPathTest(TestCase):
+ "test of bps3.host.get_env_path()"
+ def setUp(self):
+ unload_host()
+ self.tmp_dir = get_tmp_path()
+ self.backup = {}
+
+ def tearDown(self):
+ unpatch_modules(self.backup)
+
+ if os.name == "nt":
+ def test_nt(self):
+ #===============
+ #FIXME: patching os module is a really horrible way to make this test happen.
+ # should just implement tests which run only on the correct os,
+ # and fake the dir structure, etc... that way we don't have to worry about fileops going wrong.
+ #===============
+
+ #create nt environ in temp dir
+ home = self.tmp_dir / "Documents and Settings" / "User"
+ home.ensuredirs()
+ (home / "Desktop").ensuredirs()
+ (home / "My Documents").ensuredirs()
+ config = home / "Application Data"
+ config.ensuredirs()
+ env = dict(
+ USERPROFILE=str(home),
+ PATH="c:\\Windows",
+ APPDATA=str(config),
+ PATHEXT=".wys;.wyg",
+ )
+ def winver():
+ return (0, 0, 0, 2, 0)
+ patch_modules(self.backup, **{
+ "os": dict(name="nt", environ=env),
+ "os.path": dict(pathsep=";", sep="\\"),
+ "sys": dict(getwindowsversion=winver),
+ })
+ self.assertEqual(os.name, "nt")
+
+ #import host, check backend
+ from bps import host
+ from bps.host.windows import WindowsBackend
+ self.assertTrue(isinstance(host._backend, WindowsBackend))
+ self.assertEqual(host._backend.profile, "nt")
+ self.assertEqual(host.exe_exts, ('.wys', '.wyg'))
+
+ #check env paths
+ paths = host.get_env_path("all_paths")
+ self.assertEqual(paths.home_dir, home)
+ self.assertEqual(paths.state_dir, config)
+ self.assertEqual(paths.desktop_dir, home / "Desktop")
+ self.assertEqual(paths.docs_dir, home / "My Documents")
+ self.assertEqual(paths.start_dir, home / "Desktop")
+
+ #check app paths
+ paths = host.get_app_path("xxx", "all_paths")
+ self.assertEqual(paths.state_dir, config / "xxx")
+ self.assertEqual(paths.cache_dir, config / "xxx" / "cache")
+ self.assertEqual(paths.lock_file, config / "xxx" / "xxx.pid")
+
+ #check app paths
+ paths = host.get_app_path("xxx/yyy", "all_paths")
+ self.assertEqual(paths.state_dir, config / "xxx" / "yyy")
+ self.assertEqual(paths.cache_dir, config / "xxx" / "yyy" / "cache")
+ self.assertEqual(paths.lock_file, config / "xxx" / "yyy" / "yyy.pid")
+
+ #test legacy funcs
+## message=r"bps\.host: function 'get(Resource|State)Path' is deprecated, use .*",
+## module=r"bps\.tests\.test_host",
+ with catch_warnings(record=True) as wmsgs:
+ self.assertEqual(host.getResourcePath("home"), home)
+ self.assertEqual(host.getResourcePath("desktop"), home / "Desktop")
+ self.assertEqual(host.getResourcePath("docs"), home / "My Documents")
+ self.assertEqual(host.getResourcePath("start"), home / "Desktop")
+ self.assertEqual(host.getStatePath("xxx/yyy.txt"), config / "xxx" / "yyy.txt")
+ #TODO: verify we get the right warning msgs back.
+ #should be 4 deprecation warnings for getResourcePath,
+ # and 1 for getStatePath
+ self.assertEqual(len(wmsgs), 5, str(", ".join(str(w) for w in wmsgs)))
+
+#=========================================================
+#helpers
+#=========================================================
+def unload_host():
+ if 'bps.host' in sys.modules:
+ del sys.modules['bps.host']
+
+def patch_modules(backup, **kwds):
+ for name, attrs in kwds.iteritems():
+ mod = __import__(name, fromlist=['dummy'])
+ if name in backup:
+ orig = backup[name]
+ else:
+ orig = backup[name] = {}
+ for k, v in attrs.iteritems():
+ if k not in orig:
+ orig[k] = getattr(mod, k, None)
+ setattr(mod, k, v)
+
+def unpatch_modules(backup):
+ for name, orig in backup.iteritems():
+ mod = __import__(name, fromlist=['dummy'])
+ for k, v in orig.iteritems():
+ setattr(mod, k, v)
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_logs.py b/bps/tests/test_logs.py
new file mode 100644
index 0000000..133dfc7
--- /dev/null
+++ b/bps/tests/test_logs.py
@@ -0,0 +1,309 @@
+"""
+bps.logs unittest script -- (c) Assurance Technologies 2003-2006
+defines unit tests for bps's logging package
+"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os
+import sys
+import logging
+from cStringIO import StringIO
+from warnings import warn
+import warnings
+#site
+#pkg
+from bps.fs import filepath
+from bps.logs import config as lc, handlers as lh, capture as cp, config_logging, add_handler
+from bps.logs.loggers import get_logger, parse_level_name, get_level_name
+from bps.logs.handlers import WatchedFileHandler, purge_handlers
+from bps.logs import proxy_logger
+from bps.error import types as errors
+#lib
+from bps.tests.utils import ak, get_tmp_path as get_tmp_file, TestCase, capture_logger
+#module
+
+LS = os.linesep
+
+#=========================================================
+#utilities
+#=========================================================
+class HelperTest(TestCase):
+
+ def test_get_logger(self):
+ gl = logging.getLogger
+
+ #test root
+ root = gl()
+ self.assertIs(get_logger(), root)
+ self.assertIs(get_logger(None), root)
+ self.assertIs(get_logger(""), root)
+ self.assertIs(get_logger("<root>"), root)
+
+ #test this mod
+ self.assertIs(get_logger("bps"), gl("bps"))
+
+ #test logger resolution
+ l = gl("xxx")
+ self.assertIs(get_logger(l), l)
+
+ def test_parse_level_name(self):
+ #test a few of the levels
+ self.check_function_results(parse_level_name, [
+ ak(0, "NOTSET"),
+ ak(0, "notset"),
+ ak(0, "0"),
+ ak(0, 0),
+
+ ak(30, "WARNING"),
+ ak(30, "warning"),
+ ak(30, "Warn"),
+ ak(30, "30"),
+ ak(30, 30),
+
+ ak(99, "99"),
+ ak(99, 99),
+ ])
+
+ self.assertRaises(ValueError, parse_level_name, "NotALevel")
+
+ def test_get_level_name(self):
+ self.check_function_results(get_level_name, [
+ ak("NOTSET", "NOTSET"),
+ ak("NOTSET", "notset"),
+ ak("NOTSET", "0"),
+ ak("NOTSET", 0),
+
+ ak("WARNING", "WARNING"),
+ ak("WARNING", "warning"),
+ ak("WARNING", "Warn"),
+ ak("WARNING", "30"),
+ ak("WARNING", 30),
+
+ ak("99", "99"),
+ ak("99", 99),
+ ])
+
+ self.assertRaises(ValueError, get_level_name, "NotALevel")
+
+#=========================================================
+#handler tests (startup_msg etc)
+#=========================================================
+
+#---------------------------------------------------
+#watched file handler
+#---------------------------------------------------
+class WatchedFileHandlerTest(TestCase):
+ "test WatchFileHandler"
+ def setUp(self):
+ #get logger, ensure it's free of handlers, and that it will log debug msgs
+ self.log = get_logger(__name__ + ".LogsTest.test_file_handler")
+ purge_handlers(self.log)
+ self.log.setLevel(1)
+ #get a tmp file path to work with
+ self.path = get_tmp_file()
+
+ def tearDown(self):
+ purge_handlers(self.log, close=True)
+
+ def test_logging(self):
+ #NOTE: only because we're reading a file create in 'w' mode
+ # do we have to care about os.linesep (aka global var LS).
+ # the rest of the logging system uses \n.
+
+ #make sure file is created after handler
+ h = lh.WatchedFileHandler(self.path)
+
+ self.assertTrue(self.path.exists, "log path missing")
+ self.assertEquals(self.path.get(), "", "log path not empty")
+
+ self.log.addHandler(h)
+
+ #make sure lines are flushed immediately
+ self.log.debug("AAA")
+ self.assertEqual(self.path.get(), "AAA" + LS)
+
+ self.log.debug("BBB\n")
+ self.assertEqual(self.path.get(), "AAA" + LS + "BBB" + LS + LS)
+
+ #try truncating file
+ s = h.stream
+ self.path.set("")
+ self.log.debug("CCC\n")
+ self.assertNotEqual(h.stream, s, "handler didn't reopen stream")
+ self.assertEqual(self.path.get(), "CCC" + LS + LS)
+
+ #try deleting file
+ if os.name == "nt":
+ #under windows, handler's lock prevents removal
+ self.assertRaises(errors.PathInUseError, self.path.remove)
+ h.stream.close()
+ self.path.remove()
+ s = h.stream
+ self.log.debug("QQQ\n")
+ self.assertNotEqual(h.stream, s, "handler didn't reopen stream")
+ self.assertEqual(self.path.get(), "QQQ" + LS + LS)
+
+ #try moving file
+ p2 = get_tmp_file()
+ assert p2.ismissing
+ if os.name == "nt":
+ #under windows, handler's lock prevents moving it
+ self.assertRaises(errors.PathInUseError, self.path.move_to, p2)
+ h.stream.close()
+ assert p2.ismissing #todo: perm glitch in move_to's try/except of os.rename allowing p2 to exist after failed move
+ self.path.move_to(p2)
+ self.assertTrue(self.path.ismissing, "path not moved")
+ self.assertEqual(p2.get(), "QQQ" + LS + LS, "move mismatch")
+
+ #check for reopen
+ s = h.stream
+ self.log.debug("SSS")
+ self.assertNotEqual(h.stream, s, "handler didn't reopen stream")
+ self.assertEqual(p2.get(), "QQQ" + LS + LS, "old path touched")
+ self.assertEqual(self.path.get(), "SSS" + LS, "new path not written")
+
+## def test_single_shared(self):
+## h = lh.WatchFileHandler(self.path)
+## self.log.addHandler(h)
+##
+## def test_single_solo(self):
+## h = lh.WatchFileHandler(self.path, shared=False)
+## self.log.addHandler(h)
+
+## def test_double_shared(self):
+## h1 = lh.WatchFileHandler(self.path)
+## self.log.addHandler(h1)
+##
+## h2 = lh.WatchFileHandler(self.path)
+## self.log.addHandler(h2)
+##
+## def test_double_solo(self):
+## h1 = lh.WatchFileHandler(self.path, shared=False)
+## self.log.addHandler(h1)
+##
+## h2 = lh.WatchFileHandler(self.path, shared=False)
+## self.log.addHandler(h2)
+
+#=========================================================
+#formatter tests
+#=========================================================
+
+#=========================================================
+#proxy tests
+#=========================================================
+mod_log = get_logger(__name__)
+log = alog = proxy_logger.log
+mlog = proxy_logger.multilog
+
+class ProxyLoggerTest(TestCase):
+ _prefix = "bps.logs.proxy_logger"
+
+ def setUp(self):
+ global log
+ log = proxy_logger.log
+
+ def test_00_vars(self):
+ "verify initial state is correct"
+
+ #test globals
+ g = globals()
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], proxy_logger.log)
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ #test base logger
+ with capture_logger(__name__) as logbuf:
+ mod_log.warning("this is a test")
+ self.assertEqual(logbuf.getvalue(), "bps.tests.test_logs: WARNING: this is a test\n")
+
+ #test nothing changed
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], proxy_logger.log)
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ def test_01_alog(self):
+ "test accessing log under alias"
+
+ #test globals
+ g = globals()
+ g['log'] = None #just to check w/o target to replace
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], None)
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ #test base logger
+ with capture_logger(__name__) as logbuf:
+ alog.warning("this is a test")
+ self.assertEqual(logbuf.getvalue(), "bps.tests.test_logs: WARNING: this is a test\n")
+
+ #test nothing changed
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], None) #should have still replaced itself
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ #put log back
+ g['log'] = proxy_logger.log
+
+ #test base logger
+ with capture_logger(__name__) as logbuf:
+ alog.warning("this is a test")
+ self.assertEqual(logbuf.getvalue(), "bps.tests.test_logs: WARNING: this is a test\n")
+
+ #test log replaced itself
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], get_logger(__name__)) #should have still replaced itself
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ def test_02_alog(self):
+ "test accessing log with replacment behavior"
+
+ #test globals
+ g = globals()
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], proxy_logger.log)
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ #test base logger
+ with capture_logger(__name__) as logbuf:
+ log.warning("this is a test")
+ self.assertEqual(logbuf.getvalue(), "bps.tests.test_logs: WARNING: this is a test\n")
+
+ #test 'log' replaced itself
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], get_logger(__name__)) #should have replaced itself
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ def test_03_mlog(self):
+ "test accessing multilog"
+
+ #test globals
+ g = globals()
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], proxy_logger.log)
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+ #test base logger
+ with capture_logger(__name__) as logbuf:
+ mlog.warning("this is a test")
+ self.assertEqual(logbuf.getvalue(), "bps.tests.test_logs: WARNING: this is a test\n")
+
+ #test nothing changed
+ self.assertIs(g['mod_log'], get_logger(__name__))
+ self.assertIs(g['log'], proxy_logger.log) #should have replaced itself
+ self.assertIs(g['alog'], proxy_logger.log)
+ self.assertIs(g['mlog'], proxy_logger.multilog)
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_logs_apply_config.py b/bps/tests/test_logs_apply_config.py
new file mode 100644
index 0000000..5619a91
--- /dev/null
+++ b/bps/tests/test_logs_apply_config.py
@@ -0,0 +1,190 @@
+"""
+bps.logs.config unittest script -- (c) Assurance Technologies 2003-2006
+defines unit tests for the execution half of bps's logging config handling
+"""
+
+#=========================================================
+#imports
+#=========================================================
+#core
+import logging
+import warnings
+import sys
+import time
+from cStringIO import StringIO
+#pkg
+from bps.error import types as errors
+from bps.logs import config_logging
+from bps.logs.loggers import get_logger
+from bps.logs.config import LoggingConfig
+from bps.logs.handlers import purge_handlers
+from bps.meta import Params as ak
+#lib
+from bps.tests.utils import TestCase, get_tmp_path
+#local
+
+#=========================================================
+#
+#=========================================================
+
+#=========================================================
+#
+#=========================================================
+class ConfigTest(TestCase):
+
+ def tearDown(self):
+ #make sure to release any captures that were set
+ config_logging(capture_stderr=False, capture_stdout=False, capture_warnings=False)
+
+ def test_missing_file(self):
+ "test config_logging() handles missing path"
+ log_path = get_tmp_path()
+ self.assert_(config_logging(log_path) is False)
+ self.assertRaises(errors.MissingPathError, config_logging, log_path, errors="raise")
+
+ def test_placeholder(self):
+ "test reset_loggers doesn't choke on placeholders"
+ #NOTE: this was an observed bug...
+ # we reset once, add a logger which ensures a placeholder ('xxx') is created,
+ # and then make sure reset_loggers doesn't choke on the placeholder.
+ log_path = get_tmp_path()
+ config_logging(
+ reset_loggers=True,
+ levels="xxx.yyy=DEBUG",
+ )
+ config_logging(
+ reset_loggers=True,
+ )
+
+ def test_sample1(self):
+ #configure logging system
+ log_path = get_tmp_path()
+ config_logging(
+ level="WARNING",
+ levels="bps.tests.test_logs_fake=DEBUG; bps.tests.test_logs=INFO",
+ default_handler=dict(
+ klass="FileHandler",
+ args=(log_path, ),
+ formatter="std-file",
+ startup_msg=True,
+ ),
+ capture_stderr=True,
+ )
+
+## h = logging.StreamHandler(self.log_buffer)
+## h.formatter = logging.Formatter("[%(name)s %(levelname)s] %(message)s")
+
+ #log some messages
+ cur = time.strftime("%Y-%m-%d %H:%M:%S")
+ get_logger().warning("test message")
+ get_logger("myapp").info("can't see me")
+ get_logger("myapp").warning("can see me")
+ get_logger("bps.tests.test_logs").debug("shouldn't display")
+ get_logger("bps.tests.test_logs").info("should display")
+ sys.stderr.write("hello stderr!\n")
+ sys.stderr.flush()
+
+ #detach the handler
+ root = get_logger()
+ for h in root.handlers[:]:
+ if getattr(h, "baseFilename", None) == log_path:
+ root.removeHandler(h)
+ h.flush()
+ h.close()
+
+ #now check what was written
+ self.assertEqual(log_path.get(), """\
+[%(cur)s INF ] --- LOGGING STARTED %(cur)s ---
+[%(cur)s WRN root] test message
+[%(cur)s WRN myapp] can see me
+[%(cur)s INF bps.tests.test_logs] should display
+[%(cur)s RAW sys.stderr] unmanaged logging output:
+ hello stderr!
+ \n \n\n""" % dict(cur=cur))
+
+ def test_sample2(self):
+ name = __name__ + ".test_logger"
+ log = get_logger(name)
+ log.setLevel(99)
+ buffer = StringIO()
+ #NOTE: this makes sure outputs:handlers works
+ config_logging(
+ levels={name:"WARNING"},
+ outputs={name: dict(handlers=['custom'], propagate=False)},
+ handlers=dict(custom=dict(klass='StreamHandler', args=(buffer,), formatter='custom')),
+ formatters=dict(custom=dict(format="%(name)s: %(levelname)s: %(message)s")),
+ )
+ log.warning("test")
+ self.assertEqual(buffer.getvalue(), name + ": WARNING: test\n")
+
+ def test_sample3(self):
+ name = __name__ + ".test_logger"
+ log = get_logger(name)
+ log.setLevel(99)
+ buffer = StringIO()
+ #NOTE: this makes sure outputs:handlers works
+ config_logging(
+ loggers={name: dict(level="WARNING", outputs=['custom'], propagate=False)},
+ handlers=dict(custom=dict(klass='StreamHandler', args=(buffer,), formatter='custom')),
+ formatters=dict(custom=dict(format="%(name)s: %(levelname)s: %(message)s")),
+ )
+ log.warning("test")
+ self.assertEqual(buffer.getvalue(), name + ": WARNING: test\n")
+
+#=========================================================
+#eof
+#=========================================================
+
+"""
+
+config logging use cases found in the wild...
+=============================================
+
+medicred
+--------
+logs.config_logging(path)
+ medicred.cfg
+ debug.cfg
+
+logging.cfg files found in the wild...
+======================================
+[logging:levels]
+##<root> = DEBUG
+<root> = WARNING
+##thumbs = DEBUG
+##thumbs.common = DEBUG
+thumbs.zoom = DEBUG
+
+---------------
+[logging:options]
+capture_warnings = True
+warning_fmt = %(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s
+
+[logging:levels]
+<root> = WARNING
+------------
+[medicred:debug]
+site=cgmcn
+
+[logging:levels]
+<root> = WARNING
+imports = DEBUG
+bps3.base = DEBUG
+##sqlalchemy.engine = INFO
+##gwrap.windows.stack = DEBUG
+
+##automigrate = DEBUG
+medicred.migration = DEBUG
+##uif.list_control = DEBUG
+##gwrap.simple_dialogs.select_dialogs = DEBUG
+uif.mailclient = DEBUG
+
+gwrap.misc.simple_list_model = DEBUG
+
+medicred.client.report_dialog = DEBUG
+reporting = DEBUG
+
+medicred.build_client = INFO
+medicred.build_backend = INFO
+
+"""
diff --git a/bps/tests/test_logs_capture.py b/bps/tests/test_logs_capture.py
new file mode 100644
index 0000000..9dbe412
--- /dev/null
+++ b/bps/tests/test_logs_capture.py
@@ -0,0 +1,306 @@
+"""
+bps.logs.capture unittest script -- (c) Assurance Technologies 2003-2006
+defines unit tests for bps's stdio redirection package
+"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os
+import sys
+from logging import getLogger
+import logging
+from cStringIO import StringIO
+from warnings import warn
+import warnings
+#site
+#pkg
+from bps.fs import filepath
+from bps.logs import config as lc, handlers as lh, capture as cp, config_logging, add_handler
+from bps.logs.handlers import WatchedFileHandler, purge_handlers
+from bps.error import types as errors
+#lib
+from bps.tests.utils import get_tmp_path as get_tmp_file, TestCase
+#module
+log = getLogger(__name__)
+
+#=========================================================
+#capture tests
+#=========================================================
+class _StdCaptureTest(TestCase):
+ name = None
+
+ def setUp(self):
+ #make sure capturing was never on
+ orig_stream, cp_proxy, cp_orig = self.get3()
+ if cp_orig:
+ raise RuntimeError, "stream capturing has been enabled by test harness"
+ if cp_proxy:
+ #code doesn't want this cleared normally, but we do
+ setattr(cp, "_proxy_" + self.name, None)
+
+ #setup the logger & a buffer for it
+ self.log = getLogger("sys." + self.name)
+ self.log.propagate = 0
+ purge_handlers(self.log)
+ self.log.setLevel(1)
+ self.log_buffer = StringIO()
+ h = logging.StreamHandler(self.log_buffer)
+ h.formatter = logging.Formatter("[%(name)s %(levelname)s] %(message)s")
+ self.raw_prefix = "[sys.%s RAW] " % self.name
+ self.debug_prefix = "[sys.%s DEBUG] " % self.name
+ self.log.addHandler(h)
+
+ #intercept sys stream
+ self.orig_stream = self.get()
+ self.buffer = StringIO()
+ self.set(self.buffer)
+
+ def tearDown(self):
+ purge_handlers(self.log)
+ self.set(self.orig_stream)
+
+ def get(self):
+ return getattr(sys, self.name)
+
+ def get3(self):
+ return self.get(), getattr(cp, "_proxy_" + self.name), getattr(cp, "_orig_" + self.name)
+
+ def set(self, value):
+ setattr(sys, self.name, value)
+
+ def test_logger(self):
+ "test that basic logger setup works"
+ self.check_empty()
+ self.log.debug("TESTING")
+ self.check_and_empty("", self.debug_prefix + "TESTING\n")
+
+ def test_capture_release(self):
+ "test capture/release cycle with some writing"
+ #test capture & write
+ self.capture(True)
+ self.wt()
+
+ #test release & write
+ self.release()
+ self.wt2()
+
+ #test re-capturing & write
+ self.capture(False)
+ self.wt()
+
+ #release
+ self.release()
+
+ def capture(self, first):
+ "enable capturing"
+ #check it's not being captured
+ self.assert_(not getattr(cp, "check_" + self.name)())
+
+ #verify buffers
+ c, p, o = self.get3()
+ self.assertEqual(c, self.buffer)
+ if first:
+ self.assertEqual(p, None)
+ else:
+ self.assertTrue(isinstance(p, cp.StreamWrapper))
+ self.assertEqual(p.name, "sys." + self.name)
+ self.assertEqual(o, None)
+
+ #enable capturing
+ config_logging(**{"capture_" + self.name: True})
+
+ #check it's being captured
+ self.assert_(getattr(cp, "check_" + self.name)())
+
+ #recheck streams
+ c, p, o = self.get3()
+ self.assertEqual(c, p)
+ self.assertTrue(isinstance(p, cp.StreamWrapper))
+ self.assertEqual(o, self.buffer)
+
+ def release(self):
+ "release capturing"
+ #check it's being captured
+ self.assert_(getattr(cp, "check_" + self.name)())
+
+ #check streams
+ c, p, o = self.get3()
+ self.assertEqual(c, p)
+ self.assertTrue(isinstance(p, cp.StreamWrapper))
+ self.assertEqual(o, self.buffer)
+
+ #release streams
+ config_logging(**{"capture_" + self.name: False})
+
+ #check release
+ self.assert_(not getattr(cp, "check_" + self.name)())
+
+ #check buffers
+ c, p, o = self.get3()
+ self.assertEqual(c, self.buffer)
+ self.assertTrue(isinstance(p, cp.StreamWrapper))
+ self.assertEqual(o, None)
+
+ def wt(self):
+ "test that writes are being captured"
+ buf = self.get() #stdout, using proxy
+ self.check_empty()
+
+ #try a flushed write...
+ buf.write("ABCDEF\n")
+ cp.flush_buffers()
+ self.check_and_empty("", self.raw_prefix + "unmanaged logging output:\nABCDEF\n\n\n")
+
+ #try a flush forced by logging
+ buf.write("QRSTVUVE\n")
+ self.log.debug("XXX")
+ self.check_and_empty("", self.raw_prefix +
+ "unmanaged logging output:\nQRSTVUVE\n\n\n" + self.debug_prefix + "XXX\n")
+
+ def wt2(self):
+ "test that we're writing to buffer, not being captured"
+ self.check_empty()
+ self.get().write("ABC\n")
+ self.check_and_empty("ABC\n", "")
+
+ def check_and_empty(self, buffer, log_buffer):
+ self.assertEqual(self.buffer.getvalue(), buffer)
+ if buffer:
+ self.buffer.reset(); self.buffer.truncate()
+
+ self.assertEqual(self.log_buffer.getvalue(), log_buffer)
+ if log_buffer:
+ self.log_buffer.reset(); self.log_buffer.truncate()
+
+ self.check_empty()
+
+ def check_empty(self):
+ self.assertEqual(self.buffer.getvalue(), "")
+ self.assertEqual(self.log_buffer.getvalue(), "")
+
+class StdOutCaptureTest(_StdCaptureTest):
+ _prefix = "capture stdout"
+ name = "stdout"
+
+class StdErrCaptureTest(_StdCaptureTest):
+ _prefix = "capture stderr"
+ name = "stderr"
+
+class WarningCaptureTest(TestCase):
+ _prefix = "capture warnings"
+
+ def setUp(self):
+ if cp._orig_showwarning:
+ raise RuntimeError, "capture warnings enabled"
+ self.orig_stderr = sys.stderr
+ self.orig_format = warnings.formatwarning
+ def fmt(message, category, filename, lineno, line=None):
+ filename = filepath(filename)
+ return "[%s %s] %s" % (filename.root, category.__name__, message)
+ warnings.formatwarning = fmt
+
+ sys.stderr = self.err_buffer = StringIO()
+
+ #setup the logger & a buffer for it
+ self.log_buffer = StringIO()
+ self.log = getLogger("sys.warnings")
+ self.log.setLevel(1)
+ add_handler(self.log.name,
+ klass='StreamHandler',
+ args=(self.log_buffer,),
+ formatter=dict(fmt="[%(name)s %(levelname)s] %(message)s"),
+ propagate=False, add=False,
+ )
+## self.log.propagate = 0
+## purge_handlers(self.log)
+## h = logging.StreamHandler(self.log_buffer)
+## h.formatter = logging.Formatter("[%(name)s %(levelname)s] %(message)s")
+## self.log.addHandler(h)
+
+ self.warning_path = filepath(__file__).abspath
+
+ def tearDown(self):
+ sys.stderr = self.orig_stderr
+ warnings.formatwarning = self.orig_format
+ cp.release_warnings()
+ purge_handlers(self.log)
+
+ def test_logger(self):
+ "test basic logger behavior"
+ self.check_empty()
+ self.log.debug("TESTING")
+ self.check_and_empty("", "[sys.warnings DEBUG] TESTING\n")
+
+ def test_capture_release(self):
+ modname = __name__.rsplit(".", 1)[1]
+ wp = "[" + modname + " UserWarning] "
+ lp = "[sys.warnings WARNING] UserWarning:\n\tmessage: "
+
+ #check before capture
+ self.check_empty()
+ warn("XXX YYY")
+ self.check_and_empty(wp + "XXX YYY", "")
+
+ #check w/ capture
+ self.capture()
+ warn("ABDDEF")
+ self.check_and_empty("", lp + "ABDDEF\n")
+
+ #check after release
+ self.release()
+ warn("QRSIUT")
+ self.check_and_empty(wp + "QRSIUT", "")
+
+ #check re-capture
+ self.capture()
+ warn("ASIDUAASDADS")
+ self.check_and_empty("",lp + "ASIDUAASDADS\n")
+
+ #check re-release
+ self.release()
+ warn("XXXXXXX")
+ self.check_and_empty(wp + "XXXXXXX", "")
+
+ def capture(self):
+ self.assert_(not cp.check_warnings())
+ self.check_empty()
+ self.assertEqual(cp._orig_showwarning, None)
+ config_logging(
+ capture_warnings=True,
+ warning_target="sys.warnings", #override normal redirection so we see it
+ warning_fmt = "%(category)s:\n\tmessage: %(message)s" #override normal format so we can test for it
+ )
+ self.assert_(cp.check_warnings())
+ self.assertNotEqual(cp._orig_showwarning, None)
+ self.check_empty()
+
+ def release(self):
+ self.assert_(cp.check_warnings())
+ self.check_empty()
+ self.assertNotEqual(cp._orig_showwarning, None)
+ config_logging(
+ capture_warnings=False,
+ )
+ self.assertEqual(cp._orig_showwarning, None)
+ self.check_empty()
+ self.assert_(not cp.check_warnings())
+
+ def check_and_empty(self, err_buffer, buffer):
+ self.assertEqual(self.log_buffer.getvalue(), buffer, "capture buffer:")
+ if buffer:
+ self.log_buffer.reset(); self.log_buffer.truncate()
+
+ self.assertEqual(self.err_buffer.getvalue(), err_buffer, "stderr buffer:")
+ if err_buffer:
+ self.err_buffer.reset(); self.err_buffer.truncate()
+ self.check_empty()
+
+ def check_empty(self):
+ self.assertEqual(self.log_buffer.getvalue(), "", "capture buffer:")
+ self.assertEqual(self.err_buffer.getvalue(), "", "stderr buffer:")
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_logs_parse_config.py b/bps/tests/test_logs_parse_config.py
new file mode 100644
index 0000000..e6e4725
--- /dev/null
+++ b/bps/tests/test_logs_parse_config.py
@@ -0,0 +1,537 @@
+"""
+bps.logs.config unittest script -- (c) Assurance Technologies 2003-2006
+defines unit tests for the parsing half of bps's logging config handling
+"""
+from __future__ import with_statement
+#=========================================================
+#imports
+#=========================================================
+import logging
+import warnings
+import sys
+from bps.fs import filepath
+from bps.logs import config
+from bps.meta import Params
+ak = Params
+from bps.logs.config import LoggingConfig
+from bps.tests.utils import TestCase, catch_warnings, capture_logger
+from bps.error.types import MissingPathError, InputError
+
+#=========================================================
+#
+#=========================================================
+class HelperTest(TestCase):
+
+ def test_parse_output_value(self):
+ self.check_function_results(config.parse_output_value, [
+ ak(dict(outputs=[]), ""),
+ ak(dict(outputs=[]), ",|"),
+ ak(dict(outputs=['a', 'b']), "a,b"),
+ ak(dict(outputs=['a', 'b'], add=True), "a,b|add=True"),
+ ak(dict(outputs=['a', 'b'], propagate=True), "a,b|propagate=True"),
+ ak(dict(outputs=['a', 'b'], propagate=False), "a,b|propagate=False"),
+ ])
+
+ def test_parse_dict_string(self):
+ self.check_function_results(config.parse_dict_string, [
+ ak(dict(a="1", b="2"), "a=1;b=2", ";"),
+ ak(dict(a="1", d="2"), "a=1 #blah\nd=2\n\n\n#blah","\n", strip_comments=True),
+ ak(dict(a="1", b="2"), "a=1,b=2", ","),
+ ak(dict(a="1", b="2 #comment"), " a=1 , b = 2 #comment", ","),
+ ak(dict(a="1", b="2; 3=4"), "a= 1,b = 2; 3=4", ","),
+ ])
+ self.assertRaises(ValueError, config.parse_dict_string, "a=1 #blah\nd=2\n\n\n#blah","\n")
+ #ValueError: unexpected element in string
+ # caused by "#blah" element
+
+ def test_splitcomma(self):
+ self.check_function_results(config.splitcomma, [
+ ak(['a', 'b'], "a,b"),
+ ak(['a', 'b'], "a, b"),
+ ak(['a', 'b'], " a, b"),
+ ak(['a', 'b'], "a,, b ,,, , , , "),
+ ak(['a', 'b'], "a,, \n b ,,, , , , "),
+ ak(['a', 'b', ';'], "a,, \n b ,,, ; , , , "),
+ ])
+
+#=========================================================
+#parsing tests
+#=========================================================
+class ParseConfigTest(TestCase):
+
+ #=========================================================
+ #test failures
+ #=========================================================
+ def test_missing_file(self):
+ "test parse_config()'s missing file behavior"
+
+ #test file-not-found w/ errors='log'
+ path = self.sample1_path + "_file_does_not_exist.ini"
+ with capture_logger("bps.logs.config") as logbuf:
+ result = config.parse_config(path)
+ self.assertIs(result, None)
+ self.assertEqual(logbuf.getvalue(), """\
+bps.logs.config: ERROR: config file not found: filename=%r
+""" % path)
+
+ #test file-not-found w/ errors='raise'
+ self.assertRaises(MissingPathError, config.parse_config, path, errors="raise")
+ #error: no such file or directory
+
+ def test_empty_data(self):
+
+ with capture_logger("bps.logs.config") as logbuf:
+ result = config.parse_config("\n")
+ self.assertIs(result, None)
+ self.assertEqual(logbuf.getvalue(), """\
+bps.logs.config: WARNING: couldn't determine logging config format: stype='raw'
+""")
+
+ self.assertRaises(InputError, config.parse_config, "", errors="raise")
+
+ #=========================================================
+ #samples
+ #=========================================================
+ sample1 = r"""[logging:options]
+capture_warnings = True
+warning_fmt = %(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s
+reset_loggers = True
+not_an_option = ignored options should be ignored
+
+[logging:levels]
+<root> = WARNING
+"""
+ sample1_path = filepath(__file__, "..", "_logs_parse_config_sample1.ini").abspath
+
+ def test_sample1(self, data=None):
+ """test small compact-ini sample"""
+ if data is None:
+ data = self.sample1
+
+ #check it parses correctly (and emits warning about not_an_option)
+ with catch_warnings(record=True) as log:
+ warnings.filterwarnings("always")
+ c = config.parse_config(data)
+ self.assertEquals(len(log), 1)
+ self.assertWarningEquals(log[0],
+ message="unknown logging:options key encountered: 'not_an_option'",
+ filename=__file__,
+ )
+
+ self.assertConfigEquals(c, dict(
+ loggers={"":dict(level=30)},
+ options=dict(
+ capture_warnings=True,
+ reset_loggers=True,
+ warning_fmt='%(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s'
+ ),
+ ))
+
+ #examine w/ readers
+ self.assert_(c.get_option("capture_warnings"))
+ self.assert_(c.get_option("reset_loggers"))
+ self.assert_(c.get_option("reset_handlers"))
+
+ #change it
+ c.set_level('x', "DEBUG")
+ c.set_level('y', "NotSET")
+ del c.options['reset_loggers']
+
+ #try reparsing
+ c2 = config.parse_config(c)
+
+ #should be diff objects
+ assert c2 is not c
+ assert c2.loggers is not c.loggers
+
+ #but values should have parsed properly
+ self.assertConfigEquals(c2, dict(
+ loggers={"":dict(level=30), "x":dict(level=10), "y":dict(level=0)},
+ options=dict(
+ capture_warnings=True,
+ warning_fmt='%(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s'
+ ),
+ ))
+
+ #examine w/ readers
+ self.assert_(c.get_option("capture_warnings"))
+ self.assert_(not c.get_option("reset_loggers"))
+ self.assert_(not c.get_option("reset_handlers"))
+
+ def test_sample1a(self):
+ self.test_sample1(self.sample1_path)
+
+ #------------------------------------------------
+ #
+ #------------------------------------------------
+ def test_sample2(self):
+ "test large compact-ini sample"
+ data = r"""
+
+[logging:options]
+capture_stdout = false
+capture_warnings = true
+warning_fmt = %(category)s: %(message)s
+
+[logging:levels]
+<root> = INFO
+myapp = DEBUG
+pylons = WARNING
+
+[logging:output]
+<root> = console | add=True
+
+[logging:outputs]
+myapp = syslog | propagate=False
+mylib = syslog
+
+[logging:handler:console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+startup_msg = True
+
+[logging:handler:syslog]
+class=handlers.SysLogHandler
+level=ERROR
+formatter=generic
+args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
+
+[logging:handler:syslog2]
+class=handlers.SysLogHandler
+level=ERROR
+formatter=generic
+args=(('localhost', handlers.SYSLOG_UDP_PORT), level=handlers.SysLogHandler.LOG_USER)
+
+[logging:formatter:generic]
+format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S #simple date format
+
+"""
+ #check it parses correctly
+ with catch_warnings(record=True) as log:
+ warnings.filterwarnings("always")
+ c = config.parse_config(data)
+ self.assertEquals(len(log), 1)
+ self.assertWarningEquals(log[0],
+ message=r"'logging:output' is deprecated, use 'logging:outputs' instead",
+ filename=__file__,
+ )
+
+ self.assertConfigEquals(c, dict(
+ loggers={
+ "": dict(level=20,
+ outputs=['console'],
+ add=True,
+ propagate=True,
+ ),
+ "myapp": dict(
+ level=10,
+ outputs=['syslog'],
+ propagate=False,
+ ),
+ 'pylons': dict(level=30),
+ 'mylib': dict(
+ outputs=['syslog'],
+ propagate=True,
+ ),
+ },
+ formatters={
+ "generic": dict(
+ format="%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s",
+ datefmt="%H:%M:%S #simple date format",
+ ),
+ },
+ handlers={
+ "console": dict(
+ klass=logging.StreamHandler,
+ args=Params(sys.stderr),
+ level="NOTSET",
+ formatter="generic",
+ startup_msg=True,
+ ),
+ "syslog": dict(
+ klass=logging.handlers.SysLogHandler,
+ level="ERROR",
+ formatter="generic",
+ args=Params(('localhost', logging.handlers.SYSLOG_UDP_PORT), logging.handlers.SysLogHandler.LOG_USER),
+ ),
+ "syslog2": dict(
+ klass=logging.handlers.SysLogHandler,
+ level="ERROR",
+ formatter="generic",
+ args=Params(('localhost', logging.handlers.SYSLOG_UDP_PORT),
+ level=logging.handlers.SysLogHandler.LOG_USER
+ ),
+ ),
+ },
+ options=dict(
+ capture_warnings=True,
+ capture_stdout=False,
+ warning_fmt='%(category)s: %(message)s',
+ ),
+ ))
+
+ #------------------------------------------------
+ #
+ #------------------------------------------------
+ def test_sample3(self):
+ "test large stdlib-ini sample"
+ data = r"""
+
+[loggers]
+keys=root,my_app,mylib,pylons
+
+[handlers]
+keys=console,syslog
+
+[formatters]
+keys=generic
+
+[logger_root]
+level = INFO
+handlers = console
+
+[logger_my_app]
+level = DEBUG
+qualname=myapp
+handlers = syslog
+propagate = 0
+
+[logger_mylib]
+handlers = syslog
+qualname = mylib
+
+[logger_pylons]
+level = WARNING
+qualname = pylons
+
+[handler_console]
+class = StreamHandler
+args = (sys.stderr,)
+level = NOTSET
+formatter = generic
+startup_msg = True
+
+[handler_syslog]
+class=handlers.SysLogHandler
+level=ERROR
+formatter=generic
+args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
+
+[formatter_generic]
+format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
+datefmt = %H:%M:%S #simple date format
+
+"""
+ #check it parses correctly
+ c = config.parse_config(data)
+ self.assertConfigEquals(c, dict(
+ loggers={
+ "": dict(level=20,
+ outputs=['console'],
+ ),
+ "myapp": dict(
+ level=10,
+ outputs=['syslog'],
+ propagate=False,
+ ),
+ 'pylons': dict(level=30, outputs=[], propagate=True),
+ 'mylib': dict(
+ outputs=['syslog'],
+ propagate=True,
+ ),
+ },
+ formatters={
+ "generic": dict(
+ format="%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s",
+ datefmt="%H:%M:%S #simple date format",
+ ),
+ },
+ handlers={
+ "console": dict(
+ klass=logging.StreamHandler,
+ args=Params(sys.stderr),
+ level="NOTSET",
+ formatter="generic",
+ ),
+ "syslog": dict(
+ klass=logging.handlers.SysLogHandler,
+ level="ERROR",
+ formatter="generic",
+ args=Params(('localhost', logging.handlers.SYSLOG_UDP_PORT), logging.handlers.SysLogHandler.LOG_USER),
+ ),
+ },
+ options=dict(disable_existing_loggers=True),
+ ))
+
+ #------------------------------------------------
+ #
+ #------------------------------------------------
+ def test_sample4(self):
+ data = dict(
+ levels="<root>=WARNING; myapp=DEBUG",
+ capture_warnings=True,
+ warning_fmt='%(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s',
+ default_handler="console",
+ )
+
+ #check it parses correctly
+ c = config.parse_config(**data)
+ self.assertConfigEquals(c, dict(
+ loggers={"":dict(level=30, outputs=['console']), "myapp": dict(level=10)},
+ options=dict(
+ capture_warnings=True,
+ warning_fmt='%(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s',
+ ),
+ ))
+
+ #------------------------------------------------
+ #
+ #------------------------------------------------
+ def test_sample5(self):
+ data = dict(
+ levels="<root>=WARNING #my comment \n #another comment \n myapp=DEBUG",
+ capture_warnings=True,
+ warning_fmt='%(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s',
+ default_handler=dict(klass=logging.StreamHandler),
+ handlers=dict(
+ console=dict(
+ klass='StreamHandler',
+ args='sys.stderr,',
+ level="NOTSET",
+ formatter="generic",
+ startup_msg=True,
+ ),
+## console="""
+##class = StreamHandler
+##args = (sys.stderr,)
+##level = NOTSET
+##formatter = generic
+##startup_msg = True
+##""",
+ syslog=dict(
+ klass="handlers.SysLogHandler",
+ level="ERROR",
+ formatter="generic",
+ args=(('localhost', logging.handlers.SYSLOG_UDP_PORT), logging.handlers.SysLogHandler.LOG_USER),
+ ),
+ ),
+ formatters=dict(
+ generic=dict(
+ format="%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s",
+ datefmt="%H:%M:%S",
+ ),
+## generic="""
+##format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s
+##datefmt = %H:%M:%S
+##""",
+ alt=dict(
+ fmt = "%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s",
+ datefmt = "%H:%M:%S",
+ )
+ )
+ )
+
+ #check it parses correctly
+ c = config.parse_config(**data)
+ self.assertConfigEquals(c, dict(
+ loggers={
+ "":dict(level=30, outputs=[LoggingConfig.DEFAULT_HANDLER_NAME]),
+ "myapp":dict(level=10),
+ },
+ options=dict(
+ capture_warnings=True,
+ warning_fmt='%(category)s:\n\t message: %(message)s\n\tfilename: %(filename)s\n\t lineno: %(lineno)s',
+ ),
+ handlers={
+ LoggingConfig.DEFAULT_HANDLER_NAME: {"klass": logging.StreamHandler},
+ "console": dict(
+ klass=logging.StreamHandler,
+ args=Params(sys.stderr,),
+ level="NOTSET",
+ formatter="generic",
+ startup_msg=True,
+ ),
+ "syslog": dict(
+ klass=logging.handlers.SysLogHandler,
+ level="ERROR",
+ formatter="generic",
+ args=Params(('localhost', logging.handlers.SYSLOG_UDP_PORT), logging.handlers.SysLogHandler.LOG_USER),
+ ),
+ },
+ formatters={
+ "generic": dict(
+ format="%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s",
+ datefmt="%H:%M:%S",
+ ),
+ "alt": dict(
+ fmt="%(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s",
+ datefmt="%H:%M:%S",
+ ),
+ },
+ ))
+
+ #------------------------------------------------
+ #
+ #------------------------------------------------
+ def test_sample6(self):
+ name = __name__ + ".test_logger"
+ buffer = sys.stderr
+ c = config.parse_config(
+ levels={name:"WARNING"},
+ outputs={name: dict(handlers=['custom'], propagate=False)},
+ handlers=dict(custom=dict(klass='StreamHandler', args=(buffer,), formatter='custom')),
+ formatters=dict(custom=dict(format="%(name)s: %(levelname)s: %(message)s")),
+ )
+
+ self.assertConfigEquals(c, dict(
+ loggers={
+ name: dict(
+ level=30,
+ outputs=['custom'],
+ propagate=False,
+ )
+ },
+ handlers=dict(
+ custom=dict(
+ klass=logging.StreamHandler,
+ args=Params(buffer),
+ formatter='custom',
+ ),
+ ),
+ formatters=dict(
+ custom=dict(
+ format="%(name)s: %(levelname)s: %(message)s"
+ ),
+ ),
+ ))
+
+ #=========================================================
+ #helpers
+ #=========================================================
+ def assertConfigEquals(self, config, test):
+ assert isinstance(config, LoggingConfig)
+ for k in ("options", "loggers", "formatters", "handlers"):
+ msg = k + ":"
+ real = getattr(config, k)
+ correct = test.setdefault(k, {})
+ if real == correct:
+ continue
+ if set(real.keys()) != set(correct.keys()):
+ self.assertEqual(real, correct, msg) #force error
+ for sk in real:
+ left = real.get(sk)
+ right = correct.get(sk)
+ if left != right:
+ self.assertEqual(left, right, "%s[%r]:" % (k, sk, ))
+ raise RuntimeError
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#eof
+#=========================================================
diff --git a/bps/tests/test_meta.py b/bps/tests/test_meta.py
new file mode 100644
index 0000000..68b6b6a
--- /dev/null
+++ b/bps/tests/test_meta.py
@@ -0,0 +1,678 @@
+"""bps.meta unittest script"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import sys
+import time
+import os.path
+#package
+from bps import meta
+ak = Params = meta.Params
+#local
+from bps.tests.utils import TestCase
+#=========================================================
+#
+#=========================================================
+##
+## #interfaces
+## 'isseq', 'isnum', 'isstr',
+##
+## #introspection & monkeypatching
+## 'is_overridden',
+## 'find_attribute',
+#### 'get_module',
+#### 'get_module_exports',
+## 'instrument_super',
+##
+## #other decorators
+## 'abstract_method', 'abstract_property', 'AbstractMethodError',
+## 'decorate_per_instance',
+
+class MonkeypatchTest(TestCase):
+
+ def test_monkeypatch_class(self):
+ "test monkeypatch against a class"
+ #create test class
+ target = [0]
+ class Testum(object):
+ def abc(self, x):
+ target[0] = x
+ return x
+
+ xyz = abc
+
+ t = Testum()
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #test base method
+ self.assertEqual(t.abc(5), 5)
+ self.assertEqual(target[0], 5)
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #patch the class
+ @meta.monkeypatch(Testum)
+ def abc(self, x):
+ target[0] = 2*x
+ return 3*x
+
+ #check patch worked
+ self.assertEqual(t.abc(10), 30)
+ self.assertEqual(target[0], 20)
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #try patch with wrapping
+ @meta.monkeypatch(Testum, wrap=True)
+ def xyz(orig, self, x):
+ return 30*orig(self, 10*x)
+
+ #check patch worked
+ self.assertEqual(t.xyz(10), 3000)
+ self.assertEqual(target[0], 100)
+
+ def test_monkeypatch_object(self):
+ "test monkeypatch against an object"
+ #create test object
+ target = [0]
+ class Testum(object):
+ def abc(self, x):
+ target[0] = x
+ return x
+
+ xyz = abc
+
+ v = 1
+
+ t = Testum()
+ s = Testum()
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #test base method
+ self.assertEqual(t.abc(5), 5)
+ self.assertEqual(target[0], 5)
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #patch the class
+ @meta.monkeypatch(t)
+ def abc(x):
+ target[0] = 2*x
+ return 3*x
+
+ #check patch worked
+ self.assertEqual(t.abc(10), 30)
+ self.assertEqual(target[0], 20)
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #try patch with wrapping
+ @meta.monkeypatch(t, wrap=True)
+ def xyz(orig, x):
+ return 30*orig(10*x)
+
+ #check patch worked
+ self.assertEqual(t.xyz(10), 3000)
+ self.assertEqual(target[0], 100)
+
+ #-------------------------
+ #check patching didn't affect class or other instances
+
+ #reset target
+ target[0] = 1
+ self.assertEqual(target[0], 1)
+
+ #test base method
+ self.assertEqual(s.abc(5), 5)
+ self.assertEqual(target[0], 5)
+
+ def test_monkeypatch_attr(self):
+ #check patching a attribute (non-decorator mode)
+ class Testum(object):
+ v = 1
+ t = Testum()
+ s = Testum()
+ self.assertEqual(t.v, 1)
+ meta.monkeypatch(t, 'v')(2)
+ self.assertEqual(t.v, 2)
+ self.assertEqual(s.v, 1)
+
+ def test_monkeypatch_clobber(self):
+ class Testum(object):
+ def f(self):
+ pass
+ f = Testum.__dict__['f']
+
+ def g():
+ pass
+
+ meta.monkeypatch(Testum, clobber=False)(g)
+ self.assertIs(Testum.__dict__['g'], g)
+
+ self.assertRaises(AttributeError, meta.monkeypatch(Testum, attr="f", clobber=False), g)
+ self.assertIs(Testum.__dict__['f'], f)
+
+class MonkeypatchMixinTest(TestCase):
+
+ def test_separate_class(self):
+ "test monkeypatch of external mixin"
+
+ # A --+--> B
+ # |
+ # M --/
+ #
+ # M should be shadowed by A and B
+
+ class A(object):
+ x = 'a' #shadowed by B
+ y = 'a' #not shadowed by B
+
+ class B(A):
+ x = 'b'
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'a')
+ self.assertEqual(getattr(B,'m',None), None)
+
+ class M(object):
+ x = 'm' #shadowed by A,B
+ y = 'm' #shadowed by A
+ m = 'm'
+
+ r = meta.monkeypatch_mixin(B)(M)
+ self.assertIs(r, M)
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'a')
+ self.assertEqual(B.m, 'm')
+
+ def test_separate_class_first(self):
+ "test monkeypatch of external mixin"
+
+ # M --+--> B
+ # |
+ # A --/
+ #
+ # M should shadow A, be shadowed by B
+
+ class A(object):
+ x = 'a' #shadowed by M,B
+ y = 'a' #shadowed by M
+
+ class B(A):
+ x = 'b'
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'a')
+ self.assertEqual(getattr(B,'m',None), None)
+
+ class M(object):
+ x = 'm' #shadowed by A,B
+ y = 'm' #shadowed by A
+ m = 'm'
+
+ r = meta.monkeypatch_mixin(B, first=True)(M)
+ self.assertIs(r, M)
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'm')
+ self.assertEqual(B.m, 'm')
+
+ def test_subclass(self):
+ "if patching subclass, should be noop"
+
+ # A --> M --> B
+
+ class A(object):
+ x = 'a' #shadowed by B
+ y = 'a' #not shadowed
+
+ class M(A):
+ x = 'm'
+ y = 'm'
+ m = 'm'
+
+ class B(M):
+ x = 'b'
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'm')
+ self.assertEqual(B.m, 'm')
+
+ r = meta.monkeypatch_mixin(B)(M)
+ self.assertIs(r, M)
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'm')
+ self.assertEqual(B.m, 'm')
+
+ def test_wrong_subclass(self):
+ "patching parent should be error"
+
+ # A --> B --> M
+
+ class A(object):
+ x = 'a' #shadowed by B
+ y = 'a' #not shadowed
+
+ class B(A):
+ x = 'b'
+
+ self.assertEqual(B.x, 'b')
+ self.assertEqual(B.y, 'a')
+ self.assertEqual(getattr(B,'m',None), None)
+
+ class M(B):
+ x = 'm'
+ y = 'm'
+ m = 'm'
+
+ self.assertRaises(TypeError, meta.monkeypatch_mixin(B), M)
+
+class ParamsTest(TestCase):
+ "test bps.meta.Params class"
+
+ def test_misc(self):
+ self.assertEqual(repr(Params(1, 2, x=1)), "Params(1, 2, x=1)")
+
+ def test_constructor(self):
+ "test Params()"
+ #test constructor
+ p1 = Params()
+ self.assertEqual(p1.args, [])
+ self.assertEqual(p1.kwds, {})
+
+ p2 = Params(1, 2)
+ self.assertEqual(p2.args, [1, 2])
+ self.assertEqual(p2.kwds, {})
+
+ p3 = Params(1, 2, x=1, y=2)
+ self.assertEqual(p3.args, [1, 2])
+ self.assertEqual(p3.kwds, dict(x=1, y=2))
+
+ p4 = Params(x=1, y=2)
+ self.assertEqual(p4.args, [])
+ self.assertEqual(p4.kwds, dict(x=1, y=2))
+
+ def test_clone(self):
+ p1 = Params(1,2, x=1, y=2)
+
+ p2 = p1.clone()
+ self.assertIsNot(p2.args, p1.args)
+ self.assertEquals(p1.args, [1,2])
+ self.assertEquals(p2.args, [1,2])
+
+ self.assertIsNot(p2.kwds, p1.kwds)
+ self.assertEquals(p1.kwds, dict(x=1,y=2))
+ self.assertEquals(p2.kwds, dict(x=1,y=2))
+
+ def test_clone_mutate(self):
+ p1 = Params(1,2, x=1, y=2)
+
+ p2 = p1.clone(3,y=3,z=4)
+ self.assertIsNot(p2.args, p1.args)
+ self.assertEquals(p1.args, [1,2])
+ self.assertEquals(p2.args, [1,2,3])
+
+ self.assertIsNot(p2.kwds, p1.kwds)
+ self.assertEquals(p1.kwds, dict(x=1,y=2))
+ self.assertEquals(p2.kwds, dict(x=1,y=3,z=4))
+
+ def test_clear(self):
+ p1 = Params(1, 2, x=1, y=2)
+
+ a = p1.args
+ k = p1.kwds
+ self.assertEqual(a, [1,2])
+ self.assertEqual(k, dict(x=1,y=2))
+
+ p1.clear()
+ self.assertIs(p1.args, a)
+ self.assertIs(p1.kwds, k)
+ self.assertEqual(a, [])
+ self.assertEqual(k, dict())
+
+ def test_eq(self):
+ p1 = Params(1, 2, x=1, y=2)
+
+ p2 = Params(1, 2, x=1, y=2)
+ self.assertIsNot(p2, p1)
+ self.assertEqual(p2, p1)
+
+ p3 = Params(1, 2, x=1)
+ p4 = Params(1, 2, x=1, y=3)
+ p5 = Params(1, x=1, y=2)
+ p6 = Params(1, 3, x=1, y=2)
+ choices = [p1, p3, p4, p5, p6]
+ for c1 in choices:
+ for c2 in choices:
+ if c1 is c2:
+ self.assertEqual(c1, c2)
+ else:
+ self.assertNotEqual(c1, c2)
+
+ self.assertNotEqual(None, p1)
+
+ def test_parse(self):
+ "test Params.parse() constructor"
+ self.check_function_results(Params.parse, [
+ ak(Params(), ""),
+ ak(Params(1, 2), "1,2"),
+ ak(Params(1, 2), "(1,2)"),
+ ak(Params((1, 2)), "(1,2),"),
+ ak(Params((1, 5), 5), "(1,y),y", scope=dict(y=5)),
+ ak(Params(1, 2), "(x,2)", scope=dict(x=1)),
+ ak(Params((1, 2), z=3), "(1,2),z=3"),
+ ak(Params((1, 2), z=3), "(1,2),z=3,"),
+ ak(Params(a=1, b=2), "a=1,b=2"),
+ ak(Params(1, a=2, b=3), "1,a=2,b=3"),
+ ])
+
+ #TODO: test evil scope behavior, see if we can lock it down somehow.
+ #except restricted-python seems to be a frequently attempted pipedream,
+ #so fixing it would probably require waiting.
+ #we _could_ add a "safe" flag to parse,
+ #which simply prevents any syntaxes (eg complex exprs) that we can't lock down.
+
+ def test_render(self):
+ results = [
+ ak("", Params()),
+ ak("1, 2", Params(1, 2)),
+ ak("(1, 2)", Params((1, 2))),
+ ak("(1, 5), 5", Params((1, 5), 5)),
+ ak("(1, 2), z=3", Params((1, 2), z=3)),
+ ak("a=1, b=2", Params(a=1, b=2)),
+ ak("1, a=2, b=3", Params(1, a=2, b=3)),
+ ]
+ self.check_function_results(lambda x: x.render(), results)
+ self.check_function_results(lambda x: str(x), results)
+
+ def test_render_offset(self):
+ results = [
+ ak("2", Params(1, 2)),
+ ak("", Params((1, 2))),
+ ak("5", Params((1, 5), 5)),
+ ak("z=3", Params((1, 2), z=3)),
+ ak("a=2, b=3", Params(1, a=2, b=3)),
+
+ #NOTE: it hasn't been decided as to whether offsets
+ # which goes past end of positional args should be allowed to implicitly return empty tuple,
+ # or raise an error (the former behavior is what we currently have)
+ ak("", Params()),
+ ak("a=1, b=2", Params(a=1, b=2)),
+ ]
+ self.check_function_results(lambda x: x.render(1), results)
+
+ def test_render_class(self):
+ class Test(object):
+ pass
+ cls = meta.SingleSuperProperty
+ obj = cls(Test)
+
+ p = Params()
+ self.assertEquals(p.render_class(cls),"bps.meta.SingleSuperProperty()")
+
+ p = Params(1,2,a='a')
+ self.assertEquals(p.render_class(cls),"bps.meta.SingleSuperProperty(1, 2, a='a')")
+ self.assertEquals(p.render_class(obj),"bps.meta.SingleSuperProperty(1, 2, a='a')")
+
+
+ # check x.args is list, and can be edited directly
+ # check x.kwds is dict, and can be edited directly
+ # check x.normalize
+ # check x[int] and x[str]
+
+ def test_append(self):
+ p = Params(1,2,3,a='a',b='b')
+
+ p.append()
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='b'))
+
+ p.append(b='bb',c='c')
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='c'))
+
+ p.append(4,c='cc')
+ self.assertEqual(p.args,[1,2,3,4])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='cc'))
+
+ p.append(5,1,3)
+ self.assertEqual(p.args,[1,2,3,4,5,1,3])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='cc'))
+
+ p.append(c='c2',d=None)
+ self.assertEqual(p.args,[1,2,3,4,5,1,3])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='c2',d=None))
+
+ def test_append_modified(self):
+ p = Params(1,2,3,a='a',b='b')
+
+ p.append_modified({})
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='b'))
+
+ p.append_modified(dict(c=1,d=None))
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='b',c=1))
+
+ p.append_modified(dict(c=2,d=None), default=2)
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='b',c=1,d=None))
+
+ def test_insert(self):
+ p = Params(1,2,3,a='a',b='b')
+
+ p.insert(2)
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='b'))
+
+ p.insert(2,b='bb',c='c')
+ self.assertEqual(p.args,[1,2,3])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='c'))
+
+ p.insert(2,4,c='cc')
+ self.assertEqual(p.args,[1,2,4,3])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='cc'))
+
+ p.insert(4,5,1,3)
+ self.assertEqual(p.args,[1,2,4,3,5,1,3])
+ self.assertEqual(p.kwds,dict(a='a',b='bb',c='cc'))
+
+class MiscTest(TestCase):
+
+ def test_lookup_module_files(self):
+ "test lookup_module() against known py files"
+ lookup_module = meta.lookup_module
+ import bps
+ for module in (os, meta):
+ path = module.__file__
+ self.assertEquals(lookup_module(path), module)
+ self.assertEquals(lookup_module(path, name=True), module.__name__)
+
+ def test_lookup_module_packages(self):
+ "test lookup_module() against known packages"
+ lookup_module = meta.lookup_module
+ import bps as module
+ path = module.__file__
+ dir = os.path.dirname(path)
+ self.assertEquals(lookup_module(path), module)
+ self.assertEquals(lookup_module(path, name=True), module.__name__)
+ self.assertEquals(lookup_module(dir), module)
+ self.assertEquals(lookup_module(dir, name=True), module.__name__)
+
+ if os.name in ("posix", "nt"):
+ def test_lookup_module_compiled(self):
+ "test lookup_module() against a compiled extension"
+ lookup_module = meta.lookup_module
+
+ if os.name == "nt":
+ name = "select" #known to be a .pyd under nt
+ else:
+ assert os.name == "posix"
+ name = "audioop" #known to be a .so under linux
+
+ #test module isn't already in use, allowing us to remove it at will
+ #TODO: could remember & restore state
+ self.assert_(name not in sys.modules)
+
+ #import module & test compiled-module handling
+ module = __import__(name)
+ path = module.__file__
+ self.assert_(os.path.splitext(path)[1] in meta._cmod_exts)
+ self.assertEquals(lookup_module(path), module)
+ self.assertEquals(lookup_module(path, name=True), name)
+
+ #now test no detection if module not loaded
+ del sys.modules[name]
+ self.assertEquals(lookup_module(path), None)
+ self.assertEquals(lookup_module(path, name=True), None)
+
+ def test_func_accepts_key(self):
+ def check(f, k, r=True):
+ self.assertEqual(meta.func_accepts_key(f, k), r)
+
+ #check normal func
+ def f(a, b):
+ pass
+ check(f, 'a')
+ check(f, 'b')
+ check(f, 'c', False)
+ check(f, ['a', 'b'])
+ check(f, ['a', 'c'], False)
+
+
+ #check normal func
+ def f(a=None, b=None):
+ pass
+ check(f, 'a')
+ check(f, 'b')
+ check(f, 'c', False)
+ check(f, ['a', 'b'])
+ check(f, ['a', 'c'], False)
+
+ #check kwd func
+ def f(**k):
+ pass
+ check(f, 'a')
+ check(f, 'b')
+ check(f, 'c')
+ check(f, ['a', 'b'])
+ check(f, ['a', 'c'])
+
+ #check class
+ class f(object):
+ def __init__(self, a, b=None):
+ pass
+ check(f, "self", False) #first arg shouldn't count
+ check(f, 'a')
+ check(f, 'b')
+ check(f, 'c', False)
+ check(f, ['a', 'b'])
+ check(f, ['a', 'c'], False)
+
+class FallbackMethodTest(TestCase):
+ "tests class_property, fallback_method, fallback_property"
+
+ def test_class_property(self):
+ class Test:
+
+ @meta.class_property
+ def test(*a, **k):
+ return 1, a, k
+ self.assertEquals(Test.test, (1, (Test,),{}))
+ test = Test()
+ self.assertEquals(test.test, (1, (Test,),{}))
+
+ def test_fallback_property(self):
+ class Test:
+
+ @meta.fallback_property
+ def test(*a, **k):
+ return 1, a, k
+ self.assertEquals(Test.test, (1, (None, Test),{}))
+ test = Test()
+ self.assertEquals(test.test, (1, (test, Test),{}))
+
+ if meta._classobj:
+ def test_classobj(self):
+ class Test:
+
+ @meta.fallback_method
+ def test(*a, **k):
+ return a,k
+
+ self.assert_(isinstance(Test, meta._classobj))
+
+ func = Test.__dict__['test'].im_func
+
+ a = Test.test
+ self.assertIs(a.im_self, None)
+ self.assertIs(a.im_class, Test)
+ self.assertIs(a.im_func, func)
+
+ self.assertIsNot(Test.test, a)
+
+ self.assertEquals(a(), ((None, Test),{}))
+ self.assertEquals(a(1,2), ((None, Test,1,2),{}))
+ self.assertEquals(a(1,2,x=1), ((None, Test,1,2),{'x':1}))
+
+ self._check_instance(Test)
+
+ def test_class(self):
+ class Test(object):
+
+ @meta.fallback_method
+ def test(*a, **k):
+ return a,k
+
+ func = Test.__dict__['test'].im_func
+
+ a = Test.test
+ self.assertIs(a.im_self, None)
+ self.assertIs(a.im_class, Test)
+ self.assertIs(a.im_func, func)
+
+ self.assertIs(Test.test, a)
+
+ self.assertEquals(a(), ((None, Test),{}))
+ self.assertEquals(a(1,2), ((None, Test,1,2),{}))
+ self.assertEquals(a(1,2,x=1), ((None, Test,1,2),{'x':1}))
+
+ self._check_instance(Test)
+
+ def _check_instance(self, Test):
+ func = Test.__dict__['test'].im_func
+ test = Test()
+ a = test.test
+
+ self.assertIs(a.im_self, test)
+ self.assertIs(a.im_class, Test)
+ self.assertIs(a.im_func, func)
+
+ self.assertIs(test.test, a)
+ self.assertIs(test.__dict__['test'], a)
+
+ self.assertEquals(a(), ((test, Test),{}))
+ self.assertEquals(a(1,2), ((test, Test,1,2),{}))
+ self.assertEquals(a(1,2,x=1), ((test, Test,1,2),{'x':1}))
+
+#=========================================================
+#eof
+#=========================================================
diff --git a/bps/tests/test_misc.py b/bps/tests/test_misc.py
new file mode 100644
index 0000000..8bf550f
--- /dev/null
+++ b/bps/tests/test_misc.py
@@ -0,0 +1,179 @@
+"""tests for bps.misc -- (c) Assurance Technologies 2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+#site
+#pkg
+from bps import misc
+#module
+from bps.tests.utils import TestCase
+#=========================================================
+#
+#=========================================================
+class PropertyTest(TestCase):
+ "test various property constructors"
+
+ def test_indirect_property(self):
+ class Test(object):
+
+ test = misc.indirect_property("tget", "tset")
+
+ x = 1
+ def tget(self):
+ return self.x
+ def tset(self, value):
+ self.x = value
+
+ class Test2(Test):
+ def tget(self):
+ return self.x*2
+
+ def tset(self, value):
+ self.x = -value
+
+ #test direct works
+ t = Test()
+ self.assertEqual(t.x, 1)
+ self.assertEqual(t.test, 1)
+ t.test = 3
+ self.assertEqual(t.x, 3)
+ self.assertEqual(t.test, 3)
+
+ #test subclass overide works
+ t2 = Test2()
+ self.assertEqual(t2.x, 1)
+ self.assertEqual(t2.test, 2)
+ t2.test = 3
+ self.assertEqual(t2.x, -3)
+ self.assertEqual(t2.test, -6)
+
+ #test instance override works
+ t3 = Test2()
+ t3.tget = lambda : t3.x+.5
+ self.assertEqual(t3.x, 1)
+ self.assertEqual(t3.test, 1.5)
+
+ def test_constructor_property(self):
+ class Test(object):
+ test = misc.constructor_property(dict)
+
+ #test class view
+ self.assertIsInstance(Test.test, misc.constructor_property)
+
+ #check initial construction
+ t = Test()
+ d = t.test
+ self.assertIsInstance(d, dict)
+
+ #check we get same attr next time
+ self.assertIs(t.test, d)
+
+ #check overwrite works
+ e = [2]
+ t.test = e
+ self.assertIs(t.test, e)
+
+ #check delete causes re-creation
+ del t.test
+ f = t.test
+ self.assertIsInstance(f, dict)
+ self.assertIsNot(d, f)
+
+ def test_constructor_property_passref(self):
+ #check passref works
+ def f(obj):
+ return [obj]
+ class Test(object):
+ test = misc.constructor_property(f, passref=True)
+
+ #test class view
+ self.assertIsInstance(Test.test, misc.constructor_property)
+
+ #check initial construction
+ t = Test()
+ d = t.test
+ self.assertIsInstance(d, list)
+ self.assertEquals(d, [t])
+
+ #check we get same attr next time
+ self.assertIs(t.test, d)
+
+ #check overwrite works
+ e = [2]
+ t.test = e
+ self.assertIs(t.test, e)
+
+ #check delete causes re-creation
+ del t.test
+ f = t.test
+ self.assertIsInstance(f, list)
+ self.assertIsNot(f, d)
+ self.assertEquals(f, d)
+
+ def test_class_property(self):
+ class Test(object):
+ x = 1
+
+ @misc.class_property
+ def test(self):
+ return self, self.x
+
+ #make sure it works as class property
+ self.assertEquals(Test.x, 1)
+ self.assertEquals(Test.test, (Test, 1))
+
+ #make sure it doesn't return instance
+ t = Test()
+ self.assertEquals(t.x, 1)
+ self.assertEquals(t.test, (Test, 1))
+
+ #make sure it reads from the class, not instance
+ t.x = 2
+ self.assertEquals(t.x, 2)
+ self.assertEquals(t.test, (Test, 1))
+
+#=========================================================
+#
+#=========================================================
+
+class ParseAgentTest(TestCase):
+
+ def test_parse_agent_string(self):
+ for s in self.agents:
+ #TODO: should compare to return values,
+ #not just make sure we _can_ parse this
+ misc.parse_agent_string(s)
+
+ #this is just a random assorted of agent strings
+ # that should be parseable
+ agents = [
+ #firefox
+ "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.0.11) Gecko/2009060309 Ubuntu/9.04 (jaunty) Firefox/3.0.11"
+ 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7',
+
+ #msie
+ 'Mozilla/4.0 (compatible; MSIE 6.0; AOL 9.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)',
+ 'Mozilla/4.0 (compatible; MSIE 5.5; Windows 98)',
+ 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; FunWebProducts; .NET CLR 1.1.4322)',
+ 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)',
+
+ #konq
+ 'Mozilla/5.0 (compatible; Konqueror/3.4; Linux) KHTML/3.4.1 (like Gecko)',
+
+ #safari
+ 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/417.9 (KHTML, like Gecko) Safari/417.8',
+
+ #TODO: chrome
+
+ #java
+ 'Mozilla/4.0 (Windows XP 5.1) Java/1.6.0_07',
+
+ #various bots
+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
+ 'Mozilla/5.0 (compatible; Yahoo! Slurp; http://help.yahoo.com/help/us/ysearch/slurp)',
+ 'Mozilla/5.0 (compatible; Ask Jeeves/Teoma; +http://about.ask.com/en/docs/about/webmasters.shtml)'
+ 'msnbot/0.9 (+http://search.msn.com/msnbot.htm)',
+ 'XmlRssTimingBot/2.03 (libwww-perl/5.800)',
+ ]
diff --git a/bps/tests/test_numeric.py b/bps/tests/test_numeric.py
new file mode 100644
index 0000000..9e0c5c1
--- /dev/null
+++ b/bps/tests/test_numeric.py
@@ -0,0 +1,771 @@
+"""
+test_bps3 -- bps3 unittest script -- (c) Assurance Technologies 2003-2006
+
+defines unit tests for bps lib.
+
+NOTE: this module should import bps3 modules
+relative to sys.path, not locally, since it may be run in another location.
+"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import sys
+from itertools import islice
+from decimal import Decimal
+#site
+#pkg
+from bps import numeric as num
+from bps.rng import random
+from bps.meta import Params as ak
+#module
+from bps.tests.utils import TestCase
+native = sys.byteorder
+#=========================================================
+#number theory funcs
+#=========================================================
+class NumberTheoryTest(TestCase):
+ #TODO: test gcd, lcm
+
+ composites = [
+ 4, 8, 12, 7*6, 108, 641**5 * 431**2 * 449
+ ]
+ factors = {
+ -1: [],
+ 0: [],
+ 1: [],
+ 2: [(2, 1)],
+ 8:[(2, 3)],
+ -10:[(2, 1), (5, 1)],
+ }
+ def test_factors(self):
+ "run factors() against simple & border test cases"
+ for value, factors in self.factors.iteritems():
+ self.assertEqual(num.factors(value), factors)
+ for value in PrimeTest.primes:
+ f = num.factors(value)
+ self.assert_(f == [(value, 1)], "prime %r has wrong factors: %r" % (value, f))
+ for value in self.composites:
+ f = num.factors(value)
+ self.assert_(len(f) > 1 or (f[0][0] < value and f[0][1] > 1),
+ "composite %r has wrong factors: %r" % (value, f))
+
+ def test_random_factors(self):
+ "run factors() against randomly generated composites"
+ primes = PrimeTest.primes
+ for r in xrange(25):
+ c = random.randrange(1, 9)
+ out = set()
+ while len(out) < c:
+ out.add(random.choice(primes))
+ f = [
+ (p, random.randrange(1, 7))
+ for p in sorted(out)
+ ]
+ n = 1
+ for p, e in f:
+ n *= (p**e)
+ result = num.factors(n)
+ self.assertEqual(result, f)
+
+ def test_gcd(self):
+ self.check_function_results(num.gcd, [
+ #test zero behavior
+ (0, 0, 0),
+ (100, 100, 0),
+ (100, 0, 100),
+
+ #test 1 behavior
+ (1, 1, 10),
+ (1, 1, 2),
+ (1, 1, 3),
+
+ #test prime behavior
+ (1, 5, 7),
+
+ #test various composites
+ (5, 10, 15),
+
+ #test negatives
+ (2, 10, 4),
+ (2, -10, 4),
+ (2, 10, -4),
+ (2, -10, -4),
+ ])
+
+ def test_lcm(self):
+ self.check_function_results(num.lcm, [
+ (40, 10, 8),
+ (120, 15, 40),
+ (45, 15, 45),
+ ])
+
+#=========================================================
+#primality funcs
+#=========================================================
+class PrimeTest(TestCase):
+ "test primality/factorization"
+ #the first 128 primes (that's 64 more than is stored internally,
+ # so that we test both modes of operations
+ primes = [
+ #prime 0
+ 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,
+ 59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,
+ 137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,
+ 227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,
+
+ #^ end of bps.numeric._small_primes
+
+ #prime 64
+ 313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,
+ 419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,
+ 509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,
+ 617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,
+
+ #prime 128
+ 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827,
+ 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
+ 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049,
+ 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151, 1153, 1163,
+
+ #prime 192
+ 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283,
+ 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373, 1381, 1399, 1409, 1423,
+ 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
+ 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607, 1609, 1613, 1619,
+
+ #^ prime 255
+ ]
+
+ big_primes = [
+
+
+ ]
+
+ def test_is_prime(self):
+ primes = set(self.primes)
+ for value in xrange(-10, max(primes)):
+ self.assertEqual(num.is_prime(value), value in primes)
+
+ def test_is_mr_prime(self):
+ primes = set(self.primes)
+ for value in xrange(-10, max(primes)):
+ self.assertEqual(num.is_mr_prime(value), value in primes)
+
+ def test_iter_primes(self):
+ #test the list matches
+ primes = list(islice(num.iter_primes(), len(self.primes)))
+ self.assertEqual(primes, self.primes)
+
+ #what if we start real low
+ primes = list(islice(num.iter_primes(-100), len(self.primes)))
+ self.assertEqual(primes, self.primes)
+
+ #in middle of small primes
+ primes = list(islice(num.iter_primes(53), len(self.primes)-15))
+ self.assertEqual(primes, self.primes[15:])
+
+ #at end of small primes
+ primes = list(islice(num.iter_primes(310), len(self.primes)-63))
+ self.assertEqual(primes, self.primes[63:])
+
+ #at end of small primes 2
+ primes = list(islice(num.iter_primes(311), len(self.primes)-63))
+ self.assertEqual(primes, self.primes[63:])
+
+ #at end of small primes 3
+ primes = list(islice(num.iter_primes(313), len(self.primes)-64))
+ self.assertEqual(primes, self.primes[64:])
+
+ #test 'stop' kwd
+ primes = list(num.iter_primes(313, 419))
+ self.assertEqual(primes, self.primes[64:64+16])
+
+ primes = list(num.iter_primes(312, 419))
+ self.assertEqual(primes, self.primes[64:64+16])
+
+ #test 'count' kwd
+ primes = list(num.iter_primes(313, count=16))
+ self.assertEqual(primes, self.primes[64:64+16])
+
+ #test stop < count
+ primes = list(num.iter_primes(313, 419, count=32))
+ self.assertEqual(primes, self.primes[64:64+16])
+
+ #test stop > count
+ primes = list(num.iter_primes(313, 900, count=16))
+ self.assertEqual(primes, self.primes[64:64+16])
+
+ def test_np_prime(self):
+ "test next_prime & prev_prime"
+ #before first prime
+ for value in xrange(-10, 2):
+ self.assertEqual(num.next_prime(value), 2)
+ self.assertEqual(num.prev_prime(value), None)
+
+ #test 2
+ self.assertEqual(num.next_prime(2), 3)
+ self.assertEqual(num.prev_prime(2), None)
+
+ #over first 128 primes (avoiding 2 & last one)
+ for idx, value in enumerate(self.primes[1:-1]):
+ idx += 1
+ assert self.primes[idx] == value
+
+ #prev
+ prev = self.primes[idx-1]
+ self.assertEqual(num.prev_prime(value+2), value)
+ self.assertEqual(num.prev_prime(value+1), value)
+ self.assertEqual(num.prev_prime(value), prev, "value: %r" % value)
+ if prev == value-1:
+ assert value == 3
+ self.assertEqual(num.prev_prime(value-1), None)
+ self.assertEqual(num.prev_prime(value-2), None)
+ elif prev == value-2:
+ self.assertEqual(num.prev_prime(value-1), prev)
+ self.assert_(num.prev_prime(value-2) < prev)
+ else:
+ self.assertEqual(num.prev_prime(value-1), prev)
+ self.assertEqual(num.prev_prime(value-2), prev)
+
+ #next
+ next = self.primes[idx+1]
+ if value == 3:
+ self.assertEqual(num.next_prime(value-2), 2)
+ else:
+ self.assertEqual(num.next_prime(value-2), value)
+ self.assertEqual(num.next_prime(value-1), value)
+ self.assertEqual(num.next_prime(value), next)
+ self.assertEqual(num.next_prime(value+1), next)
+ if next == value+2:
+ self.assert_(num.next_prime(value+2) > next, "v=%r nv+2=%r n=%r" % (value, num.next_prime(value+2), next))
+ else:
+ self.assertEqual(num.next_prime(value+2), next)
+
+#=========================================================
+#bit string funcs
+#=========================================================
+class BytesTest(TestCase):
+
+ def test_list_to_bytes(self):
+ self.check_function_results(num.list_to_bytes, [
+ #standard big endian
+ ak('\x00', [0], 1),
+ ak('\x01', [1], 1),
+ ak('\x00\x01', [1], 2),
+ ak('\x00\x01', [0, 1], 2),
+ ak('\x00\x00\x01', [1], 3),
+ ak('\x00\x00\x00\x00', [0], 4),
+ ak('\x00\x00\x00\x01', [1], 4),
+ ak('\x00\x00\x00\xff', [255], 4),
+ ak('\x00\x00\x01\xff', [1, 255], 4),
+ ak('\x04\x03\x02\x01', [4, 3, 2, 1], 4),
+
+ #standard little endian
+ ak('\x00', [0], 1, order="little"),
+ ak('\x01', [1], 1, order="little"),
+ ak('\x01\x00', [1], 2, order="little"),
+ ak('\x01\x00', [0, 1], 2, order="little"),
+ ak('\x01\x00\x00', [1], 3, order="little"),
+ ak('\x00\x00\x00\x00', [0], 4, order="little"),
+ ak('\x01\x00\x00\x00', [1], 4, order="little"),
+ ak('\xff\x00\x00\x00', [255], 4, order="little"),
+ ak('\xff\x01\x00\x00', [1, 255], 4, order="little"),
+ ak('\x01\x02\x03\x04', [4, 3, 2, 1], 4, order="little"),
+
+ ])
+
+ #check bytes size check
+ self.assertRaises(ValueError, num.list_to_bytes, [])
+ self.assertRaises(ValueError, num.list_to_bytes, [0, 0], bytes=1)
+
+ #check bytes bound check
+ self.assertRaises(ValueError, num.list_to_bytes, [256], bytes=1)
+
+ #quick check native mode works right
+ if native == "little":
+ self.assertEqual(num.list_to_bytes([1], 3, order="native"), '\x01\x00\x00')
+ else:
+ self.assertEqual(num.list_to_bytes([1], 3, order="native"), '\x00\x00\x01')
+
+ def test_bytes_to_list(self):
+ self.check_function_results(num.bytes_to_list, [
+
+ #standard big endian
+ ak([1], '\x01'),
+ ak([0, 1], '\x00\x01'),
+ ak([0, 0, 1], '\x00\x00\x01'),
+ ak([0, 0, 0, 0],'\x00\x00\x00\x00'),
+ ak([0, 0, 0, 1],'\x00\x00\x00\x01'),
+ ak([0, 0, 0, 255],'\x00\x00\x00\xff'),
+ ak([0, 0, 1, 0],'\x00\x00\x01\x00'),
+ ak([4, 3, 2, 1],'\x04\x03\x02\x01'),
+
+ #standard little endian
+ ak([1], '\x01', order="little"),
+ ak([0, 1], '\x01\x00', order="little"),
+ ak([0, 0, 1], '\x01\x00\x00', order="little"),
+ ak([0, 0, 0, 0], '\x00\x00\x00\x00', order="little"),
+ ak([0, 0, 0, 1], '\x01\x00\x00\x00', order="little"),
+ ak([0, 0, 0, 255], '\xff\x00\x00\x00', order="little"),
+ ak([0, 0, 1, 0], '\x00\x01\x00\x00', order="little"),
+ ak([4, 3, 2, 1],'\x01\x02\x03\x04', order="little"),
+
+ ])
+
+ #quick check native mode works right
+ if native == "little":
+ self.assertEqual(num.bytes_to_list('\x01\x00\x00', order="native"), [0, 0, 1])
+ else:
+ self.assertEqual(num.bytes_to_list('\x00\x00\x01', order="native"), [0, 0, 1])
+
+ def test_int_to_bytes(self):
+ self.check_function_results(num.int_to_bytes, [
+ #standard big endian
+ ak('\x00', 0, 1),
+ ak('\x01', 1, 1),
+ ak('\x00\x01', 1, 2),
+ ak('\x00\x00\x01', 1, 3),
+ ak('\x00\x00\x00\x00', 0, 4),
+ ak('\x00\x00\x00\x01', 1, 4),
+ ak('\x00\x00\x00\xff', 255, 4),
+ ak('\x00\x00\x01\x00', 256, 4),
+ ak('\x04\x03\x02\x01', 0x04030201, 4),
+
+ #standard little endian
+ ak('\x00', 0, 1, order="little"),
+ ak('\x01', 1, 1, order="little"),
+ ak('\x01\x00', 1, 2, order="little"),
+ ak('\x01\x00\x00', 1, 3, order="little"),
+ ak('\x00\x00\x00\x00', 0, 4, order="little"),
+ ak('\x01\x00\x00\x00', 1, 4, order="little"),
+ ak('\xff\x00\x00\x00', 255, 4, order="little"),
+ ak('\x00\x01\x00\x00', 256, 4, order="little"),
+ ak('\x01\x02\x03\x04', 0x04030201, 4, order="little"),
+
+ ])
+
+ #check bytes bound check
+ self.assertRaises(ValueError, num.int_to_bytes, 256, bytes=1)
+
+ #check upper bound check
+ self.assertRaises(ValueError, num.int_to_bytes, 129, upper=128)
+
+ #check bytes/upper check
+ self.assertRaises(ValueError, num.int_to_bytes, 1, bytes=1, upper=512)
+
+ #quick check native mode works right
+ if native == "little":
+ self.assertEqual(num.int_to_bytes(1, 3, order="native"), '\x01\x00\x00')
+ else:
+ self.assertEqual(num.int_to_bytes(1, 3, order="native"), '\x00\x00\x01')
+
+ def test_bytes_to_int(self):
+ self.check_function_results(num.bytes_to_int, [
+ #standard big endian
+ ak(1, '\x01'),
+ ak(1, '\x00\x01'),
+ ak(1, '\x00\x00\x01'),
+ ak(0,'\x00\x00\x00\x00'),
+ ak(1,'\x00\x00\x00\x01'),
+ ak(255,'\x00\x00\x00\xff'),
+ ak(256,'\x00\x00\x01\x00'),
+ ak(0x04030201,'\x04\x03\x02\x01'),
+
+ #standard little endian
+ ak(1, '\x01', order="little"),
+ ak(1, '\x01\x00', order="little"),
+ ak(1, '\x01\x00\x00', order="little"),
+ ak(0, '\x00\x00\x00\x00', order="little"),
+ ak(1, '\x01\x00\x00\x00', order="little"),
+ ak(255, '\xff\x00\x00\x00', order="little"),
+ ak(256, '\x00\x01\x00\x00', order="little"),
+ ak(0x04030201,'\x01\x02\x03\x04', order="little"),
+
+ ])
+
+ #quick check native mode works right
+ if native == "little":
+ self.assertEqual(num.bytes_to_int('\x01\x00\x00', order="native"), 1)
+ else:
+ self.assertEqual(num.int_to_bytes('\x00\x00\x01', order="native"), 1)
+
+ def test_xor_bytes(self):
+ self.check_function_results(num.xor_bytes, [
+ #result, left, right
+ ak('\x00\x00\x00\x00', '\x00\x00\x00\x00', '\x00\x00\x00\x00'),
+ ak('\x00\x00\xff\x00', '\xff\x00\xff\x00', '\xff\x00\x00\x00'),
+ ak('\x00\x00\x00\x00', '\xff\x00\xff\x00', '\xff\x00\xff\x00'),
+ ak('\x00\x44\x03\x02', '\x08\x04\x02\x03', '\x08\x40\x01\x01')
+ ])
+ self.check_bs_func(num.xor_bytes, lambda a, b: a^b)
+
+ def test_align_bytes(self):
+ #since xor_bytes/and/etc all use the same alignment func,
+ #we're just quickly testing xor_bytes
+
+ self.assertRaises(ValueError, num.xor_bytes, '\x00', '\x00\x21')
+ self.assertRaises(ValueError, num.xor_bytes, '\x00', '\x00\x21', order=None)
+
+ self.assertEqual(num.xor_bytes('\x01', '\x00\x21', order="big"), '\x00\x20')
+ #^ same as '\x00\x21' \x00\x01'
+ self.assertEqual(num.xor_bytes('\x01', '\x00\x21', order="little"), '\x01\x21')
+ #^ same as '\x00\x21' \x01\x00'
+
+ def test_and_bytes(self):
+ self.check_function_results(num.and_bytes, [
+ #result, left, right
+ ak('\x00\x00\x00\x00', '\x00\x00\x00\x00', '\x00\x00\x00\x00'),
+ ak('\xff\x00\x00\x00', '\xff\x00\xff\x00', '\xff\x00\x00\x00'),
+ ak('\xff\x00\xff\x00', '\xff\x00\xff\x00', '\xff\x00\xff\x00'),
+ ak('\x08\x00\x00\x01', '\x08\x04\x02\x03', '\x08\x40\x01\x01')
+ ])
+ self.check_bs_func(num.and_bytes, lambda a, b: a&b)
+
+ def test_or_bytes(self):
+ self.check_function_results(num.or_bytes, [
+ #result, left, right
+ ak('\x00\x00\x00\x00', '\x00\x00\x00\x00', '\x00\x00\x00\x00'),
+ ak('\xff\x00\xff\x00', '\xff\x00\xff\x00', '\xff\x00\x00\x00'),
+ ak('\xff\x00\xff\x00', '\xff\x00\xff\x00', '\xff\x00\xff\x00'),
+ ak('\x08\x44\x03\x03', '\x08\x04\x02\x03', '\x08\x40\x01\x01')
+ ])
+ self.check_bs_func(num.or_bytes, lambda a, b: a|b)
+
+ def test_binop_bytes(self):
+ #note: this also checks some python invariants, just to be safe,
+ #as well as some internal bits of bs_op.
+ #under the guise of that, we test using bs_op to perform NAND
+ assert -1 % 256 == 255
+ assert 255 % 256 == 255
+ def nand(a, b):
+ assert a % 256 == a
+ assert b % 256 == b
+ c = 256 + ~ (a & b)
+ assert c % 256 == c
+ return c
+ self.check_function_results(num.binop_bytes, [
+ #result, left, right
+ ak('\xff\xff\xff\xff', '\x00\x00\x00\x00', '\x00\x00\x00\x00', nand),
+ ak('\x00\xff\xff\xff', '\xff\x00\xff\x00', '\xff\x00\x00\x00', nand),
+ ak('\x00\xff\x00\xff', '\xff\x00\xff\x00', '\xff\x00\xff\x00', nand),
+ ak('\xf7\xff\xff\xfe', '\x08\x04\x02\x03', '\x08\x40\x01\x01', nand)
+ ])
+
+ def test_invert_bytes(self):
+ self.check_function_results(num.invert_bytes, [
+ ak('\x00\xff', '\xff\x00'),
+ ak('\x84\x21\x00', '\x7b\xde\xff'),
+ ])
+
+ def check_bs_func(self, func, op):
+ "check bool operation over random bytes"
+ for r in xrange(1000):
+ al = random.randrange(1, 9)
+ bl = random.randrange(1, 9)
+ a = random.getrandbytes(al)
+ b = random.getrandbytes(bl)
+
+ #do big-endian
+ av = num.bytes_to_int(a)
+ bv = num.bytes_to_int(b)
+ cv = op(av, bv)
+ c = num.int_to_bytes(cv, max(al, bl))
+ self.assertEqual(func(a, b, order="big"), c)
+
+ #do little-endian
+ av = num.bytes_to_int(a, order="little")
+ bv = num.bytes_to_int(b, order="little")
+ cv = op(av, bv)
+ c = num.int_to_bytes(cv, max(al, bl), order="little")
+ self.assertEqual(func(a, b, order="little"), c)
+
+#=========================================================
+#roman numeral funcs
+#=========================================================
+class RomanTest(TestCase):
+ # I V X L C D M
+ # 1 5 10 50 100 500 1000
+
+ roman_pairs = [
+ #pairs tests forward and backward
+('i', 1), ('ii', 2), ('iii', 3), ('iv', 4),
+('v', 5), ('vi', 6), ('vii', 7), ('viii', 8),
+('ix', 9), ('x', 10), ('xi', 11), ('xii', 12),
+('xiii', 13), ('xiv', 14), ('xv', 15),
+('xlv', 45), ('xlvi', 46), ('xlvii', 47), ('xlviii', 48),
+('xlix', 49), ('l', 50), ('li', 51),
+('xcix', 99), ('c', 100), ('ci', 101),
+('cxcix', 199), ('cc', 200), ('cci', 201),
+('cccxcix', 399), ('cd', 400), ('cdi', 401),
+('cmxcix', 999), ('m', 1000), ('mi', 1001),
+('mcmxcviii', 1998), ('mcmxcix', 1999), ('mm', 2000), ('mmi', 2001),
+('mmmcmxcix', 3999),
+ ]
+
+ ns_roman_pairs = [
+ #non-standard roman -- not allowed in strict mode
+
+ #duplicate elements
+ ('xxxxxx', 60),
+ ('mmmmm', 5000),
+
+ #duplicate stanzas
+ ('iviv', 8),
+ ('ivivx', 2),
+
+ #over-large substraction stanzas
+ ('iiiiv', 1),
+ ('vix', 4),
+ ]
+
+ invalid_roman = [
+ #grammatically incorrect (encodes a negative w/in a subtraction stanza)
+ "vvx", "iiiiiv", "iviviix",
+ #wrong literals
+ "", "axcv",
+ ]
+
+ def test_int_to_roman(self):
+ for roman, arabic in self.roman_pairs:
+ self.assertEqual(num.int_to_roman(arabic), roman.upper())
+ self.assertRaises(ValueError, num.int_to_roman, -1)
+ self.assertRaises(ValueError, num.int_to_roman, 0)
+ self.assertRaises(ValueError, num.int_to_roman, 4001)
+
+ #test dialects
+ self.assertEqual(num.int_to_roman(99), "xcix".upper())
+ self.assertEqual(num.int_to_roman(99, dialect="standard"), "xcix".upper())
+ self.assertEqual(num.int_to_roman(99, dialect="additive"), "lxxxxviiii".upper())
+
+ #test some invariants...
+ #2. the powers of ten should never occur >3 times
+ for i in xrange(1, 3999):
+ r = num.int_to_roman(i)
+ #the non-powers of ten should never occur twice in a row
+ for c in "VLD":
+ self.assert_((c*2) not in r)
+ for c in "IXCM":
+ self.assert_((c*4) not in r)
+
+ def test_roman_to_int(self):
+ #test std pairs
+ for roman, arabic in self.roman_pairs:
+ self.assertEqual(num.roman_to_int(roman), arabic)
+
+ #run all numbers through and back
+ for i in xrange(1, 3999):
+ self.assertEqual(num.roman_to_int(num.int_to_roman(i)), i)
+
+ #check for some non-standard but correct ones
+ for roman, arabic in self.ns_roman_pairs:
+ self.assertEqual(num.roman_to_int(roman), arabic)
+ self.assertRaises(ValueError, num.roman_to_int, roman, strict=True)
+
+ #check invalid romans
+ for roman in self.invalid_roman:
+ self.assertRaises(ValueError, num.roman_to_int, roman)
+
+#=========================================================
+#base conversions
+#=========================================================
+
+# int_to_base
+# int_from_base -- int
+# float_to_base
+# float_from_base
+ # test float_to_base(1<<BPF,2) - was throwing error
+
+#=========================================================
+#misc
+#=========================================================
+
+class MiscTest(TestCase):
+
+ def test_sdivmod(self):
+ sdivmod = num.sdivmod
+
+ def ts(x,y,cd,cr):
+ rd,rr = sdivmod(x,y)
+ if isinstance(x, Decimal):
+ self.assertIsInstance(rr, Decimal)
+ elif isinstance(x, float):
+ self.assertIsInstance(rr, float)
+ self.assertEquals(rd, cd)
+ self.assertEquals(rr, cr)
+
+ ts(12,5, 2,2)
+ ts(-12,5, -2,-2)
+
+ ts(12.5,5, 2, 2.5)
+ ts(-12.5,5, -2, -2.5)
+
+ ts(Decimal("12.5"), 5, 2, Decimal("2.5"))
+ ts(Decimal("-12.5"), 5, -2, Decimal("-2.5"))
+
+ def test_splitfrac(self):
+ def ts(v, ci, cf):
+ ri, rf = num.splitfrac(v)
+ if isinstance(v, long):
+ self.assertIsInstance(ri, long)
+ self.assertIsInstance(rf, int) #could make this a long for symetry, but it's not worth it
+ elif isinstance(v, int):
+ self.assertIsInstance(ri, int)
+ self.assertIsInstance(rf, int)
+ elif isinstance(v, float):
+ self.assertIsInstance(ri, int)
+ self.assertIsInstance(rf, float)
+ elif isinstance(v, Decimal):
+ self.assertIsInstance(ri, int)
+ self.assertIsInstance(rf, Decimal)
+ else:
+ raise TypeError
+ self.assertEquals(ri, ci)
+ self.assertEquals(rf, cf)
+
+ #float w/ frac portion
+ ts(-10.75, -10, -.75)
+ ts(-1.25, -1, -.25)
+ ts(0.25, 0, .25)
+ ts(1.25, 1, .25)
+ ts(10.25, 10, .25)
+
+ #float w/o frac portion
+ ts(-12.0, -12, 0)
+ ts(-1.0, -1, 0)
+ ts(0.0, 0, 0)
+ ts(1.0, 1, 0)
+ ts(12.0, 12, 0)
+
+ #decimal w/ frac portion
+ ts(Decimal("-10.1"), -10, Decimal("-.1"))
+ ts(Decimal("-1.1"), -1, Decimal("-.1"))
+ ts(Decimal("-.1"), 0, Decimal("-.1"))
+ ts(Decimal(".1"), 0, Decimal(".1"))
+ ts(Decimal("1.1"), 1, Decimal(".1"))
+ ts(Decimal("12.1"), 12, Decimal(".1"))
+
+ #decimal w/o frac portion
+ ts(Decimal("-10.0"), -10, Decimal("0"))
+ ts(Decimal("-1.0"), -1, Decimal("0"))
+ ts(Decimal("0.0"), 0, Decimal("0"))
+ ts(Decimal("1.0"), 1, Decimal("0"))
+ ts(Decimal("12.0"), 12, Decimal("0"))
+
+ #ints
+ ts(-10, -10, 0)
+ ts(0,0,0)
+ ts(1, 1, 0)
+ ts(10, 10, 0)
+
+ #longs
+ ts(1L, 1L, 0)
+
+ #TODO: Decimal support
+
+ def test_int_to_base(self):
+ self.check_function_results(num.int_to_base, [
+ #check base 2
+ ak('0', 0, 2),
+ ak('11', 3, 2),
+ ak('1000', 8, 2),
+
+ #check 10 in various bases
+ ak('1010', 10, 2),
+ ak('101', 10, 3),
+ ak('10', 10, 10),
+
+ #check 16 in various bases
+ ak('16', 16, 10),
+ ak('f', 15, 16),
+ ak('10', 16, 16),
+ ak('23', 35, 16),
+
+ #check 35 in various bases
+ ak('35', 35, 10),
+ ak('z', 35, 36),
+ ak('10', 36, 36),
+ ak('zz', 1295, 36),
+
+ #check negatives
+ ak('-110', -(4+2), 2),
+ ak('-1f', -0x1F, 16),
+
+ #check pad kwd
+ ak('1010', 8+2, 2, pad=0),
+ ak('1010', 8+2, 2, pad=4),
+ ak('01010', 8+2, 2, pad=5),
+ ak('00001101', 8+4+1, 2, pad=8),
+ ak('00101101', 32+8+4+1, 2, pad=8),
+
+ #check pad + negative
+ ak('-00001101', -(8+4+1), 2, pad=8),
+ ])
+ self.assertRaises(ValueError, num.int_to_base, 0, -1)
+ self.assertRaises(ValueError, num.int_to_base, 0, 0)
+ self.assertRaises(ValueError, num.int_to_base, 0, 1)
+ self.assertRaises(ValueError, num.int_to_base, 0, 37)
+ self.assertRaises(ValueError, num.int_to_base, 0, 1000)
+ for r in xrange(1000):
+ b = random.randrange(2, 37)
+ n = random.randrange(-2**32, 2**32+1)
+ v = num.int_to_base(n, b)
+ self.assertEqual(int(v, b), n)
+
+ def test_limit(self):
+ self.check_function_results(num.limit, [
+ # result, value, lower, upper
+ ak(5, 5, 0, 10),
+ ak(0, -5, 0, 10),
+ ak(10, 15, 0, 10),
+
+ ak(0, -1.5, 0, 1),
+ ak(.5, .5, 0, 1),
+ ak(1, 1.5, 0, 1),
+
+ ak(5, -10, 5, 5),
+ ])
+ #check it won't let lower > upper
+ self.assertRaises(ValueError, num.limit, 0, 10, 5)
+
+ def test_avgsd(self):
+ self.assertEqual(num.avgsd([0, 1, 1, 2]), (1.0, 0.70710678118654757))
+
+ def test_digits(self):
+ self.check_function_results(num.digits, [
+ # result, value, [digits]
+ ak(2, 99),
+
+ ak(2, 99, 10),
+ ak(3, 100, 10),
+ ak(3, 7, 2),
+ ak(4, 8, 2),
+ ak(2, 255, 16),
+
+ ak(2, -99, 10),
+ ak(1, 0, 10),
+
+ ])
+
+## seqsum_cases = [
+## (
+## ak([179,50,74,51], [0,126,41,4], [93,99,109]),
+## [272, 275, 224, 55],
+## ),
+## (
+## ak(1, [179,50,74,51], 1, [0,126,41,4], 1, [93,99,109]),
+## [272, 275, 224, 55],
+## ),
+## (
+## ak((1, [179,50,74,51]), (1, [0,126,41,4]), (1, [93,99,109])),
+## [272, 275, 224, 55],
+## ),
+## ]
+## def test_seqsum(self):
+## for i,o in self.seqsum_cases:
+## r = seqsum(*i.args, **i.kwds)
+## self.assertEqual(r, o, "case %r: got %r, expected %r" % (i, r, o))
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_security_bcrypt.py b/bps/tests/test_security_bcrypt.py
new file mode 100755
index 0000000..414824d
--- /dev/null
+++ b/bps/tests/test_security_bcrypt.py
@@ -0,0 +1,210 @@
+"""bps.security._bcrypt unitests
+
+The BaseTest class was adapted from the jBcrypt unitests,
+released under the following license:
+
+ // Permission to use, copy, modify, and distribute this software for any
+ // purpose with or without fee is hereby granted, provided that the above
+ // copyright notice and this permission notice appear in all copies.
+ //
+ // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+"""
+#=========================================================
+#imports
+#=========================================================
+#site
+try:
+ import bcrypt as pybcrypt
+except ImportError:
+ pybcrypt = None
+#pkg
+from bps.tests.utils import TestCase, enable_suite
+from bps.security import _bcrypt as slow_bcrypt
+
+#=========================================================
+#test suite
+#=========================================================
+class UtilTest(TestCase):
+ "test slow_bcrypt's utilities"
+
+ def test_encode64(self):
+ encode = slow_bcrypt.encode_base64
+ self.check_function_results(encode, [
+ ('', ''),
+ ('..', '\x00'),
+ ('...', '\x00\x00'),
+ ('....', '\x00\x00\x00'),
+ ('9u', '\xff'),
+ ('996', '\xff\xff'),
+ ('9999', '\xff\xff\xff'),
+ ])
+
+ def test_decode64(self):
+ decode = slow_bcrypt.decode_base64
+ self.check_function_results(decode, [
+ ('', ''),
+ ('\x00', '..'),
+ ('\x00\x00', '...'),
+ ('\x00\x00\x00', '....'),
+ ('\xff', '9u', ),
+ ('\xff\xff','996'),
+ ('\xff\xff\xff','9999'),
+ ])
+
+class _BcryptTestBase(TestCase):
+ mod = None
+
+ test_vectors = [
+ [ "",
+ "$2a$06$DCq7YPn5Rq63x1Lad4cll.",
+ "$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s." ],
+ [ "",
+ "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.",
+ "$2a$08$HqWuK6/Ng6sg9gQzbLrgb.Tl.ZHfXLhvt/SgVyWhQqgqcZ7ZuUtye" ],
+ [ "",
+ "$2a$10$k1wbIrmNyFAPwPVPSVa/ze",
+ "$2a$10$k1wbIrmNyFAPwPVPSVa/zecw2BCEnBwVS2GbrmgzxFUOqW9dk4TCW" ],
+ [ "",
+ "$2a$12$k42ZFHFWqBp3vWli.nIn8u",
+ "$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO" ],
+ [ "a",
+ "$2a$06$m0CrhHm10qJ3lXRY.5zDGO",
+ "$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe" ],
+ [ "a",
+ "$2a$08$cfcvVd2aQ8CMvoMpP2EBfe",
+ "$2a$08$cfcvVd2aQ8CMvoMpP2EBfeodLEkkFJ9umNEfPD18.hUF62qqlC/V." ],
+ [ "a",
+ "$2a$10$k87L/MF28Q673VKh8/cPi.",
+ "$2a$10$k87L/MF28Q673VKh8/cPi.SUl7MU/rWuSiIDDFayrKk/1tBsSQu4u" ],
+ [ "a",
+ "$2a$12$8NJH3LsPrANStV6XtBakCe",
+ "$2a$12$8NJH3LsPrANStV6XtBakCez0cKHXVxmvxIlcz785vxAIZrihHZpeS" ],
+ [ "abc",
+ "$2a$06$If6bvum7DFjUnE9p2uDeDu",
+ "$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i" ],
+ [ "abc",
+ "$2a$08$Ro0CUfOqk6cXEKf3dyaM7O",
+ "$2a$08$Ro0CUfOqk6cXEKf3dyaM7OhSCvnwM9s4wIX9JeLapehKK5YdLxKcm" ],
+ [ "abc",
+ "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.",
+ "$2a$10$WvvTPHKwdBJ3uk0Z37EMR.hLA2W6N9AEBhEgrAOljy2Ae5MtaSIUi" ],
+ [ "abc",
+ "$2a$12$EXRkfkdmXn2gzds2SSitu.",
+ "$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q" ],
+ [ "abcdefghijklmnopqrstuvwxyz",
+ "$2a$06$.rCVZVOThsIa97pEDOxvGu",
+ "$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC" ],
+ [ "abcdefghijklmnopqrstuvwxyz",
+ "$2a$08$aTsUwsyowQuzRrDqFflhge",
+ "$2a$08$aTsUwsyowQuzRrDqFflhgekJ8d9/7Z3GV3UcgvzQW3J5zMyrTvlz." ],
+ [ "abcdefghijklmnopqrstuvwxyz",
+ "$2a$10$fVH8e28OQRj9tqiDXs1e1u",
+ "$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq" ],
+ [ "abcdefghijklmnopqrstuvwxyz",
+ "$2a$12$D4G5f18o7aMMfwasBL7Gpu",
+ "$2a$12$D4G5f18o7aMMfwasBL7GpuQWuP3pkrZrOAnqP.bmezbMng.QwJ/pG" ],
+ [ "~!@#$%^&*() ~!@#$%^&*()PNBFRD",
+ "$2a$06$fPIsBO8qRqkjj273rfaOI.",
+ "$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO" ],
+ [ "~!@#$%^&*() ~!@#$%^&*()PNBFRD",
+ "$2a$08$Eq2r4G/76Wv39MzSX262hu",
+ "$2a$08$Eq2r4G/76Wv39MzSX262huzPz612MZiYHVUJe/OcOql2jo4.9UxTW" ],
+ [ "~!@#$%^&*() ~!@#$%^&*()PNBFRD",
+ "$2a$10$LgfYWkbzEvQ4JakH7rOvHe",
+ "$2a$10$LgfYWkbzEvQ4JakH7rOvHe0y8pHKF9OaFgwUZ2q7W2FFZmZzJYlfS" ],
+ [ "~!@#$%^&*() ~!@#$%^&*()PNBFRD",
+ "$2a$12$WApznUOJfkEGSmYRfnkrPO",
+ "$2a$12$WApznUOJfkEGSmYRfnkrPOr466oFDCaj4b6HY3EXGvfxm43seyhgC" ],
+ ]
+
+ def test_00_hashpw(self):
+ "test hashpw() generates expected result for a given plaintext & salt"
+ hashpw = self.mod.hashpw
+ for plain, salt, expected in self.test_vectors:
+ hashed = hashpw(plain, salt)
+ self.assertEquals(hashed, expected)
+
+ def test_01_hashpw_success(self):
+ "test hashpw() verifies knowns correctly"
+ hashpw = self.mod.hashpw
+ for plain, _, expected in self.test_vectors:
+ hash = hashpw(plain, expected)
+ self.assertEquals(hash, expected)
+
+ def test_02_hashpw_failure(self):
+ "test hashpw() negatively verifies incorrect knowns"
+ hashpw = self.mod.hashpw
+ for plain, _, expected in self.test_vectors:
+ hash = hashpw(plain + 'number 15', expected)
+ self.assertNotEquals(hash, expected)
+
+ def test_03_gensalt(self):
+ "test new salts verifies correctly"
+ hashpw = self.mod.hashpw
+ gensalt = self.mod.gensalt
+ seen = set()
+ for plain, _, _ in self.test_vectors:
+ if plain in seen:
+ continue
+ seen.add(plain)
+
+ #create salt
+ salt = gensalt()
+
+ #hash it
+ hashed1 = hashpw(plain, salt)
+
+ #run check again
+ hashed2 = hashpw(plain, hashed1)
+
+ #hashes shouldn't have changed
+ self.assertEquals(hashed1, hashed2)
+
+ def test_04_gensalt(self):
+ "test gensalt options"
+ hashpw = self.mod.hashpw
+ gensalt = self.mod.gensalt
+ seen = set()
+ for plain, _, _ in self.test_vectors:
+ if plain in seen:
+ continue
+ seen.add(plain)
+
+ #create salt
+ salt = gensalt(4)
+
+ #hash it
+ hashed1 = hashpw(plain, salt)
+
+ #run check again
+ hashed2 = hashpw(plain, hashed1)
+
+ #hashes shouldn't have changed
+ self.assertEquals(hashed1, hashed2)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+if enable_suite("slow_bcrypt"):
+ class SlowBcryptTest(_BcryptTestBase):
+ "test slow bcrypt module"
+ mod = slow_bcrypt
+
+if pybcrypt and enable_suite("bcrypt"):
+ #if pybcrypt is installed, run our unitest on them too,
+ #just to ensure slow_bcrypt's interface is compatible.
+ class PyBcryptTest(_BCryptTestBase):
+ "make sure slow_bcrypt is compatible w/ pybcrypt"
+ mod = pybcrypt
+
+#=========================================================
+#eof
+#=========================================================
diff --git a/bps/tests/test_security_policy.py b/bps/tests/test_security_policy.py
new file mode 100644
index 0000000..ac726f7
--- /dev/null
+++ b/bps/tests/test_security_policy.py
@@ -0,0 +1,1710 @@
+"""bps.security.policy unitests"""
+
+#=========================================================
+#imports
+#=========================================================
+#core
+from __future__ import with_statement
+import warnings
+#site
+#pkg
+from bps import *
+from bps.types import stub
+from bps.meta import is_iter
+from bps.tests.utils import TestCase, catch_all_warnings
+from bps.security.policy import Policy, Role, Permission, PERM
+
+#=========================================================
+#helpers
+#=========================================================
+def policy_01x(**kwds):
+ "default roleset used by many tests"
+ #NOTE: this is a non-sensical inheritance hierarchy,
+ #which mainly exists to provide a variety of shapes for testing purposes.
+ # admin -> (user, pirate) -> base
+ policy = Policy(**kwds)
+ b = policy.create_role("base", grantable=False)
+ u = policy.create_role("user", "base")
+ p = policy.create_role("pirate", "base")
+ a = policy.create_role("admin", 'user,pirate')
+ return policy,b,u,p,a
+
+def policy_01(**kwds):
+ return policy_01x(**kwds)[0]
+
+def policy_02x():
+ "default roleset+permset used by many tests"
+ #NOTE: this is a non-sensical set of permissions,
+ #which mainly exists to provide a perms for testing purposes
+ policy = policy_01()
+ a = policy.permit("admin", "perm-a")
+ b = policy.permit("base", "perm-b")
+ u = policy.permit("user", "perm-u")
+ p = policy.permit("pirate", "perm-p")
+ policy.freeze()
+ #NOTE: order should be order of definition
+ return policy,a,b,u,p
+
+def policy_02():
+ return policy_02x()[0]
+
+def policy_03x():
+ "example roleset+permset"
+ #NOTE: this role & permset should make sense,
+ # and are a stripped down version of the policy for a web application.
+
+ policy = Policy()
+
+ #
+ #create a nice user account object
+ #
+ class User(BaseClass):
+ policy = None
+
+ def __init__(self, name=None, roles=None):
+ self.name = name or "NoName"
+ self.roles = roles or ()
+
+ def has_role(self, role):
+ #NOTE: by calling this instead of reading .roles, we get benefit of inherited role system
+ return self.policy.user_has_role(self,role)
+
+ def has_permission(self, *a, **k):
+ return self.policy.user_has_permission(self, *a, **k)
+ User.policy = policy
+
+ #
+ #create roles
+ #
+ policy.create_role("person", desc="base role for all users")
+ policy.create_role("client", inherits="person", desc="role for end users of system")
+ policy.create_role("employee", inherits="person", desc="role for people running system")
+ policy.create_role("admin", inherits="employee", desc="system administrator")
+
+ #
+ #create some helpful guard funcs
+ #
+ def is_own_account(user, item=None):
+ "only permit action if it's on user's own account"
+ if item:
+ return user == item
+ return True
+
+ def is_client_account(user, item=None):
+ "only permit action if it's on a client user account"
+ if item:
+ return item.has_role("client")
+ return True
+
+ #
+ #grant actions to roles
+ #
+
+ #all users can edit own account, and log in
+ policy.permit_list(["person"],[
+ dict(action="sign-in", klass=False),
+ dict(action="view", klass="user", guard=is_own_account),
+ dict(action="update", klass="user", guard=is_own_account),
+ ])
+
+ #all clients can manage their journal entries
+ #NOTE: in real-world, a guard would be used to
+ # require journal was owned by user:
+ ##def is_own_journal(user, item=None):
+ ## if item:
+ ## return item.owner == user
+ ## return True
+ policy.permit_list(["client"],[
+ dict(action="list", klass="journal"),
+ dict(action="create", klass="journal"),
+ dict(action="view", klass="journal"),
+ dict(action="update", klass="journal", attrs=("owner",), deny=True),
+ dict(action="update", klass="journal"),
+ dict(action="retire", klass="journal"),
+ ])
+
+ #all employees can manage client accounts
+ policy.permit_list(["employee"],[
+ dict(action="list", klass="user", guard=is_client_account),
+ dict(action="create", klass="user", guard=is_client_account),
+ dict(action="view", klass="user", guard=is_client_account),
+ dict(action="update", klass="user", guard=is_client_account),
+ dict(action="retire", klass="user", guard=is_client_account),
+ ])
+
+ #and admins can perform all std actions on any class
+ policy.permit_list(["admin"],[
+ dict(action="list", klass=True),
+ dict(action="create", klass=True),
+ dict(action="view", klass=True),
+ dict(action="update", klass=True),
+ dict(action="retire", klass=True),
+ dict(action="delete", klass=True), #and only admins can delete things forever
+ ])
+
+ #
+ #freeze policy & create some users
+ #
+ policy.freeze()
+ admin = User(roles=("admin",))
+ employee = User(roles=("employee",))
+ client = User(roles=("client",))
+ return policy, admin, employee, client, User
+
+#TODO: remove this stub
+def check_rtype(self, func, deftype, elems, ordered=False):
+ "run test for func with rtype return"
+ return self.check_function_rtype(func, retval=elems, rtype=deftype, ordered=ordered)
+
+#=========================================================
+#support classes
+#=========================================================
+class RoleClassTest(TestCase):
+ "test role class itself"
+
+ def test_const_basic(self):
+ "test basic role constructor"
+ r = Role("admin")
+ self.assertEquals(r.name, "admin")
+ self.assertEquals(r.title, "Admin")
+ self.assertIs(r.desc, None)
+ self.assertEquals(r.inherits, frozenset())
+ self.assertEquals(r.grantable, True)
+
+ def test_const_invalid(self):
+ "test invalid role constructors"
+ self.assertRaises(TypeError, Role)
+ self.assertRaises(TypeError, Role, "admin", xxx=123)
+
+ def test_const_full(self):
+ "test common role constructor"
+ r = Role("admin", title="captain", inherits=["user", "pirate", "user"],
+ desc="descy", grantable=False)
+ self.assertEquals(r.name, "admin")
+ self.assertEquals(r.title, "captain")
+ self.assertEquals(r.desc, "descy")
+ self.assertEquals(r.grantable, False)
+ self.assertEquals(r.inherits, frozenset(["user", "pirate"]))
+
+ def test_eq(self):
+ "test role equal to itself"
+
+ r1 = Role("admin")
+ self.assertEquals(r1,r1)
+
+ r2 = Role("other")
+ self.assertNotEquals(r1,r2)
+
+ #NOTE: module doesn't current assert either way on this,
+ # an eq operator may be defined in the future.
+ # this test is just to ensure current behavior is reliable.
+ r3 = Role("admin")
+ self.assertNotEquals(r1,r3)
+
+class PermissionClassTest(TestCase):
+ "test permission class itself"
+
+ #=========================================================
+ #constructors
+ #=========================================================
+ def test_const_basic(self):
+ "test basic perm constructor"
+ p = Permission("sign-in")
+ self.assertEquals(p.action, "sign-in")
+ self.assertEquals(p.desc, None)
+ self.assertEquals(p.klass, None)
+ self.assertEquals(p.attrs, None)
+ self.assertEquals(p.guard, None)
+ self.assertEquals(p.deny, False)
+ self.assertEquals(p.priority, 0)
+
+ def test_const_invalid(self):
+ "test invalid perm constructors"
+
+ #make sure action is required
+ self.assertRaises(TypeError, Permission)
+ self.assertRaises(TypeError, Permission, klass=False)
+
+ #make sure unknowns raise err
+ self.assertRaises(TypeError, Permission, "sign-in", xxx=123)
+
+ def test_const_full(self):
+ "test full perm constructor"
+ def g(user):
+ return True
+ p = Permission(
+ action="update",
+ klass="user",
+ attrs=("bob","sue"),
+ guard=g,
+ deny=True,
+ desc="desc",
+ priority=-100,
+ )
+ self.assertEquals(p.action, "update")
+ self.assertEquals(p.desc, "desc")
+ self.assertEquals(p.klass, "user")
+ self.assertEquals(p.attrs, frozenset(["bob", "sue"]))
+ self.assertEquals(p.guard, g)
+ self.assertEquals(p.guard_kwds, frozenset(["user"]))
+ self.assertEquals(p.deny, True)
+ self.assertEquals(p.priority, -100)
+
+ #=========================================================
+ #check() basic usage
+ #=========================================================
+ def test_check_params(self):
+ "test check() params"
+ u = stub()
+ p = Permission("update", "user", attrs=("bob", None))
+
+ self.assertEquals(p.check(u,"update","user",u, attr=None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update","journal",u, attr=None), PERM.PENDING)
+
+ p = Permission("sign-in", False)
+ self.assertEquals(p.check(u,"sign-in"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in",None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in","user"), PERM.PENDING)
+
+ def test_check_invalid_values(self):
+ "test passing invalid values to check"
+ u = stub()
+ p = Permission("update")
+
+ #haven't decided the policy for these border cases,
+ #so they're currently forbidden..
+ self.assertRaises(ValueError, p.check, u, "update", attr="")
+ self.assertRaises(ValueError, p.check, u, "update", attr=False)
+ self.assertRaises(ValueError, p.check, u, "update", klass="")
+ self.assertRaises(ValueError, p.check, u, "update", klass=False)
+
+ #=========================================================
+ #could_allow() basic usage
+ #=========================================================
+ def test_could_allow_params(self):
+ #simple check against action + klass
+ p = Permission("update", "user", attrs=("bob", None))
+ self.assert_(p.could_allow("update","user", attr=None))
+ self.assert_(not p.could_allow("update","journal", attr=None))
+
+ #simple check against action - klass
+ p = Permission("sign-in", False)
+ self.assert_(p.could_allow("sign-in"))
+ self.assert_(p.could_allow("sign-in",None))
+ self.assert_(not p.could_allow("sign-in","user"))
+
+ def test_could_allow_guard(self):
+ #simple check that guard is ignored
+ p = Permission("update", "user", guard=lambda user: False)
+ self.assert_(p.could_allow("update","user"))
+ self.assert_(not p.could_allow("update","journal"))
+
+ #=========================================================
+ #action matching
+ #=========================================================
+ def test_action(self):
+ "test generic action specifier"
+ u = stub()
+ p = Permission("update")
+ self.assertEquals(p.check(u, None), PERM.PENDING)
+ self.assertEquals(p.check(u, "update"), PERM.ALLOW)
+ self.assertEquals(p.check(u, "zzz"), PERM.PENDING)
+
+ #=========================================================
+ #klass matching
+ #=========================================================
+ #NOTE: klass="" and klass=False shouldn't be passed into check normally,
+ # only pass in a non-empty string or None.
+
+ def test_klass_false(self):
+ "test klass=False matches only if klass missing"
+ u = stub()
+ p = Permission("sign-in", klass=False)
+ self.assertEquals(p.klass, False)
+
+ self.assertEquals(p.check(u,"sign-in"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in",None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in","user"), PERM.PENDING)
+ self.assertEquals(p.check(u,"sign-in","journal"), PERM.PENDING)
+
+ def test_klass_none(self):
+ "test klass=None matches anything"
+ u = stub()
+
+ p1 = Permission("sign-in")
+ self.assertEquals(p1.klass, None)
+
+ p = Permission("sign-in", klass=None)
+ self.assertEquals(p.klass, None)
+
+ self.assertEquals(p.check(u,"sign-in"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in",None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in","user"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in","journal"), PERM.ALLOW)
+
+ def test_klass_true(self):
+ "test klass=True matches anything except missing klass"
+ u = stub()
+
+ p = Permission("sign-in", klass=True)
+ self.assertEquals(p.klass, True)
+
+ self.assertEquals(p.check(u,"sign-in"), PERM.PENDING)
+ self.assertEquals(p.check(u,"sign-in",None), PERM.PENDING)
+ self.assertEquals(p.check(u,"sign-in","user"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in","journal"), PERM.ALLOW)
+
+ def test_klass_exact(self):
+ "test klass=<str> matches only that string"
+ u = stub()
+
+ p = Permission("sign-in", klass="user")
+ self.assertEquals(p.klass, "user")
+
+ self.assertEquals(p.check(u,"sign-in"), PERM.PENDING)
+ self.assertEquals(p.check(u,"sign-in",None), PERM.PENDING)
+ self.assertEquals(p.check(u,"sign-in","user"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"sign-in","journal"), PERM.PENDING)
+
+ #=========================================================
+ #attr matching
+ #=========================================================
+ #NOTE: no policy is current set for attr="" and attr=False,
+ # these shouldn't be used.
+
+ def test_attrs_none(self):
+ "test attrs=None matches any/no attrs"
+ u = stub()
+
+ p1 = Permission("update")
+ self.assertEquals(p1.attrs, None)
+
+ p = Permission("update", attrs=None)
+ self.assertEquals(p.attrs, None)
+
+ self.assertEquals(p.check(u,"update"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr=None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr="xxx"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr="zzz"), PERM.ALLOW)
+
+ def test_attrs_empty(self):
+ "test attrs=(), attrs=(None), and attrs=False matches no attr"
+ u = stub()
+
+ p1 = Permission("update", attrs=False)
+ self.assertEquals(p1.attrs, frozenset([None]))
+
+ p1 = Permission("update", attrs=(None,))
+ self.assertEquals(p1.attrs, frozenset([None]))
+
+ p = Permission("update", attrs=())
+ self.assertEquals(p.attrs, frozenset([None]))
+
+ self.assertEquals(p.check(u,"update"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr=None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr="xxx"), PERM.PENDING)
+ self.assertEquals(p.check(u,"update", attr="zzz"), PERM.PENDING)
+
+ def test_attrs_explicit(self):
+ "test attrs=('a','b') matches only those attrs"
+ u = stub()
+
+ p = Permission("update", attrs=("xxx", "yyy","xxx"))
+ self.assertEquals(p.attrs, frozenset(["xxx", "yyy"]))
+
+ self.assertEquals(p.check(u,"update"), PERM.PENDING)
+ self.assertEquals(p.check(u,"update", attr=None), PERM.PENDING)
+ self.assertEquals(p.check(u,"update", attr="xxx"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr="zzz"), PERM.PENDING)
+
+ def test_attrs_explicit2(self):
+ "test attrs=('a','b',None) matches only those or no attrs"
+ u = stub()
+
+ p = Permission("update", attrs=("xxx", "yyy",None))
+ self.assertEquals(p.attrs, frozenset(["xxx", "yyy",None]))
+
+ self.assertEquals(p.check(u,"update"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr=None), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr="xxx"), PERM.ALLOW)
+ self.assertEquals(p.check(u,"update", attr="zzz"), PERM.PENDING)
+
+ #=========================================================
+ #guard matching
+ #=========================================================
+ result = None #used as temp location for some guards in these tests
+
+ def test_guard_retval(self):
+ "test guard w/o args, using diff retvals"
+
+ #test True return value
+ def g():
+ self.result = True
+ return True
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update"), PERM.ALLOW)
+ self.assert_(self.result)
+
+ #test False return value
+ def g():
+ self.result = True
+ return False
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update"), PERM.PENDING)
+ self.assert_(self.result)
+
+ #test None return value
+ def g():
+ self.result = True
+ return None
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update"), PERM.PENDING)
+ self.assert_(self.result)
+
+ #test false-as-bool return value
+ def g():
+ self.result = True
+ return ""
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update"), PERM.PENDING)
+ self.assert_(self.result)
+
+ #test true-as-bool return value
+ def g():
+ self.result = True
+ return "xxx"
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update"), PERM.ALLOW)
+ self.assert_(self.result)
+
+ def test_guard_after_patterns(self):
+ "test guard called after patterns"
+ def g():
+ self.result = True
+ return True
+ u = stub()
+
+ #check action
+ self.result = False
+ p = Permission("update", guard=g)
+ self.assertEquals(p.check(u,"list"),PERM.PENDING)
+ self.assert_(not self.result)
+ self.assertEquals(p.check(u,"update"),PERM.ALLOW)
+ self.assert_(self.result)
+
+ #check klass
+ self.result = False
+ p = Permission("update", "user", guard=g)
+ self.assertEquals(p.check(u,"update", "journal"),PERM.PENDING)
+ self.assert_(not self.result)
+ self.assertEquals(p.check(u,"update", "user"),PERM.ALLOW)
+ self.assert_(self.result)
+
+ #check attrs
+ self.result = False
+ p = Permission("update", attrs=["x"], guard=g)
+ self.assertEquals(p.check(u,"update", attr="y"),PERM.PENDING)
+ self.assert_(not self.result)
+ self.assertEquals(p.check(u,"update", attr="x"),PERM.ALLOW)
+ self.assert_(self.result)
+
+ def test_guard_wildcard(self):
+ "test guard w/ all kwds defaulting"
+ def g(**kwds):
+ self.result = kwds
+ return True
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update"), PERM.ALLOW)
+ self.assertEquals(self.result,dict(
+ user=u,
+ action="update",
+ klass=None,
+ attr=None,
+ item=None,
+ scope=None,
+ perm=p,
+ ))
+
+ def test_guard_full(self):
+ "test guard w/ all kwds filled in"
+ def g(**kwds):
+ self.result = kwds
+ return True
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update","user",u,attr="xxx",scope=self), PERM.ALLOW)
+ self.assertEquals(self.result,dict(
+ user=u,
+ action="update",
+ klass="user",
+ attr="xxx",
+ item=u,
+ scope=self,
+ perm=p,
+ ))
+
+ def test_guard_some(self):
+ "test guard w/ all kwds filled in but few used"
+ def g(user, action=None, item=None):
+ self.result = dict(user=user, action=action, item=item)
+ return True
+ u = stub()
+ p = Permission("update", guard=g)
+ self.result = False
+ self.assertEquals(p.check(u,"update","user",u,attr="xxx",scope=self), PERM.ALLOW)
+ self.assertEquals(self.result,dict(
+ user=u,
+ action="update",
+ item=u,
+ ))
+
+ #=========================================================
+ #test eq
+ #=========================================================
+ def test_eq(self):
+ "test permission equality operator works"
+
+ #test match considers action, klass, attrs, guard, deny
+ for k,a,b in (
+ ("action", "update", "delete"),
+ ("klass", None, False),
+ ("klass", "user", False),
+ ("klass", "user", "journal"),
+ ("attrs", ("xxx",), ("yyy",)),
+ ("attrs", (), ("yyy",)),
+ ("guard", lambda : True, lambda : True),
+ ("deny", True, False),
+ ):
+ ad = {k:a}
+ bd = {k:b}
+ if k != "action":
+ ad["action"] = bd["action"] = "update"
+ p1 = Permission(**ad)
+ p2 = Permission(**ad)
+ p3 = Permission(**bd)
+ self.assertEquals(p1,p2)
+ self.assertEquals(p1,p1)
+ self.assertNotEquals(p1,p3)
+ self.assertNotEquals(p2,p3)
+
+ #test match discards non-perms
+ p = Permission("update")
+ self.assertNotEquals(p, None)
+ self.assertNotEquals(p, "xxx")
+ self.assertNotEquals(p, Role("admin"))
+
+ #test match ignores desc
+ p1 = Permission("update", desc="xxx")
+ p2 = Permission("update", desc="yyy")
+ self.assertEquals(p1,p1)
+ self.assertEquals(p1,p2)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#
+#=========================================================
+class RoleManagementTest(TestCase):
+ "test policy's role management functions"
+
+ #=========================================================
+ #test create_role(name, *a, **k) -> role_obj
+ #=========================================================
+ def test_create_role_simple(self):
+ "test creating a role works properly"
+ policy = Policy()
+
+ r = policy.create_role("admin")
+ self.assertIsInstance(r, Role)
+ self.assertEquals(r.name, "admin")
+ self.assertEquals(r.title, "Admin")
+ self.assertEquals(r.inherits, frozenset())
+
+ self.assertElementsEqual(policy.get_role_objs(), [r])
+
+ def test_create_role_inherits(self):
+ "test role inheritance works properly"
+ policy = Policy()
+
+ u = policy.create_role("pirate")
+ p = policy.create_role("user")
+
+ r = policy.create_role("admin", inherits=["user", "pirate", "user"])
+ self.assertEquals(r.name, "admin")
+ self.assertEquals(r.inherits, frozenset(["user", "pirate"]))
+
+ self.assertElementsEqual(policy.get_role_objs(), [u,p,r])
+
+ def test_create_role_inherits_undefined(self):
+ "test role inheritance requires existing parents"
+ policy = Policy()
+
+ #shouldn't be able to create role w/ out parents
+ self.assertRaises(ValueError, policy.create_role, "admin", ["user", "pirate"])
+ #KeyError: undefined roles: user, pirate
+
+ u = policy.create_role("user")
+
+ #without _all_ parents
+ self.assertRaises(ValueError, policy.create_role, "admin", ["user", "pirate"])
+ #KeyError: undefined roles: pirate
+
+ self.assertElementsEqual(policy.get_role_objs(), [u])
+
+ def test_create_role_inherit_self(self):
+ "test role can't inherit from self"
+ policy = Policy()
+
+ self.assertRaises(ValueError, policy.create_role, "user", ['user'])
+ #ValueError: role can't inherit from self
+
+ def test_create_role_frozen(self):
+ "test role can't be created after frozen"
+ policy = Policy()
+ policy.freeze()
+
+ self.assertRaises(AssertionError, policy.create_role, "user")
+ #AssertionError: policy frozen
+
+ def test_create_role_subclassed(self):
+ "test create_role() honors Policy.Role"
+ #make sure orig Role won't take "xxx"
+ self.assertRaises(TypeError, Policy.Role, "test", xxx=23)
+
+ #create role subclass which accepts "xxx"
+ class MyRole(Policy.Role):
+ def __init__(self, *a, **k):
+ self.xxx = k.pop("xxx",None)
+ self.__super.__init__(*a,**k)
+
+ #create policy class which uses MyRole
+ class MyPolicy(Policy):
+ Role = MyRole
+
+ #try creating role, make sure MyRole was used
+ policy = MyPolicy()
+ r = policy.create_role("test", xxx=23)
+ self.assertIsInstance(r,MyRole)
+ self.assertEqual(r.xxx, 23)
+
+ #=========================================================
+ #test get_role_obj(name, default=Undef) -> role_obj|default/Error
+ #=========================================================
+ def test_get_role_obj(self):
+ policy = Policy()
+
+ #check raises error by default
+ self.assertRaises(KeyError, policy.get_role_obj, "user")
+
+ #test default works
+ self.assertIs(policy.get_role_obj("user",None), None)
+
+ #test returns correct result
+ u = policy.create_role("user")
+ self.assertIs(policy.get_role_obj("user"), u)
+
+ #=========================================================
+ #test get_role_objs(roles=None, grantable=None, rtype=set)-> role_objs
+ #=========================================================
+ def test_gro_plain(self):
+ "test get_role_objs() w/o args"
+ policy,b,u,p,a = policy_01x()
+ result = policy.get_role_objs()
+ self.assertElementsEqual(result, [b,u,p,a])
+
+ def test_gro_roles(self):
+ "test get_role_objs() with role name filter"
+ policy,b,u,p,a = policy_01x()
+
+ #check normal
+ result = policy.get_role_objs(['admin','pirate'])
+ self.assertElementsEqual(result,[a,p])
+
+ #check w/ unknown
+ self.assertRaises(KeyError, policy.get_role_objs, ['admin', 'person'])
+
+ #check ordering matches input list
+ result = policy.get_role_objs(["admin","base","user","pirate"],
+ rtype=list)
+ self.assertEquals(result,[a,b,u,p])
+
+ #check ordering matches input list (just in case 1st was accident)
+ result = policy.get_role_objs(["base","user","admin","pirate"],
+ rtype=list)
+ self.assertEquals(result,[b,u,a,p])
+
+ def test_gro_grantable(self):
+ "test get_role_objs() with grantable filter"
+ policy,b,u,p,a = policy_01x()
+ self.assertElementsEqual(policy.get_role_objs(grantable=None),[b,u,p,a])
+ self.assertElementsEqual(policy.get_role_objs(grantable=True),[u,p,a])
+ self.assertElementsEqual(policy.get_role_objs(grantable=False),[b])
+
+ def test_gro_grantable_roles(self):
+ "test get_role_objs() with grantable & role name filters"
+ policy,b,u,p,a = policy_01x()
+ self.assert_sets_equal(
+ policy.get_role_objs(['admin','base'], grantable=True),
+ [a])
+ self.assert_sets_equal(
+ policy.get_role_objs(['admin','base'], grantable=False),
+ [b])
+
+ def test_gro_rtype(self):
+ "test get_role_objs() rtype option"
+ policy,b,u,p,a = policy_01x()
+ elems = [b,u,p,a]
+ check_rtype(self, policy.get_role_objs, set, elems)
+
+ func = partial(policy.get_role_objs, ["base","user","pirate","admin"])
+ check_rtype(self, func, set, elems, ordered=True)
+
+ #=========================================================
+ #test get_roles(grantable=None, rtype=set)
+ #=========================================================
+ def test_gr_plain(self):
+ "test get_roles() w/o args"
+ policy = policy_01()
+ result = policy.get_roles()
+ self.assert_sets_equal(result, ["base", "admin", "user", "pirate"])
+
+ def test_gr_grantable(self):
+ "test get_roles() with grantable filter"
+ policy = policy_01()
+ self.assertElementsEqual(
+ policy.get_roles(grantable=None),
+ ["base","admin","user","pirate"])
+ self.assertElementsEqual(
+ policy.get_roles(grantable=True),
+ ["admin","user","pirate"])
+ self.assertElementsEqual(
+ policy.get_roles(grantable=False),
+ ["base"])
+
+ def test_gr_rtype(self):
+ "test get_roles() rtype option"
+ policy = policy_01()
+ elems = ["base", "user", "pirate", "admin"]
+ out = policy.get_roles(rtype=list)
+ self.assert_sets_equal(out,elems)
+ check_rtype(self, policy.get_roles, set, out, ordered=True)
+
+ #=========================================================
+ #test has_role(role, grantable=None)
+ #=========================================================
+ def test_has_role(self):
+ "test has_role()"
+ policy = policy_01()
+
+ #test grantable role
+ self.assert_(policy.has_role("admin"))
+ self.assert_(policy.has_role("admin", grantable=True))
+ self.assert_(not policy.has_role("admin", grantable=False))
+
+ #test ungrantable role
+ self.assert_(policy.has_role("base"))
+ self.assert_(not policy.has_role("base", grantable=True))
+ self.assert_(policy.has_role("base", grantable=False))
+
+ #test unknown role
+ self.assert_(not policy.has_role("fooey"))
+ self.assert_(not policy.has_role("fooey", grantable=True))
+ self.assert_(not policy.has_role("fooey", grantable=False))
+
+ def test_has_role_inherits(self):
+ "test has_role() inherits kwd"
+ policy = policy_01()
+
+ self.assertEqual(policy.has_role("admin", inherits="base"), True)
+ self.assertEqual(policy.has_role("admin", inherits="pirate"), True)
+ self.assertEqual(policy.has_role("admin", inherits=["user", "base"]), True)
+
+ self.assertEqual(policy.has_role("user", inherits="base"), True)
+ self.assertEqual(policy.has_role("user", inherits="pirate"), False)
+ self.assertEqual(policy.has_role("user", inherits=["admin", "base"]), True)
+
+ #make sure can't inherit from self
+ self.assertEqual(policy.has_role("user", inherits="user"), False)
+
+ #or from child
+ self.assertEqual(policy.has_role("user", inherits="admin"), False)
+
+ #=========================================================
+ #test get_user_roles(user, inherited=True, rtype=set)
+ #=========================================================
+ def test_gur_simple(self):
+ "test basic get_user_roles behavior"
+ policy = policy_01()
+ user = stub(roles=("user",))
+
+ self.assert_sets_equal(
+ policy.get_user_roles(user),
+ ['user','base'],
+ )
+
+ self.assert_sets_equal(
+ policy.get_user_roles(user, inherited=False),
+ ['user',],
+ )
+
+ def test_gur_rtype(self):
+ "test get_user_roles() rtype"
+ policy = policy_01()
+ user = stub(roles=("user",))
+ check_rtype(self, partial(policy.get_user_roles,user),
+ set,["user","base"])
+
+ def test_gur_ungrantable(self):
+ "test get_user_roles() prevents ungrantable roles"
+ policy = policy_01()
+ user = stub(roles=("user","base"))
+ self.assertRaises(ValueError, policy.get_user_roles, user)
+ self.assertRaises(ValueError, policy.get_user_roles, user, inherited=False)
+
+ #=========================================================
+ #test user_has_role(user,role,inherited=True)
+ #=========================================================
+ def test_uhr_simple(self):
+ "test user_has_role() basic behavior"
+ policy = policy_01()
+
+ user = stub(roles=("user",))
+ def func(role):
+ return policy.user_has_role(user,role)
+ self.assertEqual(func("base"),True)
+ self.assertEqual(func("user"),True)
+ self.assertEqual(func("pirate"),False)
+ self.assertEqual(func("admin"),False)
+
+ user2 = stub(roles=("admin",))
+ def func(role):
+ return policy.user_has_role(user2,role)
+ self.assertEqual(func("base"),True)
+ self.assertEqual(func("user"),True)
+ self.assertEqual(func("pirate"),True)
+ self.assertEqual(func("admin"),True)
+
+ def test_uhr_inherit(self):
+ "test user_has_role() inherited=False flag"
+ policy = policy_01()
+
+ user = stub(roles=("user",))
+ def func(role):
+ return policy.user_has_role(user,role,inherited=False)
+ self.assertEqual(func("base"),False)
+ self.assertEqual(func("user"),True)
+ self.assertEqual(func("pirate"),False)
+ self.assertEqual(func("admin"),False)
+
+ user2 = stub(roles=("admin",))
+ def func(role):
+ return policy.user_has_role(user2,role,inherited=False)
+ self.assertEqual(func("base"),False)
+ self.assertEqual(func("user"),False)
+ self.assertEqual(func("pirate"),False)
+ self.assertEqual(func("admin"),True)
+
+ #=========================================================
+ #test user_has_any_role(user,roles,inherited=True)
+ #=========================================================
+ def test_uhar_simple(self):
+ "test user_has_any_role() basic behavior"
+ policy = policy_01()
+
+ user = stub(roles=("user",))
+ def func(*roles):
+ return policy.user_has_any_role(user,roles)
+ self.assertEqual(func("base","pirate"),True)
+ self.assertEqual(func("user","pirate"),True)
+ self.assertEqual(func("pirate","pirate"),False)
+ self.assertEqual(func("admin","pirate"),False)
+
+ user2 = stub(roles=("user","pirate"))
+ def func(*roles):
+ return policy.user_has_any_role(user2,roles)
+ self.assertEqual(func("base"),True)
+ self.assertEqual(func("user","pirate"),True)
+ self.assertEqual(func("pirate"),True)
+ self.assertEqual(func("admin","pirate"),True)
+
+ def test_uhar_inherited(self):
+ "test user_has_any_role() inherited=False"
+ policy = policy_01()
+
+ user = stub(roles=("user",))
+ def func(*roles):
+ return policy.user_has_any_role(user,roles, inherited=False)
+ self.assertEqual(func("base","pirate"),False)
+ self.assertEqual(func("user","pirate"),True)
+ self.assertEqual(func("pirate","pirate"),False)
+ self.assertEqual(func("admin","pirate"),False)
+
+ user2 = stub(roles=("user","pirate"))
+ def func(*roles):
+ return policy.user_has_any_role(user2,roles, inherited=False)
+ self.assertEqual(func("base"),False)
+ self.assertEqual(func("user","pirate"),True)
+ self.assertEqual(func("pirate"),True)
+ self.assertEqual(func("admin","pirate"),True)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+class RoleHelperTest(TestCase):
+ "test policy's role helper functions"
+ #=========================================================
+ #test expand_roles(roles,rtype=set)
+ #=========================================================
+ def test_expand_roles(self):
+ policy = policy_01()
+
+ #expand from 1
+ self.assertElementsEqual(policy.expand_roles(["admin"]),
+ ["admin", "user", "pirate", "base"])
+
+ #expand from 1 + dup
+ self.assertElementsEqual(policy.expand_roles(["admin","user"]),
+ ["admin", "user", "pirate", "base"])
+
+ #expand from 1 lower
+ self.assertElementsEqual(policy.expand_roles(["user"]),
+ ["user", "base"])
+
+ #expand from 1 lowest
+ self.assertElementsEqual(policy.expand_roles(["base"]),
+ ["base"])
+
+ #expand from none
+ self.assertElementsEqual(policy.expand_roles([]),
+ [])
+
+ def test_expand_roles_rtype(self):
+ policy = policy_01()
+ elems = ["admin", "pirate", "user", "base"]
+ check_rtype(self, partial(policy.expand_roles,["admin", "user"]), set, elems)
+
+ #=========================================================
+ #test collapse_roles(roles,rtype=set)
+ #=========================================================
+ def test_collapse_roles(self):
+ #TODO: test rtype option
+ policy = policy_01()
+
+ #collapse to top
+ self.assertElementsEqual(policy.collapse_roles(["admin", "user", "pirate", "base"]),
+ ["admin"])
+
+ #collapse to medium
+ self.assertElementsEqual(policy.collapse_roles(["user", "pirate", "base"]),
+ ["pirate","user"])
+
+ #collapse to same
+ self.assertElementsEqual(policy.collapse_roles(["user","pirate"]),
+ ["pirate", "user"])
+
+ #collapse none
+ self.assertElementsEqual(policy.collapse_roles([]),
+ [])
+
+ def test_collapse_roles_rtype(self):
+ policy = policy_01()
+ elems = ["pirate", "user"]
+ check_rtype(self, partial(policy.collapse_roles,["pirate","base", "user"]), set, elems)
+
+ #=========================================================
+ #test ascend_roles(roles,rtype=set)
+ #=========================================================
+ def test_ascend_roles(self):
+ policy = policy_01()
+
+ #ascend top
+ self.assertElementsEqual(
+ policy.ascend_roles(["admin"]),
+ [])
+
+ #ascend top and medium
+ self.assertElementsEqual(
+ policy.ascend_roles(["admin", "pirate"]),
+ ["admin"])
+
+ #ascend medium & dup
+ self.assertElementsEqual(
+ policy.ascend_roles(["user", "pirate","base"]),
+ ["admin","user", "pirate"])
+
+ #ascend medium
+ self.assertElementsEqual(
+ policy.ascend_roles(["user", "pirate"]),
+ ["admin"])
+
+ #ascend lowest
+ self.assertElementsEqual(
+ policy.ascend_roles(["base"]),
+ ["admin", "user", "pirate"])
+
+ #ascend none
+ self.assertElementsEqual(
+ policy.ascend_roles([]),
+ [])
+
+ def test_ascend_roles_keep(self):
+ policy = policy_01()
+
+ #ascend top
+ self.assertElementsEqual(
+ policy.ascend_roles(["admin"],keep=True),
+ ["admin"])
+
+ #ascend top and medium
+ self.assertElementsEqual(
+ policy.ascend_roles(["admin", "pirate"],keep=True),
+ ["admin","pirate"])
+
+ #ascend medium & dup
+ self.assertElementsEqual(
+ policy.ascend_roles(["user", "pirate","base"],keep=True),
+ ["admin","user", "pirate","base"])
+
+ #ascend medium
+ self.assertElementsEqual(
+ policy.ascend_roles(["user", "pirate"],keep=True),
+ ["admin","user", "pirate"])
+
+ #ascend lowest
+ self.assertElementsEqual(
+ policy.ascend_roles(["base"],keep=True),
+ ["admin", "user", "pirate","base"])
+
+ #ascend none
+ self.assertElementsEqual(
+ policy.ascend_roles([],keep=True),
+ [])
+
+ def test_ascend_roles_rtype(self):
+ policy = policy_01()
+ elems = [ "admin" ]
+ check_rtype(self, partial(policy.ascend_roles, ["pirate"]), set, elems)
+
+ #=========================================================
+ #test descend_roles(roles,rtype=set)
+ #=========================================================
+ def test_descend_roles(self):
+ policy = policy_01()
+
+ #descend top
+ self.assertElementsEqual(
+ policy.descend_roles(["admin"]),
+ ["user", "pirate", "base"])
+
+ #descend top and medium
+ self.assertElementsEqual(
+ policy.descend_roles(["admin", "pirate"]),
+ ["user", "pirate", "base"])
+
+ #descend medium & dup
+ self.assertElementsEqual(
+ policy.descend_roles(["user", "pirate","base"]),
+ ["base"])
+
+ #descend medium
+ self.assertElementsEqual(
+ policy.descend_roles(["user", "pirate"]),
+ ["base"])
+
+ #descend lowest
+ self.assertElementsEqual(
+ policy.descend_roles(["base"]),
+ [])
+
+ #descend none
+ self.assertElementsEqual(
+ policy.descend_roles([]),
+ [])
+
+ def test_descend_roles_keep(self):
+ policy = policy_01()
+
+ #descend top
+ self.assertElementsEqual(
+ policy.descend_roles(["admin"], keep=True),
+ ["user", "pirate", "base","admin"])
+
+ #descend top and medium
+ self.assertElementsEqual(
+ policy.descend_roles(["admin", "pirate"], keep=True),
+ ["user", "pirate", "base","admin"])
+
+ #descend medium & dup
+ self.assertElementsEqual(
+ policy.descend_roles(["user", "pirate","base"], keep=True),
+ ["base","user","pirate"])
+
+ #descend medium
+ self.assertElementsEqual(
+ policy.descend_roles(["user", "pirate"], keep=True),
+ ["base","user","pirate"])
+
+ #descend lowest
+ self.assertElementsEqual(
+ policy.descend_roles(["base"], keep=True),
+ ["base"])
+
+ #descend none
+ self.assertElementsEqual(
+ policy.descend_roles([], keep=True),
+ [])
+
+ def test_descend_roles_rtype(self):
+ policy = policy_01()
+ elems = [ "base"]
+ check_rtype(self, partial(policy.descend_roles, ["user","pirate"]), set, elems)
+
+ #=========================================================
+ #test ensure_valid_roles(roles,grantable=None)
+ #=========================================================
+ def test_ensure_valid_roles(self):
+ "test ensure_valid_roles()"
+ policy = policy_01()
+
+ #test no roles
+ self.assert_(policy.ensure_valid_roles([]))
+ self.assert_(policy.ensure_valid_roles([], grantable=True))
+ self.assert_(policy.ensure_valid_roles([], grantable=False))
+
+ #test known roles
+ self.assert_(policy.ensure_valid_roles(["user", "base"]))
+
+ #test unknown roles (and combinations w/ known roles)
+ self.assertRaises(ValueError, policy.ensure_valid_roles, ["user", "xxx"])
+ self.assertRaises(ValueError, policy.ensure_valid_roles, [None])
+
+ #test grantable role
+ self.assert_(policy.ensure_valid_roles(["user"], grantable=True))
+ self.assertRaises(ValueError, policy.ensure_valid_roles, ["user"], grantable=False)
+
+ #test ungrantable role
+ self.assert_(policy.ensure_valid_roles(["base"], grantable=False))
+ self.assertRaises(ValueError, policy.ensure_valid_roles, ["base"], grantable=True)
+
+ #check accepts single role string
+ #NOTE: this is deprecated, and may be removed in future.
+ with catch_all_warnings() as wmsgs:
+ self.assert_(policy.ensure_valid_roles("user", grantable=True))
+ wmsgs.pop()
+ self.assertRaises(ValueError, policy.ensure_valid_roles, "user", grantable=False)
+ wmsgs.pop()
+
+ #=========================================================
+ #test ensure_valid_role(role,grantable=None)
+ #=========================================================
+ def test_ensure_valid_role(self):
+ "test ensure_valid_role()"
+ policy = policy_01()
+
+ #test unknown role
+ self.assertRaises(ValueError, policy.ensure_valid_role, None)
+ self.assertRaises(ValueError, policy.ensure_valid_role, "xxx")
+ self.assertRaises(ValueError, policy.ensure_valid_role, "xxx", grantable=True)
+ self.assertRaises(ValueError, policy.ensure_valid_role, "xxx", grantable=False)
+
+ #test grantable role
+ self.assert_(policy.ensure_valid_role("user"))
+ self.assert_(policy.ensure_valid_role("user", grantable=True))
+ self.assertRaises(ValueError, policy.ensure_valid_role, "user", grantable=False)
+
+ #test ungrantable role
+ self.assert_(policy.ensure_valid_role("base"))
+ self.assertRaises(ValueError, policy.ensure_valid_role, "base", grantable=True)
+ self.assert_(policy.ensure_valid_role("base", grantable=False))
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+class PermissionCreationTest(TestCase):
+ "test policy's permission & link creation functions"
+ #=========================================================
+ #test permit(roles, action, *a, **k) -> perm_obj
+ #=========================================================
+ def test_permit(self):
+ "test permit()"
+ policy = policy_01()
+ self.assertEquals(policy._links,[])
+
+ a = policy.permit(["admin"], "perm-a")
+ b = policy.permit(["user","pirate"],"perm-b")
+ l1,l2 = policy._links
+
+ self.assertEqual(l1.perm_objs, [a])
+ self.assert_sets_equal(l1.base_roles,["admin"])
+ ##self.assert_sets_equal(l1.expanded_roles,["admin"])
+
+ self.assertEqual(l2.perm_objs, [b])
+ self.assert_sets_equal(l2.base_roles,["user",'pirate'])
+ ##self.assert_sets_equal(l2.expanded_roles,["admin","user","pirate"])
+
+ def test_permit_string(self):
+ "test permit() w/ single role as string"
+ policy = policy_01()
+ self.assertEquals(policy._links,[])
+ a = policy.permit("admin","perm-a")
+ l1, = policy._links
+ self.assertEqual(l1.perm_objs, [a])
+ self.assert_sets_equal(l1.base_roles,["admin"])
+
+ #=========================================================
+ #test permit_list(roles, perm_descs) -> perm_objs
+ #=========================================================
+ def test_permit_list(self):
+ "test permit_list()"
+ policy = policy_01()
+ self.assertEquals(policy._links,[])
+ a, = policy.permit_list(["admin"],[dict(action="perm-a")])
+ b,c = policy.permit_list(["user","pirate"],[dict(action="perm-a"),
+ dict(action="perm-b")])
+ l1,l2 = policy._links
+ self.assertEqual(l1.perm_objs, [a])
+ self.assert_sets_equal(l1.base_roles,["admin"])
+ ##self.assert_sets_equal(l1.expanded_roles,["admin"])
+
+ self.assertEqual(l2.perm_objs, [b,c])
+ self.assert_sets_equal(l2.base_roles,["user",'pirate'])
+ ##self.assert_sets_equal(l2.expanded_roles,["admin","user","pirate"])
+
+ def test_permit_list_string(self):
+ "test permit_list() w/ single role as string"
+ policy = policy_01()
+ self.assertEquals(policy._links,[])
+ a, = policy.permit_list("admin",[dict(action="perm-a")])
+ l1, = policy._links
+ self.assertEqual(l1.perm_objs, [a])
+ self.assert_sets_equal(l1.base_roles,["admin"])
+
+ #=========================================================
+ #test create_permission(action, *a, **k) -> perm
+ #=========================================================
+ def test_create_permission(self):
+ "test create_permission"
+ policy = Policy()
+ p = policy.create_permission("update")
+ self.assertEqual(p.action, "update")
+ self.assertIs(p.klass, None)
+ self.assertIs(p.attrs,None)
+
+ p2 = policy.create_permission("update", "test")
+ self.assertEqual(p2.action, "update")
+ self.assertIs(p2.klass, "test")
+ self.assertIs(p.attrs,None)
+
+ p3 = policy.create_permission("update", "test", attrs=("bob",))
+ self.assertEqual(p3.action, "update")
+ self.assertIs(p3.klass, "test")
+ self.assert_sets_equal(p3.attrs, ["bob"])
+
+ policy.freeze()
+ self.assertRaises(AssertionError, policy.create_permission, "edit")
+
+ def test_create_permission_subclassed(self):
+ "test create_permission() honors Policy.Permission"
+ #make sure orig Perm won't take "xxx"
+ self.assertRaises(TypeError, Policy.Permission, "test", xxx=23)
+
+ #create role subclass which accepts "xxx"
+ class MyPermission(Policy.Permission):
+ def __init__(self, *a, **k):
+ self.xxx = k.pop("xxx",None)
+ self.__super.__init__(*a,**k)
+
+ #create policy class which uses MyRole
+ class MyPolicy(Policy):
+ Permission = MyPermission
+
+ #try creating role, make sure MyRole was used
+ policy = MyPolicy()
+ r = policy.create_permission("test", xxx=23)
+ self.assertIsInstance(r,MyPermission)
+ self.assertEqual(r.xxx, 23)
+
+ #=========================================================
+ #test create_link(perm_objs, roles)
+ #=========================================================
+ def test_create_link(self):
+ "test create_link()"
+ policy = policy_01()
+ a = policy.create_permission("perm-a")
+ b = policy.create_permission("perm-b")
+ c = policy.create_permission("perm-c")
+ self.assertEquals(policy._links,[])
+
+ policy.create_link([a],['admin'])
+ policy.create_link([b,c],['user','pirate'])
+ l1,l2 = policy._links
+
+ self.assertEqual(l1.perm_objs, [a])
+ self.assert_sets_equal(l1.base_roles,["admin"])
+ ##self.assert_sets_equal(l1.expanded_roles,["admin"])
+
+ self.assertEqual(l2.perm_objs, [b,c])
+ self.assert_sets_equal(l2.base_roles,["user",'pirate'])
+ ##self.assert_sets_equal(l2.expanded_roles,["user","pirate","admin"])
+
+ def test_create_link_string(self):
+ "test create_link() with single role as string"
+ policy = policy_01()
+ a = policy.create_permission("perm-a")
+ b = policy.create_permission("perm-b")
+ c = policy.create_permission("perm-c")
+ self.assertEquals(policy._links,[])
+
+ policy.create_link([a],'admin')
+ l1, = policy._links
+
+ self.assertEqual(l1.perm_objs, [a])
+ self.assert_sets_equal(l1.base_roles,["admin"])
+ ##self.assert_sets_equal(l1.expanded_roles,["admin"])
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+class PermissionExaminationTest(TestCase):
+ "test policy's permission & link examination functions"
+ #=========================================================
+ #user_has_permission
+ #=========================================================
+ #test positional params (action, klass, item)
+ #test kwd params (attr, scope)
+
+ def test_uhp(self):
+ "test basic user_has_permission() functions"
+ policy, admin, employee, client, User = policy_03x()
+
+ #check everyone inherits from 'person'
+ self.assert_(admin.has_permission("sign-in"))
+ self.assert_(employee.has_permission("sign-in"))
+ self.assert_(client.has_permission("sign-in"))
+
+ #double-check guards are working
+ self.assert_(employee.has_permission("update","user",employee))
+ self.assert_(not employee.has_permission("update","user",admin))
+
+ #check guard works for generic case
+ self.assert_(employee.has_permission("retire", "user"))
+ self.assert_(employee.has_permission("retire", "user", client))
+ self.assert_(not employee.has_permission("retire", "user", employee))
+
+ #check klass=False works
+ self.assert_(not admin.has_permission("sign-in", "user"))
+
+ #check klass=True works
+ self.assert_(not admin.has_permission("delete"))
+ self.assert_(admin.has_permission("delete", "user"))
+
+ #check inheritance matches down, not up
+ self.assert_(not employee.has_permission("delete", "user"))
+
+ #check attrs & deny are working properly
+ self.assert_(client.has_permission("update","journal"))
+ self.assert_(client.has_permission("update","journal", attr="date"))
+ self.assert_(not client.has_permission("update","journal", attr="owner"))
+
+ def test_uhp_params(self):
+ "test user_has_permission() positional vs kwd arguments"
+
+ policy, admin, employee, client, User = policy_03x()
+
+ #all kwds
+ self.assert_(employee.has_permission(action="update", klass="user", attr="xxx", item=employee))
+
+ #min positionals
+ self.assert_(employee.has_permission("sign-in"))
+ self.assert_(employee.has_permission("sign-in",attr="xxx"))
+
+ #too few positionals
+ self.assertRaises(TypeError, employee.has_permission, attr="xxx")
+
+ #all possible positionals
+ self.assert_(employee.has_permission("update", "user", employee, attr="xxx"))
+
+ #too many positionals
+ self.assertRaises(TypeError, employee.has_permission,
+ "update", "user", employee, "xxx")
+
+ #unknown kwds
+ self.assertRaises(TypeError, employee.has_permission,
+ "update", "user", employee, xxx="xxx")
+
+ #=========================================================
+ #test get_user_permissions(user,rtype=tuple)
+ #=========================================================
+ #NOTE: get_user_permissions() wraps get_role_permissons,
+ # so we rely on that test for more complicated inputs.
+ def test_gup_simple(self):
+ "test get_user_permissions()"
+ policy,a,b,u,p = policy_02x()
+
+ user = stub(roles=())
+ self.assertEquals(policy.get_user_permissions(user,rtype=list),[])
+
+ user = stub(roles=("user",))
+ self.assertEquals(policy.get_user_permissions(user,rtype=list),[b,u])
+
+ user = stub(roles=("admin",))
+ self.assertEquals(policy.get_user_permissions(user,rtype=list),[a,b,u,p])
+
+ def test_gup_rtype(self):
+ policy,a,b,u,p = policy_02x()
+
+ user = stub(roles=("user", "pirate"))
+ elems = [b,u,p]
+ check_rtype(self, partial(policy.get_user_permissions,user), tuple, elems, ordered=True)
+
+ #=========================================================
+ #test get_role_permissions(roles, inherited=True, rtype=tuple)
+ #=========================================================
+ def test_grp_00(self):
+ "test get_role_permissions() works under frozen & thawed modes"
+ policy = policy_01()
+ self.assertElementsEqual(policy.get_role_permissions(["user"]),[])
+ policy.freeze()
+ self.assertElementsEqual(policy.get_role_permissions(["user"]),[])
+ #NOTE: current implementation no longer forces policy to be frozen
+ ## "test get_role_permissions() requires frozen policy object"
+ ## policy = policy_01()
+ ## self.assertRaises(AssertionError, policy.get_role_permissions, ["client"])
+ ## policy.freeze()
+ ## self.assertElementsEqual(policy.get_role_permissions(["client"]),[])
+
+ def test_grp_01(self):
+ "test get_role_permissions() obeys role inheritance chain"
+ #test perms reported for correct roles
+ policy,a,b,u,p = policy_02x()
+
+ #test non-inherited permissions are listed correctly
+ def grp(*roles):
+ return list(policy.get_role_permissions(roles, inherited=False))
+ self.assertEqual(grp("base"),[b])
+ self.assertEqual(grp("user"),[u])
+ self.assertEqual(grp("admin"),[a])
+ self.assertEqual(grp("pirate"),[p])
+
+ #test inherited permissions are listed correctly and in order
+ def grp(*roles):
+ return list(policy.get_role_permissions(roles))
+ self.assertEqual(grp("base"),[b])
+ self.assertEqual(grp("user"),[b,u])
+ self.assertEqual(grp("admin"),[a,b,u,p])
+ self.assertEqual(grp("pirate"),[b,p])
+
+ def test_grp_02(self):
+ "test get_role_permissions() handles multiple roles"
+ #test perms reported for correct roles
+ policy,a,b,u,p = policy_02x()
+
+ #test non-inherited permissions are listed correctly
+ def grp(*roles):
+ return list(policy.get_role_permissions(roles, inherited=False))
+ self.assertEqual(grp("base","user"),[b,u])
+ self.assertEqual(grp("pirate","user"),[u,p])
+ self.assertEqual(grp("admin","base"),[a,b])
+ self.assertEqual(grp("admin","pirate"),[a,p])
+
+ #test inherited permissions are listed correctly and in order
+ def grp(*roles):
+ return list(policy.get_role_permissions(roles))
+ self.assertEqual(grp("base","user"),[b,u])
+ self.assertEqual(grp("pirate","user"),[b,u,p])
+ self.assertEqual(grp("admin","base"),[a,b,u,p])
+ self.assertEqual(grp("admin","pirate"),[a,b,u,p])
+
+ def test_grp_priority(self):
+ "test get_role_permissions() obeys priority"
+ policy = policy_01()
+ b = policy.permit("base", "perm-b")
+ p = policy.permit("pirate", "perm-p", priority=-10)
+ u = policy.permit("user", "perm-u", priority=10)
+ a = policy.permit("admin", "perm-a")
+ #NOTE: w/o priority, order would be b,p,u,a
+ policy.freeze()
+
+ def grp(*roles):
+ return list(policy.get_role_permissions(roles))
+ self.assertEqual(grp("base"),[b])
+ self.assertEqual(grp("user"),[u,b])
+ self.assertEqual(grp("admin"),[u,b,a,p])
+ self.assertEqual(grp("pirate"),[b,p])
+
+ def test_grp_rtype(self):
+ "test get_role_permissions() rtype option"
+ policy,a,b,u,p = policy_02x()
+ elems = [a,b,u,p]
+ check_rtype(self,partial(policy.get_role_permissions,["admin"]), tuple, elems)
+
+ def test_grp_string(self):
+ "test get_role_permissions() w/ single role as string"
+ policy,a,b,u,p = policy_02x()
+ self.assertElementsEqual(policy.get_role_permissions("user"),[b,u])
+
+ #=========================================================
+ #get_linked_roles(perm_obj, inherited=True, limit_roles=None, rtype=set)
+ #=========================================================
+ def test_glr_basic(self):
+ "test get_linked_roles() basic behavior"
+ policy,a,b,u,p = policy_02x()
+
+ results = policy.get_linked_roles(a)
+ self.assert_sets_equal(results,["admin"])
+
+ results = policy.get_linked_roles(b)
+ self.assert_sets_equal(results,["admin","base","user", "pirate"])
+
+ results = policy.get_linked_roles(u)
+ self.assert_sets_equal(results,["admin","user"])
+
+ results = policy.get_linked_roles(p)
+ self.assert_sets_equal(results,["admin","pirate"])
+
+ def test_glr_inherited(self):
+ "test get_linked_roles() inherited=False flag"
+ policy,a,b,u,p = policy_02x()
+
+ results = policy.get_linked_roles(a, inherited=False)
+ self.assert_sets_equal(results,["admin"])
+
+ results = policy.get_linked_roles(b, inherited=False)
+ self.assert_sets_equal(results,["base"])
+
+ results = policy.get_linked_roles(u, inherited=False)
+ self.assert_sets_equal(results,["user"])
+
+ results = policy.get_linked_roles(p, inherited=False)
+ self.assert_sets_equal(results,["pirate"])
+
+ def test_glr_limit_roles(self):
+ "test get_linked_roles() limit_roles kwd"
+ policy,a,b,u,p = policy_02x()
+
+ #check no roles
+ results = policy.get_linked_roles(a, limit_roles=[])
+ self.assert_sets_equal(results,[])
+
+ #check restricting roles
+ results = policy.get_linked_roles(b, limit_roles=["user", "pirate"])
+ self.assert_sets_equal(results,["user", "pirate"])
+
+ #check unused + used roles
+ results = policy.get_linked_roles(u, limit_roles=["admin", "user", "base"])
+ self.assert_sets_equal(results,["admin","user"])
+
+ #check unused roles
+ results = policy.get_linked_roles(p, limit_roles=["user"])
+ self.assert_sets_equal(results,[])
+
+ def test_glr_rtype(self):
+ "test get_linked_roles() rtype kwd"
+ policy,a,b,u,p = policy_02x()
+
+ match = ["admin", "base", "user", "pirate"]
+ check_rtype(self, partial(policy.get_linked_roles,b), set, match)
+
+ #=========================================================
+ #test could_allow()
+ #=========================================================
+ def test_ca_basic(self):
+ "test policy.could_allow()"
+ policy, admin, employee, client, User = policy_03x()
+
+ #test one with a guard in the perms
+ self.assert_(policy.could_allow("update", "user"))
+
+ #test one that's not listed
+ self.assert_(not policy.could_allow("smile-at", "user"))
+
+ #test one with a deny rule in the perms
+ self.assert_(policy.could_allow("update", "journal", attr="owner"))
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+class MiscTest(TestCase):
+ "test misc policy functions"
+ #=========================================================
+ #inspect_user_roles
+ #=========================================================
+ def test_iur_default(self):
+ policy = policy_01()
+ u = stub(roles=("user",))
+ self.assertElementsEqual(policy.get_user_roles(u,inherited=False),["user"])
+ self.assertElementsEqual(policy.get_user_roles(u),["user", "base"])
+
+ def test_iur_override(self):
+ policy = policy_01(inspect_user_roles=lambda u: u.alt_roles)
+ u = stub(alt_roles=("user",))
+ self.assertElementsEqual(policy.get_user_roles(u,inherited=False),["user"])
+ self.assertElementsEqual(policy.get_user_roles(u),["user", "base"])
+
+ def test_iur_valid(self):
+ policy = policy_01()
+ u = stub(roles=("user","xxx"))
+ self.assertRaises(ValueError, policy.get_user_roles, u)
+ #KeyError: xxx role undefined
+
+ def test_iur_grantable(self):
+ policy = policy_01()
+ u = stub(roles=("user","base"))
+ self.assertRaises(ValueError, policy.get_user_roles, u)
+ #ValueError: base role not grantable
+
+ #=========================================================
+ #freeze() and frozen
+ #=========================================================
+ def test_freeze(self):
+ "test freeze() and .frozen"
+ policy = Policy()
+ self.assert_(not policy.frozen)
+ policy.freeze()
+ self.assert_(policy.frozen)
+ self.assertRaises(AssertionError, policy.freeze)
+
+ #=========================================================
+ #ensure_frozen
+ #=========================================================
+ def test_ensure_frozen(self):
+ policy = Policy()
+ self.assertRaises(AssertionError, policy.ensure_frozen)
+ policy.freeze()
+ self.assert_(policy.ensure_frozen())
+
+ #=========================================================
+ #ensure_thawed
+ #=========================================================
+ def test_ensure_thawed(self):
+ policy = Policy()
+ self.assert_(policy.ensure_thawed())
+ policy.freeze()
+ self.assertRaises(AssertionError, policy.ensure_thawed)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#eof
+#=========================================================
diff --git a/bps/tests/test_security_pwgen.py b/bps/tests/test_security_pwgen.py
new file mode 100644
index 0000000..6c8c34a
--- /dev/null
+++ b/bps/tests/test_security_pwgen.py
@@ -0,0 +1,109 @@
+"""tests for bps.security.pwhash -- (c) Assurance Technologies 2003-2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os
+from unittest import TestCase
+import hashlib
+import warnings
+from logging import getLogger
+#site
+#pkg
+from bps.security import pwgen
+from bps.rng import drandom, srandom
+from bps.text import asbool
+from bps.tests.utils import enable_suite
+#module
+log = getLogger(__name__)
+
+#=========================================================
+#
+#=========================================================
+if enable_suite("pwgen_dups"):
+
+ class DupTest(TestCase):
+ "Test the rate of duplicate generation for various algorithms"
+ rounds = 10**5
+ duplicates = [
+ #check random engine, mainly as a sanity check
+ dict(alg='hex', size=7, dups=25),
+
+ #check cvc engine
+ dict(alg="cvc", size=8, dups=10),
+ dict(alg="cvc", size=10, dups=0),
+
+ #check the gpw engine for various languages
+ dict(alg="gpw", language="gpw", size=8, dups=350),
+ dict(alg="gpw", language="gpw", size=10, dups=20),
+
+ #the public presets should always values at least this low
+ dict(alg='strong', dups=0),
+ dict(alg='human', dups=0),
+
+ ]
+
+ def test_duplicates(self):
+ "test rate of duplicate password generation"
+ for preset in self.duplicates:
+ self._test_duplicates_preset(preset)
+
+ def _test_duplicates_preset(self, preset):
+ info = preset.copy()
+ max_dups = info.pop('dups')
+ max_dup_rate = info.pop("dup_rate", 2)
+ log.info("Testing config for duplicates: config=%r rounds=%r", info, self.rounds)
+ gen = pwgen.generate_secret(count="iter", **info)
+ seen = set()
+ hist = {}
+ dups = 0
+ for c in xrange(self.rounds):
+ secret = gen.next()
+ if secret in seen:
+ dups += 1
+ if secret in hist:
+ hist[secret] += 1
+ else:
+ hist[secret] = 2
+ else:
+ seen.add(secret)
+ log.info("\tresults: rate=%.2f%% dups=%r max_dups=%r",
+ 100.0 * dups / self.rounds, dups, max_dups)
+ if hist:
+ def sk(pair):
+ return pair[1], pair[0]
+ values = sorted(hist.iteritems(), key=sk)[:10]
+ self.assertTrue(values[0][1] <= max_dup_rate, "bias detected: %r" % (values, ))
+ log.debug("\ttop dups: %s", values)
+
+ #NOTE: having no better measurement, we'll accept a .08% dup rate, but nothing more.
+ self.assertTrue(dups <= max_dups, "too many duplicates: %r > %r" % (dups, max_dups))
+
+class ConstantTest(TestCase):
+ "make sure predefined constants work"
+ #NOTE: this is _very_ dependant on number of times rand is called,
+ #if code changes, these constants may change.
+ presets = [
+ [ dict(alg="alphanum", count=3),
+ ['xR0uwaf5lE1mLcc9', 'B70Ux4XSb5ZGYdTM', 'FvSW1V08TN3aAY8w'] ],
+ [ dict(alg="human", count=3),
+ ['yuicoboeradai', 'rahimeyiinaa', 'fiyoujaefafuk'] ],
+ ]
+
+ def setUp(self):
+ pwgen.srandom = drandom
+
+ def tearDown(self):
+ pwgen.srandom = srandom
+
+ def test_presets(self):
+ #test preset password known to be created for a given seed value
+ for kwds, result in self.presets:
+ drandom.seed(1234)
+ out = pwgen.generate_secret(**kwds)
+ self.assertEqual(out, result)
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_security_pwhash.py b/bps/tests/test_security_pwhash.py
new file mode 100644
index 0000000..08601d0
--- /dev/null
+++ b/bps/tests/test_security_pwhash.py
@@ -0,0 +1,1220 @@
+"""tests for bps.security.pwhash -- (c) Assurance Technologies 2003-2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import hashlib
+import warnings
+from logging import getLogger
+#site
+#pkg
+from bps.security import pwhash
+from bps.tests.utils import TestCase, enable_suite, catch_warnings
+#module
+log = getLogger(__name__)
+
+#=========================================================
+#helper password algorithms - these serve both as simple
+# examples, and are used in the unittests
+#=========================================================
+class UnsaltedAlg(pwhash.CryptAlgorithm):
+ "example algorithm usuing constant-salt hash"
+ name = "unsalted"
+ salt_bits = 0
+
+ def identify(self, hash):
+ if hash is None:
+ return False
+ if len(hash) != 40:
+ return False
+ try:
+ int(hash, 16)
+ except ValueError:
+ return False
+ return True
+
+ def encrypt(self, secret, salt=None, keep_salt=False):
+ #NOTE: that salt / keep_salted are simply ignored
+ return hashlib.sha1("boblious" + secret).hexdigest()
+
+class SaltedAlg(pwhash.CryptAlgorithm):
+ """example naive salted algorithm which never obeys keep_salt
+ (note that the default verify() is implemented in this case)
+ """
+ name = "salted"
+ salt_bits = 6*2
+
+ def identify(self, hash):
+ if hash is None:
+ return False
+ return hash.startswith("@salt")
+
+ def _raw(self, secret, salt):
+ return "@salt%s%s" % (salt, hashlib.sha1(salt+secret).hexdigest())
+
+ def encrypt(self, secret, salt=None, keep_salt=False):
+## warn("keep_salt not supported by this algorithm")
+ real_salt = pwhash.h64_gen_salt(2)
+ return self._raw(secret, real_salt)
+
+ def verify(self, secret, hash):
+ if hash is None:
+ return False
+ salt = hash[5:7]
+ return self._raw(secret, salt) == hash
+
+class SampleAlg(pwhash.CryptAlgorithm):
+ "example salted algorithm w/ keep_salt support"
+ name = "sample"
+ salt_bits = 6*2
+
+ def identify(self, hash):
+ if hash is None:
+ return False
+ return hash.startswith("@sam")
+
+ def encrypt(self, secret, salt=None, keep_salt=False):
+ if salt and keep_salt:
+ real_salt = salt[4:6]
+ else:
+ real_salt = pwhash.h64_gen_salt(2)
+ return "@sam%s%s" % (real_salt, hashlib.sha1(real_salt+secret).hexdigest())
+
+#=========================================================
+#other unittest helpers
+#=========================================================
+
+#list of various distinct secrets that all algs are tested with
+SECRETS = [
+ '',
+ ' ',
+ 'test',
+ 'testa',
+ 'test test',
+ 'test bcdef',
+ 'testq'
+ 'testtest',
+ 'Compl3X AlphaNu3meric',
+ '4lpHa N|_|M3r1K W/ Cur51|\\|g: #$%(*)(*%#',
+ 'Really Long Password (tm), which is all the rage nowadays with the cool kids'
+ ]
+
+class _CryptTestCase(TestCase):
+ "base class for CryptAlgorithm subclass testing"
+
+ #=========================================================
+ #subclass attrs
+ #=========================================================
+ alg = None #plugin for class
+ positive_knowns = () #list of (secret,hash) pairs to verify they do match
+ negative_knowns = () #list of (secret,hash) pairs to verify they don't match
+ negative_identify = () # list of hashses that shouldn't identify as this one
+ invalid_identify = () # list of this alg's hashes w/ typo
+
+ def _prefix(self):
+ return self.alg.name
+
+ secrets = SECRETS #list of default secrets to check
+
+ #=========================================================
+ #identify
+ #=========================================================
+ def test_01_identify_positive_knowns(self):
+ "test identify() against known correct algorithm hashes"
+ for _, hash in self.positive_knowns:
+ self.assertEqual(self.do_identify(hash), True)
+ for _, hash in self.negative_knowns:
+ self.assertEqual(self.do_identify(hash), True)
+
+ def test_02_identify_negative_knowns(self):
+ "test identify() against known wrong algorithm hashes"
+ for hash in self.negative_identify:
+ self.assertEqual(self.do_identify(hash), False)
+
+ def test_03_identify_invalid_knowns(self):
+ "test identify() against known invalid algorithm hashes"
+ for hash in self.invalid_identify:
+ self.assertEqual(self.do_identify(hash), False)
+
+ def test_04_identify_none(self):
+ "test identify() reports hash=None as False"
+ self.assertEqual(self.do_identify(None), False)
+
+ #=========================================================
+ #verify
+ #=========================================================
+ def test_10_verify_positive_knowns(self):
+ "test verify() against algorithm-specific known positive matches"
+ for secret, hash in self.positive_knowns:
+ self.assertEqual(self.do_verify(secret, hash), True)
+
+ def test_11_verify_negative_knowns(self):
+ "test verify() against algorithm-specific known negative matches"
+ for secret, hash in self.negative_knowns:
+ self.assertEqual(self.do_verify(secret, hash), False)
+
+ def test_12_verify_derived_negative_knowns(self):
+ "test verify() against algorithm-specific deliberate negative matches"
+ for secret, hash in self.positive_knowns:
+ self.assertEqual(self.do_verify(self.do_concat(secret,'x'), hash), False)
+
+#XXX: haven't decided if this should be part of protocol
+## def test_13_verify_secret_none(self):
+## "test verify() accepts secret=None and reports False"
+## for _, hash in self.positive_knowns:
+## self.assert_(not self.do_verify(None, hash))
+
+ def test_14_verify_hash_none(self):
+ "test verify() reports hash=None as not matching"
+ for secret in (None, "", "xxx"):
+ self.assert_(not self.do_verify(secret, None))
+
+ #=========================================================
+ #encrypt
+ #=========================================================
+ def test_30_encrypt(self):
+ "test encrypt() against standard secrets"
+ for secret in self.secrets:
+ self.check_encrypt(secret)
+ for secret, _ in self.positive_knowns:
+ self.check_encrypt(secret)
+ for secret, _ in self.negative_knowns:
+ self.check_encrypt(secret)
+
+ def test_31_encrypt_gen_salt(self):
+ "test encrypt() generates new salt each time"
+ if not self.alg.has_salt:
+ return
+ for secret, hash in self.positive_knowns:
+ hash2 = self.do_encrypt(secret, hash)
+ self.assertNotEqual(hash, hash2)
+
+ def test_31_encrypt_keep_salt(self):
+ "test encrypt() honors keep_salt keyword"
+ if not self.alg.has_salt:
+ return
+ for secret, hash in self.positive_knowns:
+ hash2 = self.do_encrypt(secret, hash, keep_salt=True)
+ self.assertEqual(hash, hash2)
+
+ def check_encrypt(self, secret):
+ "check encrypt() behavior for a given secret"
+ #hash the secret
+ hash = self.do_encrypt(secret)
+
+ #test identification
+ self.assertEqual(self.do_identify(hash), True)
+
+ #test positive verification
+ self.assertEqual(self.do_verify(secret, hash), True)
+
+ #test negative verification
+ for other in ['', 'test', self.do_concat(secret,'x')]:
+ if other != secret:
+ self.assertEqual(self.do_verify(other, hash), False,
+ "hash collision: %r and %r => %r" % (secret, other, hash))
+
+ def test_32_secret_chars(self):
+ "test secret_chars limitation"
+ #hash a really long secret
+ secret = "too many secrets" * 16
+ tail = "my socrates note" * 8
+ hash = self.do_encrypt(secret)
+
+ sc = self.alg.secret_chars
+ if sc:
+ #bcrypt, unixcrypt
+ assert sc < len(secret), "need to increase test secret size"
+ self.assert_(self.do_verify(secret[:sc], hash))
+ self.assert_(self.do_verify(secret + tail, hash))
+ self.assert_(not self.do_verify(secret[:sc-1], hash))
+ else:
+ #if no limit, secret+tail shouldn't verify
+ self.assert_(not self.do_verify(secret[:16], hash))
+ self.assert_(not self.do_verify(secret+tail, hash))
+
+ def test_33_encrypt_none(self):
+ "test encrypt() refused secret=None"
+ self.assertRaises(TypeError, self.do_encrypt, None)
+
+ #=========================================================
+ #alg interface
+ #=========================================================
+ def do_concat(self, secret, prefix):
+ return prefix + secret
+
+ def do_encrypt(self, *args, **kwds):
+ return self.alg().encrypt(*args, **kwds)
+
+ def do_verify(self, secret, hash):
+ return self.alg().verify(secret, hash)
+
+ def do_identify(self, hash):
+ return self.alg().identify(hash)
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#dummy algorithms
+#=========================================================
+#this tests the dummy algorithms defined above,
+#to make sure creating custom algorithms works properly.
+
+class UnsaltedDummyAlgTest(_CryptTestCase):
+ alg = UnsaltedAlg
+
+class SaltedDummyAlgTest(_CryptTestCase):
+ alg = SaltedAlg
+
+class SampleDummyAlgTest(_CryptTestCase):
+ alg = SampleAlg
+
+#=========================================================
+#database hashes
+#=========================================================
+class Mysql10CryptTest(_CryptTestCase):
+ alg = pwhash.Mysql10Crypt
+
+ #remove single space from secrets
+ secrets = [ x for x in _CryptTestCase.secrets if x != ' ' ]
+
+ positive_knowns = (
+ ('mypass', '6f8c114b58f2ce9e'),
+ )
+ invalid_identify = (
+ #bad char in otherwise correct hash
+ '6z8c114b58f2ce9e',
+ )
+ negative_identify = (
+ #other hashes
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o.'
+ )
+
+ def test_whitespace(self):
+ "check whitespace is ignored properly"
+ h = self.do_encrypt("mypass")
+ h2 = self.do_encrypt("my pass")
+ self.assertEqual(h, h2)
+
+class Mysql41CryptTest(_CryptTestCase):
+ alg = pwhash.Mysql41Crypt
+ positive_knowns = (
+ ('mypass', '*6C8989366EAF75BB670AD8EA7A7FC1176A95CEF4'),
+ )
+ invalid_identify = (
+ #bad char in otherwise correct hash
+ '*6Z8989366EAF75BB670AD8EA7A7FC1176A95CEF4',
+ )
+ negative_identify = (
+ #other hashes
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o.'
+ '6f8c114b58f2ce9e',
+ )
+
+class PostgresMd5CryptTest(_CryptTestCase):
+ alg = pwhash.PostgresMd5Crypt
+ positive_knowns = (
+ # ((secret,user),hash)
+ (('mypass', 'postgres'), 'md55fba2ea04fd36069d2574ea71c8efe9d'),
+ (('mypass', 'root'), 'md540c31989b20437833f697e485811254b'),
+ (("testpassword",'testuser'), 'md5d4fc5129cc2c25465a5370113ae9835f'),
+ )
+ invalid_identify = (
+ #bad char in otherwise correct hash
+ 'md54zc31989b20437833f697e485811254b',
+ )
+ negative_identify = (
+ #other hashes
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o.'
+ '6f8c114b58f2ce9e',
+ )
+
+ def test_tuple_mode(self):
+ "check tuple mode works for encrypt/verify"
+ self.assertEquals(self.alg().encrypt(('mypass', 'postgres')),
+ 'md55fba2ea04fd36069d2574ea71c8efe9d')
+ self.assertEquals(self.alg().verify(('mypass', 'postgres'),
+ 'md55fba2ea04fd36069d2574ea71c8efe9d'), True)
+
+ def test_user(self):
+ "check user kwd is required for encrypt/verify"
+ self.assertRaises(ValueError, self.alg().encrypt, 'mypass')
+ self.assertRaises(ValueError, self.alg().verify, 'mypass', 'md55fba2ea04fd36069d2574ea71c8efe9d')
+
+ def do_concat(self, secret, prefix):
+ if isinstance(secret, tuple):
+ secret, user = secret
+ secret = prefix + secret
+ return secret, user
+ else:
+ return prefix + secret
+
+ def do_encrypt(self, secret, *args, **kwds):
+ if isinstance(secret, tuple):
+ secret, user = secret
+ else:
+ user = 'default'
+ assert 'user' not in kwds
+ kwds['user'] = user
+ return self.alg().encrypt(secret, *args, **kwds)
+
+ def do_verify(self, secret, hash):
+ if isinstance(secret, tuple):
+ secret, user = secret
+ else:
+ user = 'default'
+ return self.alg().verify(secret, hash, user=user)
+
+#=========================================================
+#UnixCrypt
+#=========================================================
+
+class UnixCryptTest(_CryptTestCase):
+ "test UnixCrypt algorithm"
+ alg = pwhash.UnixCrypt
+ positive_knowns = (
+ #secret, example hash which matches secret
+ ('', 'OgAwTx2l6NADI'),
+ (' ', '/Hk.VPuwQTXbc'),
+ ('test', 'N1tQbOFcM5fpg'),
+ ('Compl3X AlphaNu3meric', 'um.Wguz3eVCx2'),
+ ('4lpHa N|_|M3r1K W/ Cur5Es: #$%(*)(*%#', 'sNYqfOyauIyic'),
+ ('AlOtBsOl', 'cEpWz5IUCShqM'),
+ )
+ invalid_identify = (
+ #bad char in otherwise correctly formatted hash
+ '!gAwTx2l6NADI',
+ )
+ negative_identify = (
+ #hashes using other algs, which shouldn't match this algorithm
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o.'
+ )
+
+class UnixCryptBackendTest(TestCase):
+ "test builtin unix crypt backend"
+ unix_crypt = pwhash.unix_crypt
+
+ positive_knowns = UnixCryptTest.positive_knowns
+
+ def test_knowns(self):
+ "test lowlevel unix_crypt function"
+ unix_crypt = self.unix_crypt
+ for secret, result in self.positive_knowns:
+ #make sure crypt verifies using salt
+ out = unix_crypt(secret, result[:2])
+ self.assertEqual(out, result)
+ #make sure crypt verifies using partial hash
+ out = unix_crypt(secret, result[:6])
+ self.assertEqual(out, result)
+ #make sure crypt verifies using whole hash
+ out = unix_crypt(secret, result)
+ self.assertEqual(out, result)
+
+ #TODO: deal with border cases where host crypt & bps crypt differ
+ # (none of which should impact the normal use cases)
+ #border cases:
+ # no salt given, empty salt given, 1 char salt
+ # salt w/ non-b64 chars (linux crypt handles this _somehow_)
+ #test that \x00 is NOT allowed
+ #test that other chars _are_ allowed
+
+#=========================================================
+#Md5Crypt
+#=========================================================
+class Md5CryptTest(_CryptTestCase):
+ alg = pwhash.Md5Crypt
+ positive_knowns = (
+ ('', '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o.'),
+ (' ', '$1$m/5ee7ol$bZn0kIBFipq39e.KDXX8I0'),
+ ('test', '$1$ec6XvcoW$ghEtNK2U1MC5l.Dwgi3020'),
+ ('Compl3X AlphaNu3meric', '$1$nX1e7EeI$ljQn72ZUgt6Wxd9hfvHdV0'),
+ ('4lpHa N|_|M3r1K W/ Cur5Es: #$%(*)(*%#', '$1$jQS7o98J$V6iTcr71CGgwW2laf17pi1'),
+ ('test', '$1$SuMrG47N$ymvzYjr7QcEQjaK5m1PGx1'),
+ )
+ invalid_identify = (
+ #bad char in otherwise correct hash
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6o!',
+ )
+ negative_identify = (
+ #other hashes
+ '!gAwTx2l6NADI',
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ )
+
+#=========================================================
+#test raw sha-crypt functions
+#=========================================================
+class Sha256CryptTest(_CryptTestCase):
+ alg = pwhash.Sha256Crypt
+ positive_knowns = (
+ ('', '$5$rounds=10428$uy/jIAhCetNCTtb0$YWvUOXbkqlqhyoPMpN8BMe.ZGsGx2aBvxTvDFI613c3'),
+ (' ', '$5$rounds=10376$I5lNtXtRmf.OoMd8$Ko3AI1VvTANdyKhBPavaRjJzNpSatKU6QVN9uwS9MH.'),
+ ('test', '$5$rounds=11858$WH1ABM5sKhxbkgCK$aTQsjPkz0rBsH3lQlJxw9HDTDXPKBxC0LlVeV69P.t1'),
+ ('Compl3X AlphaNu3meric', '$5$rounds=10350$o.pwkySLCzwTdmQX$nCMVsnF3TXWcBPOympBUUSQi6LGGloZoOsVJMGJ09UB'),
+ ('4lpHa N|_|M3r1K W/ Cur5Es: #$%(*)(*%#', '$5$rounds=11944$9dhlu07dQMRWvTId$LyUI5VWkGFwASlzntk1RLurxX54LUhgAcJZIt0pYGT7'),
+ )
+ invalid_identify = (
+ #bad char in otherwise correct hash
+ '$5$rounds=10428$uy/jIAhCetNCTtb0$YWvUOXbkqlqhyoPMpN8BMe!ZGsGx2aBvxTvDFI613c3'
+ )
+ negative_identify = (
+ #other hashes
+ '!gAwTx2l6NADI',
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6ox',
+ )
+
+class Sha512CryptTest(_CryptTestCase):
+ alg = pwhash.Sha512Crypt
+ positive_knowns = (
+ ('', '$6$rounds=11021$KsvQipYPWpr93wWP$v7xjI4X6vyVptJjB1Y02vZC5SaSijBkGmq1uJhPr3cvqvvkd42Xvo48yLVPFt8dvhCsnlUgpX.//Cxn91H4qy1'),
+ (' ', '$6$rounds=11104$ED9SA4qGmd57Fq2m$q/.PqACDM/JpAHKmr86nkPzzuR5.YpYa8ZJJvI8Zd89ZPUYTJExsFEIuTYbM7gAGcQtTkCEhBKmp1S1QZwaXx0'),
+ ('test', '$6$rounds=11531$G/gkPn17kHYo0gTF$Kq.uZBHlSBXyzsOJXtxJruOOH4yc0Is13uY7yK0PvAvXxbvc1w8DO1RzREMhKsc82K/Jh8OquV8FZUlreYPJk1'),
+ ('Compl3X AlphaNu3meric', '$6$rounds=10787$wakX8nGKEzgJ4Scy$X78uqaX1wYXcSCtS4BVYw2trWkvpa8p7lkAtS9O/6045fK4UB2/Jia0Uy/KzCpODlfVxVNZzCCoV9s2hoLfDs/'),
+ ('4lpHa N|_|M3r1K W/ Cur5Es: #$%(*)(*%#', '$6$rounds=11065$5KXQoE1bztkY5IZr$Jf6krQSUKKOlKca4hSW07MSerFFzVIZt/N3rOTsUgKqp7cUdHrwV8MoIVNCk9q9WL3ZRMsdbwNXpVk0gVxKtz1'),
+ )
+ negative_identify = (
+ #other hashes
+ '!gAwTx2l6NADI',
+ '$5$rounds=10428$uy/jIAhCetNCTtb0$YWvUOXbkqlqhyoPMpN8BMe.ZGsGx2aBvxTvDFI613c3',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6ox',
+ )
+ invalid_identify = (
+ #bad char in otherwise correct hash
+ '$6$rounds=11021$KsvQipYPWpr9!wWP$v7xjI4X6vyVptJjB1Y02vZC5SaSijBkGmq1uJhPr3cvqvvkd42Xvo48yLVPFt8dvhCsnlUgpX.//Cxn91H4qy1',
+ )
+
+class Sha512BackendTest(TestCase):
+ "test sha512-crypt backend against specification unittest"
+ cases512 = [
+ #salt-hash, secret, result -- taken from alg definition page
+ ("$6$saltstring", "Hello world!",
+ "$6$saltstring$svn8UoSVapNtMuq1ukKS4tPQd8iKwSMHWjl/O817G3uBnIFNjnQJu"
+ "esI68u4OTLiBFdcbYEdFCoEOfaS35inz1" ),
+
+ ( "$6$rounds=10000$saltstringsaltstring", "Hello world!",
+ "$6$rounds=10000$saltstringsaltst$OW1/O6BYHV6BcXZu8QVeXbDWra3Oeqh0sb"
+ "HbbMCVNSnCM/UrjmM0Dp8vOuZeHBy/YTBmSK6H9qs/y3RnOaw5v." ),
+
+ ( "$6$rounds=5000$toolongsaltstring", "This is just a test",
+ "$6$rounds=5000$toolongsaltstrin$lQ8jolhgVRVhY4b5pZKaysCLi0QBxGoNeKQ"
+ "zQ3glMhwllF7oGDZxUhx1yxdYcz/e1JSbq3y6JMxxl8audkUEm0" ),
+
+ ( "$6$rounds=1400$anotherlongsaltstring",
+ "a very much longer text to encrypt. This one even stretches over more"
+ "than one line.",
+ "$6$rounds=1400$anotherlongsalts$POfYwTEok97VWcjxIiSOjiykti.o/pQs.wP"
+ "vMxQ6Fm7I6IoYN3CmLs66x9t0oSwbtEW7o7UmJEiDwGqd8p4ur1" ),
+
+ ( "$6$rounds=77777$short",
+ "we have a short salt string but not a short password",
+ "$6$rounds=77777$short$WuQyW2YR.hBNpjjRhpYD/ifIw05xdfeEyQoMxIXbkvr0g"
+ "ge1a1x3yRULJ5CCaUeOxFmtlcGZelFl5CxtgfiAc0" ),
+
+ ( "$6$rounds=123456$asaltof16chars..", "a short string",
+ "$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc"
+ "elCjmw2kSYu.Ec6ycULevoBK25fs2xXgMNrCzIMVcgEJAstJeonj1" ),
+
+ ( "$6$rounds=10$roundstoolow", "the minimum number is still observed",
+ "$6$rounds=1000$roundstoolow$kUMsbe306n21p9R.FRkW3IGn.S9NPN0x50YhH1x"
+ "hLsPuWGsUSklZt58jaTfF4ZEQpyUNGc0dqbpBYYBaHHrsX." ),
+ ]
+ def test512(self):
+ crypt = pwhash.Sha512Crypt()
+ for hash, secret, result in self.cases512:
+ rec = crypt.parse(hash)
+ self.assertEqual(rec.alg, '6')
+ out = crypt.encrypt(secret, hash, keep_salt=True)
+ rec2 = crypt.parse(hash)
+ self.assertEqual(rec2.salt, rec.salt, "hash=%r secret=%r" % (hash, secret))
+ self.assertEqual(rec2.chk, rec.chk, "hash=%r secret=%r" % (hash, secret))
+ self.assertEqual(out, result, "hash=%r secret=%r" % (hash, secret))
+
+#=========================================================
+#BCrypt
+#=========================================================
+if enable_suite("bcrypt"):
+ class BCryptTest(_CryptTestCase):
+ alg = pwhash.BCrypt
+ positive_knowns = (
+ #test cases taken from bcrypt spec
+ ('', '$2a$06$DCq7YPn5Rq63x1Lad4cll.TV4S6ytwfsfvkgY8jIucDrjc8deX1s.'),
+ ('', '$2a$08$HqWuK6/Ng6sg9gQzbLrgb.Tl.ZHfXLhvt/SgVyWhQqgqcZ7ZuUtye'),
+ ('', '$2a$10$k1wbIrmNyFAPwPVPSVa/zecw2BCEnBwVS2GbrmgzxFUOqW9dk4TCW'),
+ ('', '$2a$12$k42ZFHFWqBp3vWli.nIn8uYyIkbvYRvodzbfbK18SSsY.CsIQPlxO'),
+ ('a', '$2a$06$m0CrhHm10qJ3lXRY.5zDGO3rS2KdeeWLuGmsfGlMfOxih58VYVfxe'),
+ ('a', '$2a$08$cfcvVd2aQ8CMvoMpP2EBfeodLEkkFJ9umNEfPD18.hUF62qqlC/V.'),
+ ('a', '$2a$10$k87L/MF28Q673VKh8/cPi.SUl7MU/rWuSiIDDFayrKk/1tBsSQu4u'),
+ ('a', '$2a$12$8NJH3LsPrANStV6XtBakCez0cKHXVxmvxIlcz785vxAIZrihHZpeS'),
+ ('abc', '$2a$06$If6bvum7DFjUnE9p2uDeDu0YHzrHM6tf.iqN8.yx.jNN1ILEf7h0i'),
+ ('abc', '$2a$08$Ro0CUfOqk6cXEKf3dyaM7OhSCvnwM9s4wIX9JeLapehKK5YdLxKcm'),
+ ('abc', '$2a$10$WvvTPHKwdBJ3uk0Z37EMR.hLA2W6N9AEBhEgrAOljy2Ae5MtaSIUi'),
+ ('abc', '$2a$12$EXRkfkdmXn2gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q'),
+ ('abcdefghijklmnopqrstuvwxyz', '$2a$06$.rCVZVOThsIa97pEDOxvGuRRgzG64bvtJ0938xuqzv18d3ZpQhstC'),
+ ('abcdefghijklmnopqrstuvwxyz', '$2a$08$aTsUwsyowQuzRrDqFflhgekJ8d9/7Z3GV3UcgvzQW3J5zMyrTvlz.'),
+ ('abcdefghijklmnopqrstuvwxyz', '$2a$10$fVH8e28OQRj9tqiDXs1e1uxpsjN0c7II7YPKXua2NAKYvM6iQk7dq'),
+ ('abcdefghijklmnopqrstuvwxyz', '$2a$12$D4G5f18o7aMMfwasBL7GpuQWuP3pkrZrOAnqP.bmezbMng.QwJ/pG'),
+ ('~!@#$%^&*() ~!@#$%^&*()PNBFRD', '$2a$06$fPIsBO8qRqkjj273rfaOI.HtSV9jLDpTbZn782DC6/t7qT67P6FfO'),
+ ('~!@#$%^&*() ~!@#$%^&*()PNBFRD', '$2a$08$Eq2r4G/76Wv39MzSX262huzPz612MZiYHVUJe/OcOql2jo4.9UxTW'),
+ ('~!@#$%^&*() ~!@#$%^&*()PNBFRD', '$2a$10$LgfYWkbzEvQ4JakH7rOvHe0y8pHKF9OaFgwUZ2q7W2FFZmZzJYlfS'),
+ ('~!@#$%^&*() ~!@#$%^&*()PNBFRD', '$2a$12$WApznUOJfkEGSmYRfnkrPOr466oFDCaj4b6HY3EXGvfxm43seyhgC'),
+ )
+ negative_identify = (
+ #other hashes
+ '!gAwTx2l6NADI',
+ '$6$rounds=123456$asaltof16chars..$BtCwjqMJGx5hrJhZywWvt0RLE8uZ4oPwc',
+ '$1$dOHYPKoP$tnxS1T8Q6VVn3kpV8cN6ox',
+ )
+ invalid_identify = (
+ #unsupported version
+ "$2b$12$EXRkfkdmXn!gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q",
+ #bad char in otherwise correct hash
+ "$2a$12$EXRkfkdmXn!gzds2SSitu.MW9.gAVqa9eLS1//RYtYCmB1eLHg.9q",
+ )
+
+ #NOTE: BCrypt backend tests stored in test_security_bcrypt
+else:
+ BCryptTest = None
+
+#=========================================================
+#utils
+#=========================================================
+class UtilsTest(TestCase):
+ "test util funcs and core class behavior"
+
+ def test_has_salt(self):
+ "check CryptAlgorithm.has_salt property works"
+
+ #make sure property function works at class level, not instance level
+ self.assertEqual(UnsaltedAlg.has_salt, False)
+ self.assertEqual(SaltedAlg.has_salt, True)
+
+ #make sure property function works at instance level too
+ self.assertEqual(UnsaltedAlg().has_salt, False)
+ self.assertEqual(SaltedAlg().has_salt, True)
+
+#=========================================================
+#CryptContext
+#=========================================================
+
+CryptContext = pwhash.CryptContext
+
+class CryptContextTest(TestCase):
+ "test CryptContext object's behavior"
+
+ #=========================================================
+ #0 constructor
+ #=========================================================
+ def test_00_constructor(self):
+ "test CryptContext constructor using classes"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+
+ #parse
+ a, b, c = cc
+ self.assertIsInstance(a, UnsaltedAlg)
+ self.assertIsInstance(b, SaltedAlg)
+ self.assertIsInstance(c, SampleAlg)
+
+ def test_01_constructor(self):
+ "test CryptContext constructor using instances"
+ #create crypt context
+ a = UnsaltedAlg()
+ b = SaltedAlg()
+ c = SampleAlg()
+ cc = CryptContext([a,b,c])
+
+ #verify elements
+ self.assertEquals(list(cc), [a, b, c])
+
+ #=========================================================
+ #1 list getters
+ #=========================================================
+ def test_10_getitem(self):
+ "test CryptContext.__getitem__[idx]"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ #verify len
+ self.assertEquals(len(cc), 3)
+
+ #verify getitem
+ self.assertEquals(cc[0], a)
+ self.assertEquals(cc[1], b)
+ self.assertEquals(cc[2], c)
+ self.assertEquals(cc[-1], c)
+ self.assertRaises(IndexError, cc.__getitem__, 3)
+
+ def test_11_index(self):
+ "test CryptContext.index(elem)"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ d = SampleAlg()
+
+ self.assertEquals(cc.index(a), 0)
+ self.assertEquals(cc.index(b), 1)
+ self.assertEquals(cc.index(c), 2)
+ self.assertEquals(cc.index(d), -1)
+
+ def test_12_contains(self):
+ "test CryptContext.__contains__(elem)"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ d = SampleAlg()
+
+ self.assertEquals(a in cc, True)
+ self.assertEquals(b in cc, True)
+ self.assertEquals(c in cc, True)
+ self.assertEquals(d in cc, False)
+
+ #=========================================================
+ #2 list setters
+ #=========================================================
+ def test_20_setitem(self):
+ "test CryptContext.__setitem__"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ d = SampleAlg()
+ self.assertIsNot(c, d)
+ e = pwhash.Md5Crypt()
+
+ #check baseline
+ self.assertEquals(list(cc), [a, b, c])
+
+ #replace 0 w/ d should raise error (SampleAlg already in list)
+ self.assertRaises(KeyError, cc.__setitem__, 0, d)
+ self.assertEquals(list(cc), [a, b, c])
+
+ #replace 0 w/ e
+ cc[0] = e
+ self.assertEquals(list(cc), [e, b, c])
+
+ #replace 2 w/ d
+ cc[2] = d
+ self.assertEquals(list(cc), [e, b, d])
+
+ #replace -1 w/ c
+ cc[-1] = c
+ self.assertEquals(list(cc), [e, b, c])
+
+ #replace -2 w/ d should raise error
+ self.assertRaises(KeyError, cc.__setitem__, -2, d)
+ self.assertEquals(list(cc), [e, b, c])
+
+ def test_21_append(self):
+ "test CryptContext.__setitem__"
+ cc = CryptContext([UnsaltedAlg])
+ a, = cc
+ b = SaltedAlg()
+ c = SampleAlg()
+ d = SampleAlg()
+
+ self.assertEquals(list(cc), [a])
+
+ #try append
+ cc.append(b)
+ self.assertEquals(list(cc), [a, b])
+
+ #and again
+ cc.append(c)
+ self.assertEquals(list(cc), [a, b, c])
+
+ #try append dup
+ self.assertRaises(KeyError, cc.append, d)
+ self.assertEquals(list(cc), [a, b, c])
+
+ def test_20_insert(self):
+ "test CryptContext.insert"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ d = SampleAlg()
+ self.assertIsNot(c, d)
+ e = pwhash.Md5Crypt()
+ f = pwhash.Sha512Crypt()
+ g = pwhash.UnixCrypt()
+
+ #check baseline
+ self.assertEquals(list(cc), [a, b, c])
+
+ #inserting d at 0 should raise error (SampleAlg already in list)
+ self.assertRaises(KeyError, cc.insert, 0, d)
+ self.assertEquals(list(cc), [a, b, c])
+
+ #insert e at start
+ cc.insert(0, e)
+ self.assertEquals(list(cc), [e, a, b, c])
+
+ #insert f at end
+ cc.insert(-1, f)
+ self.assertEquals(list(cc), [e, a, b, f, c])
+
+ #insert g at end
+ cc.insert(5, g)
+ self.assertEquals(list(cc), [e, a, b, f, c, g])
+
+ #=========================================================
+ #3 list dellers
+ #=========================================================
+ def test_30_remove(self):
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ d = SampleAlg()
+ self.assertIsNot(c, d)
+
+ self.assertEquals(list(cc), [a, b, c])
+
+ self.assertRaises(ValueError, cc.remove, d)
+ self.assertEquals(list(cc), [a, b, c])
+
+ cc.remove(a)
+ self.assertEquals(list(cc), [b, c])
+
+ self.assertRaises(ValueError, cc.remove, a)
+ self.assertEquals(list(cc), [b, c])
+
+ def test_31_discard(self):
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ d = SampleAlg()
+ self.assertIsNot(c, d)
+
+ self.assertEquals(list(cc), [a, b, c])
+
+ self.assertEquals(cc.discard(d), False)
+ self.assertEquals(list(cc), [a, b, c])
+
+ self.assertEquals(cc.discard(a), True)
+ self.assertEquals(list(cc), [b, c])
+
+ self.assertEquals(cc.discard(a), False)
+ self.assertEquals(list(cc), [b, c])
+
+ #=========================================================
+ #4 list composition
+ #=========================================================
+
+ def test_40_add(self, lsc=False):
+ "test CryptContext + list"
+ #build and join cc to list
+ a = UnsaltedAlg()
+ b = SaltedAlg()
+ c = SampleAlg()
+ cc = CryptContext([a, b, c])
+ ls = [pwhash.Md5Crypt, pwhash.Sha512Crypt]
+ if lsc:
+ ls = CryptContext(ls)
+ cc2 = cc + ls
+
+ #verify types
+ self.assertIsInstance(cc, CryptContext)
+ self.assertIsInstance(cc2, CryptContext)
+ self.assertIsInstance(ls, CryptContext if lsc else list)
+
+ #verify elements
+ self.assertIsNot(cc, ls)
+ self.assertIsNot(cc, cc2)
+ self.assertIsNot(ls, cc2)
+
+ #verify cc
+ a, b, c = cc
+ self.assertIsInstance(a, UnsaltedAlg)
+ self.assertIsInstance(b, SaltedAlg)
+ self.assertIsInstance(c, SampleAlg)
+
+ #verify ls
+ d, e = ls
+ if lsc:
+ self.assertIsInstance(d, pwhash.Md5Crypt)
+ self.assertIsInstance(e, pwhash.Sha512Crypt)
+ else:
+ self.assertIs(d, pwhash.Md5Crypt)
+ self.assertIs(e, pwhash.Sha512Crypt)
+
+ #verify cc2
+ a2, b2, c2, d2, e2 = cc2
+ self.assertIs(a2, a)
+ self.assertIs(b2, b)
+ self.assertIs(c2, c)
+ if lsc:
+ self.assertIs(d2, d)
+ self.assertIs(e2, e)
+ else:
+ self.assertIsInstance(d2, pwhash.Md5Crypt)
+ self.assertIsInstance(e2, pwhash.Sha512Crypt)
+
+ def test_41_add(self):
+ "test CryptContext + CryptContext"
+ self.test_40_add(lsc=True)
+
+ def test_42_iadd(self, lsc=False):
+ "test CryptContext += list"
+ #build and join cc to list
+ a = UnsaltedAlg()
+ b = SaltedAlg()
+ c = SampleAlg()
+ cc = CryptContext([a, b, c])
+ ls = [pwhash.Md5Crypt, pwhash.Sha512Crypt]
+ if lsc:
+ ls = CryptContext(ls)
+
+ #baseline
+ self.assertEquals(list(cc), [a, b, c])
+ self.assertIsInstance(cc, CryptContext)
+ self.assertIsInstance(ls, CryptContext if lsc else list)
+ if lsc:
+ d, e = ls
+ self.assertIsInstance(d, pwhash.Md5Crypt)
+ self.assertIsInstance(e, pwhash.Sha512Crypt)
+
+ #add
+ cc += ls
+
+ #verify types
+ self.assertIsInstance(cc, CryptContext)
+ self.assertIsInstance(ls, CryptContext if lsc else list)
+
+ #verify elements
+ self.assertIsNot(cc, ls)
+
+ #verify cc
+ a2, b2, c2, d2, e2 = cc
+ self.assertIs(a2, a)
+ self.assertIs(b2, b)
+ self.assertIs(c2, c)
+ if lsc:
+ self.assertIs(d2, d)
+ self.assertIs(e2, e)
+ else:
+ self.assertIsInstance(d2, pwhash.Md5Crypt)
+ self.assertIsInstance(e2, pwhash.Sha512Crypt)
+
+ #verify ls
+ d, e = ls
+ if lsc:
+ self.assertIsInstance(d, pwhash.Md5Crypt)
+ self.assertIsInstance(e, pwhash.Sha512Crypt)
+ else:
+ self.assertIs(d, pwhash.Md5Crypt)
+ self.assertIs(e, pwhash.Sha512Crypt)
+
+ def test_43_iadd(self):
+ "test CryptContext += CryptContext"
+ self.test_42_iadd(lsc=True)
+
+ def test_44_extend(self):
+ a = UnsaltedAlg()
+ b = SaltedAlg()
+ c = SampleAlg()
+ cc = CryptContext([a, b, c])
+ ls = [pwhash.Md5Crypt, pwhash.Sha512Crypt]
+
+ cc.extend(ls)
+
+ a2, b2, c2, d2, e2 = cc
+ self.assertIs(a2, a)
+ self.assertIs(b2, b)
+ self.assertIs(c2, c)
+ self.assertIsInstance(d2, pwhash.Md5Crypt)
+ self.assertIsInstance(e2, pwhash.Sha512Crypt)
+
+ self.assertRaises(KeyError, cc.extend, [pwhash.Sha512Crypt ])
+ self.assertRaises(KeyError, cc.extend, [pwhash.Sha512Crypt() ])
+
+ #=========================================================
+ #5 basic crypt interface
+ #=========================================================
+ def test_50_resolve(self):
+ "test CryptContext.resolve()"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ self.assertEquals(cc.resolve('unsalted'), a)
+ self.assertEquals(cc.resolve('salted'), b)
+ self.assertEquals(cc.resolve('sample'), c)
+ self.assertEquals(cc.resolve('md5-crypt'), None)
+
+ self.assertEquals(cc.resolve(['unsalted']), a)
+ self.assertEquals(cc.resolve(['md5-crypt']), None)
+ self.assertEquals(cc.resolve(['unsalted', 'salted', 'md5-crypt']), b)
+
+ def test_51_identify(self):
+ "test CryptContext.identify"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ for crypt in (a, b, c):
+ h = crypt.encrypt("test")
+ self.assertEquals(cc.identify(h, resolve=True), crypt)
+ self.assertEquals(cc.identify(h), crypt.name)
+
+ self.assertEquals(cc.identify('$1$232323123$1287319827', resolve=True), None)
+ self.assertEquals(cc.identify('$1$232323123$1287319827'), None)
+
+ #make sure "None" is accepted
+ self.assertEquals(cc.identify(None), None)
+
+ def test_52_encrypt_and_verify(self):
+ "test CryptContext.encrypt & verify"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ #check encrypt/id/verify pass for all algs
+ for crypt in (a, b, c):
+ h = cc.encrypt("test", alg=crypt.name)
+ self.assertEquals(cc.identify(h, resolve=True), crypt)
+ self.assertEquals(cc.verify('test', h), True)
+ self.assertEquals(cc.verify('notest', h), False)
+
+ #check default alg
+ h = cc.encrypt("test")
+ self.assertEquals(cc.identify(h, resolve=True), c)
+
+ #check verify using algs
+ self.assertEquals(cc.verify('test', h, alg='sample'), True)
+ self.assertEquals(cc.verify('test', h, alg='salted'), False)
+
+ def test_53_encrypt_salting(self):
+ "test CryptContext.encrypt salting options"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+ self.assert_(c.has_salt)
+
+ h = cc.encrypt("test")
+ self.assertEquals(cc.identify(h, resolve=True), c)
+
+ h2 = cc.encrypt("test", h)
+ self.assertEquals(cc.identify(h2, resolve=True), c)
+ self.assertNotEquals(h2, h)
+
+ h3 = cc.encrypt("test", h, keep_salt=True)
+ self.assertEquals(cc.identify(h3, resolve=True), c)
+ self.assertEquals(h3, h)
+
+ def test_54_verify_empty(self):
+ "test CryptContext.verify allows hash=None"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ self.assertEquals(cc.verify('xxx', None), False)
+ for crypt in cc:
+ self.assertEquals(cc.verify('xxx', None, alg=crypt.name), False)
+
+#XXX: haven't decided if this should be part of protocol
+## def test_55_verify_empty_secret(self):
+## "test CryptContext.verify allows secret=None"
+## cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+## h = cc.encrypt("test")
+## self.assertEquals(cc.verify(None,h), False)
+
+ #=========================================================
+ #6 crypt-enhanced list interface
+ #=========================================================
+ def test_60_getitem(self):
+ "test CryptContext.__getitem__[algname]"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ #verify getitem
+ self.assertEquals(cc['unsalted'], a)
+ self.assertEquals(cc['salted'], b)
+ self.assertEquals(cc['sample'], c)
+ self.assertRaises(KeyError, cc.__getitem__, 'md5-crypt')
+
+ def test_61_get(self):
+ "test CryptContext.get(algname)"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ #verify getitem
+ self.assertEquals(cc.get('unsalted'), a)
+ self.assertEquals(cc.get('salted'), b)
+ self.assertEquals(cc.get('sample'), c)
+ self.assertEquals(cc.get('md5-crypt'), None)
+
+ def test_62_index(self):
+ "test CryptContext.index(algname)"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+
+ #verify getitem
+ self.assertEquals(cc.index('unsalted'), 0)
+ self.assertEquals(cc.index('salted'), 1)
+ self.assertEquals(cc.index('sample'), 2)
+ self.assertEquals(cc.index('md5-crypt'), -1)
+
+ def test_63_contains(self):
+ "test CryptContext.__contains__(algname)"
+ #create crypt context
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ self.assertEquals('salted' in cc, True)
+ self.assertEquals('unsalted' in cc, True)
+ self.assertEquals('sample' in cc, True)
+ self.assertEquals('md5-crypt' in cc, False)
+
+ def test_64_keys(self):
+ "test CryptContext.keys()"
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ self.assertEquals(cc.keys(), ['unsalted', 'salted', 'sample'])
+
+ def test_65_remove(self):
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ self.assertEquals(list(cc), [a, b, c])
+
+ self.assertRaises(KeyError, cc.remove, 'md5-crypt')
+ self.assertEquals(list(cc), [a, b, c])
+
+ cc.remove('unsalted')
+ self.assertEquals(list(cc), [b, c])
+
+ self.assertRaises(KeyError, cc.remove, 'unsalted')
+ self.assertEquals(list(cc), [b, c])
+
+ def test_66_discard(self):
+ cc = CryptContext([UnsaltedAlg, SaltedAlg, SampleAlg])
+ a, b, c = cc
+
+ self.assertEquals(list(cc), [a, b, c])
+
+ self.assertEquals(cc.discard('md5-crypt'), False)
+ self.assertEquals(list(cc), [a, b, c])
+
+ self.assertEquals(cc.discard('unsalted'), True)
+ self.assertEquals(list(cc), [b, c])
+
+ self.assertEquals(cc.discard('unsalted'), False)
+ self.assertEquals(list(cc), [b, c])
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#quick access functions
+#=========================================================
+class QuickAccessTest(TestCase):
+ "test quick access functions"
+
+ crypt_cases = [ UnixCryptTest, Md5CryptTest, Sha256CryptTest]
+ if BCryptTest:
+ crypt_cases.append(BCryptTest)
+ crypt_cases.extend([ Sha512CryptTest ])
+
+ def test_00_identify(self):
+ "test pwhash.identify()"
+ identify = pwhash.identify
+ for cc in self.crypt_cases:
+ name = cc.alg.name
+ for _, hash in cc.positive_knowns:
+ self.assertEqual(identify(hash), name)
+ for _, hash in cc.negative_knowns:
+ self.assertEqual(identify(hash), name)
+ for hash in cc.negative_identify:
+ self.assertNotEqual(identify(hash), name)
+ for hash in cc.invalid_identify:
+ self.assertEqual(identify(hash), None)
+
+ def test_01_verify(self):
+ "test pwhash.verify()"
+ verify = pwhash.verify
+ for cc in self.crypt_cases:
+ name = cc.alg.name
+ for secret, hash in cc.positive_knowns[:3]:
+ self.assert_(verify(secret, hash))
+ self.assert_(verify(secret, hash, alg=name))
+ for secret, hash in cc.negative_knowns[:3]:
+ self.assert_(not verify(secret, hash))
+ self.assert_(not verify(secret, hash, alg=name))
+ for hash in cc.invalid_identify[:3]:
+ #context should raise ValueError because can't be identified
+ self.assertRaises(ValueError, verify, secret, hash)
+
+ def test_02_encrypt(self):
+ "test pwhash.encrypt()"
+ identify = pwhash.identify
+ verify = pwhash.verify
+ encrypt = pwhash.encrypt
+ for cc in self.crypt_cases:
+ alg = cc.alg.name
+ s = 'test'
+ h = encrypt(s, alg=alg)
+ self.assertEqual(identify(h), alg)
+ self.assertEqual(verify(s, h), True)
+ h2 = encrypt(s, h)
+ self.assertEqual(identify(h2), alg)
+ self.assertEqual(verify(s, h2, alg=alg), True)
+
+ def test_03_legacy(self):
+ "test legacy pwhash quick access funcs"
+ with catch_warnings(record=True) as wmsgs:
+ warnings.filterwarnings("always")
+
+ h = pwhash.encrypt_secret('test', alg='md5-crypt')
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'encrypt_secret' is deprecated, use 'bps.security.pwhash.encrypt' instead",
+ filename=__file__,
+ )
+
+ self.assertEqual(pwhash.identify_secret(h), 'md5-crypt')
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'identify_secret' is deprecated, use 'bps.security.pwhash.identify' instead",
+ filename=__file__,
+ )
+
+ self.assertEqual(pwhash.verify_secret('test', h), True)
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'verify_secret' is deprecated, use 'bps.security.pwhash.verify' instead",
+ filename=__file__,
+ )
+
+ self.assertEqual(pwhash.verify_secret('notest', h), False)
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'verify_secret' is deprecated, use 'bps.security.pwhash.verify' instead",
+ filename=__file__,
+ )
+
+ h2 = pwhash.encrypt_secret('test', h)
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'encrypt_secret' is deprecated, use 'bps.security.pwhash.encrypt' instead",
+ filename=__file__,
+ )
+
+ self.assertEqual(pwhash.identify_secret(h2), 'md5-crypt')
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'identify_secret' is deprecated, use 'bps.security.pwhash.identify' instead",
+ filename=__file__,
+ )
+
+ self.assertEqual(pwhash.verify_secret('test', h2, alg="md5-crypt"), True)
+ self.assertWarningEquals(wmsgs.pop(),
+ message="bps.security.pwhash: function 'verify_secret' is deprecated, use 'bps.security.pwhash.verify' instead",
+ filename=__file__,
+ )
+
+ self.assert_(not wmsgs)
+
+ def test_04_default_context(self):
+ "test pwhash.default_context contents"
+ dc = pwhash.default_context
+ for case in self.crypt_cases:
+ self.assert_(case.alg.name in dc)
+
+ last = 'sha512-crypt'
+ self.assertEqual(dc.keys()[-1], last)
+ h = dc.encrypt("test")
+ self.assertEqual(dc.identify(h), last)
+ self.assertEqual(dc.verify('test', h, alg=last), True)
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_stream.py b/bps/tests/test_stream.py
new file mode 100644
index 0000000..daa3eab
--- /dev/null
+++ b/bps/tests/test_stream.py
@@ -0,0 +1,33 @@
+"""tests for bps.stream -- (c) Assurance Technologies 2003-2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os.path
+#site
+#pkg
+from bps import stream
+from bps.stream import BT
+from bps.meta import Params as ak
+#module
+from bps.tests.utils import TestCase
+
+#=========================================================
+#
+#=========================================================
+
+#TODO: test MUCH MORE of stream
+class SourceTypeTest(TestCase):
+
+ def test_get_source_type(self):
+ self.check_function_results(stream.get_input_type, [
+ ak(BT.RAW, ""),
+
+ #TODO: many more test cases!
+
+ ])
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_text.py b/bps/tests/test_text.py
new file mode 100644
index 0000000..5b5d90c
--- /dev/null
+++ b/bps/tests/test_text.py
@@ -0,0 +1,927 @@
+"""tests for bps.text -- (c) Assurance Technologies 2003-2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os.path
+#site
+#pkg
+from bps.text import EnglishInflector, condense, asbool, clean_filename, \
+ split_condense, fmt_has_field, get_fmt_fields, parse_fmt_field, \
+ parse_fmt_string
+from bps.unstable import ellipsize
+from bps.meta import Params as ak
+#module
+from bps.tests.utils import TestCase
+#=========================================================
+#
+#=========================================================
+class ParseTest(TestCase):
+ condense_cases = [
+ (None, None),
+ ("",""),
+ (" ", ""),
+ ("a", "a"),
+ ("a\r\n", "a"),
+ (" a", "a"),
+ (" a", "a"),
+ ("a ", "a"),
+ ("a ", "a"),
+ (" a ", "a"),
+ (" a b ", "a b"),
+ (" aaa bbb ", "aaa bbb"),
+ (" aaa bbb", "aaa bbb"),
+ (" a a ", "a a"),
+ (" asas asdas ", "asas asdas"),
+ ("asas asdas", "asas asdas"),
+ (" asas asdas ", "asas asdas"),
+ ("\t asas \r\n asdas \n", "asas asdas"),
+ ]
+ condense_other = [
+ ("", "xyz", ""),
+ ("xy", "xyz", ""),
+ ("xayyybz", "xyz", "axb"),
+ ("xayyybz", " xyz", "a b"),
+ (". .. a .. d .. c ..", " .", "a d c"),
+ (". .. a .. d .. c ..", ". ", "a.d.c"),
+
+ #make sure regexp escaping works
+ ("x--[[-y]-]---z", "[-]", "x[y[z"),
+ ]
+
+ def test_condense(self):
+ for i,o in self.condense_cases:
+ self.assertEqual(condense(i), o)
+ def test_condense_other(self):
+ for i,c,o in self.condense_other:
+ r = condense(i, c)
+ self.assertEqual(r, o, "case %r: got %r, expected %r" % ((i, c), r, o))
+
+ sc_cases = [
+ ak([], None),
+ ak([''], ''),
+ ak([], '', empty="strip"),
+ ak(['a'], "a"),
+ ak(['a'], " a "),
+ ak(['a b'], " a b"),
+ ak(['a','b'], " a , b"),
+ ak(['a','','b'], " a ,, b"),
+ ak(['a','','b', ''], " a , , b,"),
+ ak(['a','b'], " a , , b,", empty="strip"),
+ ak(['a','c ; d','b ;; b'], " a , c ; d , b ;; b,", empty="strip"),
+ ak(['a','c ; d','b','b'], " a , c ; d , b ;; b,", sep=[';;', ','], empty="strip"),
+
+ #bug - char in sep occurs in strip chars, was causing sep to be lost
+ ak(['a', 'b', '', 'c', 'd'], "a\n b \n , c \t \n d", sep=['\n', ','])
+ ]
+ def test_split_condense(self):
+ self.check_function_results(split_condense, self.sc_cases)
+
+ asbool_cases = [
+ ('yes', True),
+ (' y ', True),
+ ('y', False, True),
+ ('y', True, True),
+
+ ('no', False),
+ ('n', True, False),
+ ('n', True, False),
+
+ (None, None),
+ (None, False, False),
+ ('', None),
+ ('null', None),
+ ('null', None, None),
+ ('null', False, False),
+ ('null', True, True),
+ ]
+
+ def test_asbool(self):
+ for elem in self.asbool_cases:
+ if len(elem) == 2:
+ i, o = elem
+ self.assertEqual(asbool(i), o)
+ else:
+ i, d, o = elem
+ self.assertEqual(asbool(i, d), o)
+ self.assertEqual(asbool(i, default=d), o)
+ self.assertRaises(ValueError, asbool, "not a bool")
+
+ cleanfn_cases = [
+ #row format: (expected_result, *args, **kwds)
+
+ #
+ #check safe preset
+ #
+
+ #random data
+ ak("c def ____ ___", "/a/b/c def ::!% ***"),
+ ak("c def", "/a/b/c def ::!% ***", safe_char=''),
+ ak("_.._sbin run", "../../sbin run"),
+ ak("sbin run", "../../sbin run", safe_char=' '),
+
+ #
+ #check clean preset
+ #
+
+ #random data
+ ak("c def", "/a/b/c def ::!% ***", preset='clean'),
+ ak("c def", "/a/b/c def ::!% ***", safe_char='', preset='clean'),
+ ak("sbin run", "../../sbin run", preset='clean'),
+ ak("sbin run", "../../sbin run", safe_char=' ', preset='clean'),
+
+ #
+ #check paranoid preset
+ #
+
+ #random data
+ ak("c_def", "/a/b/c def", preset="paranoid"),
+ ak("x_y_z_123", "% .. / / .. $#^& *(x)[]/ y\\!!! z 123",preset="paranoid"),
+
+ #
+ #check other presets
+ #
+## ak("/a/b/c", " / a / b / c ::\\!%", preset="posix-path", safe=""),
+## ak("/a/b/c", "/a/b/c", dialect="posix-path"),
+ ak("_.._sbin run _this_ _ this", "../../sbin run [this] & this", preset="excel_sheet"),
+
+ #
+ #default should be honored for None and badset
+ #
+ ak(None, None), #the default default is None
+ ak("xxx", None, "xxx"), #custom default is honored
+ ak("xxx", ".", "xxx"),
+ ak("xxx", "..", "xxx"),
+
+ #
+ #should strip absolute paths entirely
+ #
+ ak("name", "/a/b/c/name"), #absolute posix path
+ ak("name", "xxx:\\bbb\\ccc\\name"), #absolute dos path
+ ak("name", "\\\\bbb\\ccc\\name"), #absolute win network path
+
+ #
+ #should clean path-like chars (slashes, etc)
+ #
+ ak("_x_y_z run", "../x/y/z run"),
+ ak("x_y_z__", "x\\y\\z%%"),
+ ak("x_y_z__", "x\\y\\z$$"),
+ ak("_ProgramFiles__EvilApp.exe", "%ProgramFiles%\\EvilApp.exe"),
+
+ #
+ #should remove badset entirely
+ #
+ ak(None, ""),
+ ak(None, " "),
+ ak(None, "."),
+ ak(None, ".."),
+ ak(None, "..."),
+ ak(None, " !.!!.! ", safe_char=""),
+
+ #
+ #should strip dots/spaces
+ #
+ ak("x y z", "... .. x y z ..."),
+
+ #
+ #shouldn't allow unsafe chars to sneak into safe_chars
+ #
+ ak("xy__z", "xy%!z"),
+ ak("xyz", "xy%!z", safe_char="%"),
+
+ #
+ #test safe_char mapping
+ #
+ ak("_--y-z_", "%!&y&z%", safe_char={"default": '_', "&!": "-"}),
+ ak("_d-y-z_", "%d&y&z%", safe_char={"default": "_", "&": "-"}),
+
+ #
+ #ext_list testing
+ #
+ ak("a", "a", ext_list=""), #should strip all extension
+ ak("a", "a.b", ext_list=""),
+
+ ak("a", "a", ext_list=[]), #should strip all extensions
+ ak("a", "a.b", ext_list=[]),
+
+ ak("a.b", "a", ext_list=".b"), #should enforce '.b' extension
+ ak("a.b", "a.b", ext_list=".b"),
+ ak("a.b", "a.c", ext_list=".b"),
+
+ ak("a.b", "a", ext_list=".b:.c"), #should enforce '.b' or '.c', using ':' sep
+ ak("a.b", "a.b", ext_list=".b:.c"),
+ ak("a.c", "a.c", ext_list=".b:.c"),
+ ak("a.b", "a.d", ext_list=".b:.c"),
+
+ ak("a.b", "a", ext_list=".b;.c"), #should enforce '.b' or '.c', using ';' sep
+ ak("a.b", "a.b", ext_list=".b;.c"),
+ ak("a.c", "a.c", ext_list=".b;.c"),
+ ak("a.b", "a.d", ext_list=".b:.c"),
+
+ ak("a.b", "a", ext_list=[".b",".c"]), #should enforce '.b' or '.c', using list
+ ak("a.b", "a.b", ext_list=[".b",".c"]),
+ ak("a.c", "a.c", ext_list=[".b",".c"]),
+ ak("a.b", "a.d", ext_list=".b:.c"),
+
+ ak("a", "a", ext_list=".b:"), #should allow empty or '.b'
+ ak("a.b", "a.b", ext_list=".b:"),
+ ak("a.b", "a.c", ext_list=".b:"),
+
+ ak("a.c", "a", "x.c", ext_list=".b:.c"), #should promote default to front
+ ak("a.b", "a.b", "x.c", ext_list=".b:.c"),
+ ak("a.c", "a.c", "x.c", ext_list=".b:.c"),
+ ak("a.c", "a.d", "x.c", ext_list=".b:.c"),
+
+ ak("a.b", "a", "x.d", ext_list=".b:.c"), #should ignore default
+ ak("a.b", "a.d", "x.d", ext_list=".b:.c"),
+ ak("a.c", "a.c", "x.d", ext_list=".b:.c"),
+ ak("a.b", "a.d", "x.d", ext_list=".b:.c"),
+ ]
+ def test_cleanfn(self):
+ self.check_cases(clean_filename, self.cleanfn_cases)
+
+ #TODO: replace w/ check_function_results()
+ def check_cases(self, func, cases):
+ "helper for running through function call cases"
+ for elem in cases:
+ correct = elem.args[0]
+ result = func(*elem.args[1:], **elem.kwds)
+ self.assertEqual(result, correct,
+ "error for case %s, got %r, expected %r" % (elem.render(1), result, correct)
+ )
+
+#=========================================================
+#formatting
+#=========================================================
+S = os.path.sep
+
+class MiscTest(TestCase):
+
+ def test_ellipsize(self):
+ self.check_function_results(ellipsize, [
+ #too short
+ ak("abc", "abc", 3),
+ ak("...", "abcd", 3),
+ ak("...", "abcd", 3, "<"),
+ ak("...", "abcd", 3, "^"),
+
+ #right
+ ak("", "", 6),
+ ak("abc", "abc", 6),
+ ak("abcdef", "abcdef", 6),
+ ak("abc...", "abcdefghi", 6),
+
+ #left
+ ak("", "", 6, "<"),
+ ak("abc", "abc", 6, "<"),
+ ak("abcdef", "abcdef", 6, "<"),
+ ak("...ghi", "abcdefghi", 6, "<"),
+ ak("...jkl", "abcdefghijkl", 6, "<"),
+
+ #center
+ ak("", "", 6, "^"),
+ ak("abc", "abc", 6, "^"),
+ ak("abcdef", "abcdef", 6, "^"),
+ ak("a...hi", "abcdefghi", 6, "^"),
+ ak("a...kl", "abcdefghijkl", 6, "^"),
+
+ #custom char
+ ak("abc!!!", "abcdefghi", 6, ellipsis="!!!"),
+
+ #left / smart
+ ak("...ghijkl", "abcdefghijkl", 9, "<", mode="smart"),
+ ak("... hijkl", "abcdef hijkl", 9, "<", mode="smart"),
+ ak("... ijkl", "abcdefg ijkl", 9, "<", mode="smart"),
+ ak("... l", "abcdefghij l", 9, "<", mode="smart"),
+ ak("... l", "abcdefghij l", 9, "<", mode="smart", window=5),
+ ak("...ghij l", "abcdefghij l", 9, "<", mode="smart", window=4),
+
+ #right / plain
+ ak("abc...", "abcdefghijkl", 6),
+ ak("a c...", "a cdefghijkl", 6),
+ ak("a"+S+"c...", "a"+S+"cdefghijkl", 6),
+
+ #right / smart
+ ak("abc...", "abcdefghijkl", 6, mode="smart"),
+ ak("a ...", "a cdefghijkl", 6, mode="smart"),
+ ak("a" + S + "c...", "a" + S + "cdefghijkl", 6, mode="smart"),
+
+ #right / filepath
+ ak("abc...", "abcdefghijkl", 6, mode="filepath"),
+ ak("a c...", "a cdefghijkl", 6, mode="filepath"),
+ ak("a/...", "a"+S+"cdefghijkl", 6, mode="filepath"),
+
+ ])
+
+#=========================================================
+#inflection
+#=========================================================
+class EnglishInflectorTest(TestCase):
+ #=========================================================
+ #setup
+ #=========================================================
+ def setUp(self):
+ self.inf = EnglishInflector()
+
+ #standard pairs to test
+ pairs = [
+ #various random words
+ ('money', 'money'),
+ ('cow', 'cows'),
+ ('user', 'users'),
+ ('matrix', 'matrices'),
+ ('array', 'arrays'),
+ ('baby', 'babies'),
+ ('permission', 'permissions'),
+ ('fez', 'fezzes'),
+ ('pez', 'pez'),
+ ('fetus', 'fetuses'),
+
+ #from medicred
+ ('certification', 'certifications'),
+ ('policy', 'policies'),
+ ('product', 'products'),
+ ('contract', 'contracts'),
+ ('attachment', 'attachments'),
+ ('cert', 'certs'),
+ ('entry', 'entries'),
+ ('license', 'licenses'),
+ ('affiliation', 'affiliations'),
+ ('record', 'records'),
+
+ #from other jobs
+ ('loaf','loaves'),
+
+ #from python_inflector - http://www.bermi.org/inflector/download
+ ("search" , "searches"),
+ ("switch" , "switches"),
+ ("fix" , "fixes"),
+ ("box" , "boxes"),
+ ("process" , "processes"),
+ ("address" , "addresses"),
+ ("case" , "cases"),
+ ("stack" , "stacks"),
+ ("wish" , "wishes"),
+ ("fish" , "fish"),
+
+ ("category" , "categories"),
+ ("query" , "queries"),
+ ("ability" , "abilities"),
+ ("agency" , "agencies"),
+ ("movie" , "movies"),
+
+ ("archive" , "archives"),
+
+ ("index" , "indices"),
+
+ ("wife" , "wives"),
+ ("safe" , "saves"),
+ ("half" , "halves"),
+
+ ("move" , "moves"),
+
+ ("salesperson" , "salespeople"),
+ ("person" , "people"),
+
+ ("spokesman" , "spokesmen"),
+ ("man" , "men"),
+ ("woman" , "women"),
+
+ ("basis" , "bases"),
+ ("diagnosis" , "diagnoses"),
+
+ ("datum" , "data"),
+ ("medium" , "media"),
+ ("analysis" , "analyses"),
+
+ ("node_child" , "node_children"),
+ ("child" , "children"),
+
+ ("experience" , "experiences"),
+ ("day" , "days"),
+
+ ("comment" , "comments"),
+ ("foobar" , "foobars"),
+ ("newsletter" , "newsletters"),
+
+ ("old_news" , "old_news"),
+ ("news" , "news"),
+
+ ("series" , "series"),
+ ("species" , "species"),
+
+ ("quiz" , "quizzes"),
+
+ ("perspective" , "perspectives"),
+
+ ("ox" , "oxen"),
+ ("photo" , "photos"),
+ ("buffalo" , "buffaloes"),
+ ("tomato" , "tomatoes"),
+ ("dwarf" , "dwarves"),
+ ("elf" , "elves"),
+ ("information" , "information"),
+ ("equipment" , "equipment"),
+ ("bus" , "buses"),
+ ("status" , "statuses"),
+ ("mouse" , "mice"),
+
+ ("louse" , "lice"),
+ ("house" , "houses"),
+ ("octopus" , "octopi"),
+ ("virus" , "viri"),
+ ("alias" , "aliases"),
+ ("portfolio" , "portfolios"),
+
+ ("vertex" , "vertices"),
+ ("matrix" , "matrices"),
+
+ ("axis" , "axes"),
+ ("testis" , "testes"),
+ ("crisis" , "crises"),
+
+ ("rice" , "rice"),
+ ("shoe" , "shoes"),
+
+ ("horse" , "horses"),
+ ("prize" , "prizes"),
+ ("edge" , "edges"),
+ ]
+
+ #various prefixes
+ prefixes = [
+ '',
+ 'the ',
+ 'man-',
+ 'the baby-',
+ 'the kinda-slow ',
+ 'the kinda-slow baby-',
+ ]
+
+ #=========================================================
+ #test base singularize & pluralize behavior
+ #=========================================================
+ def test_empty(self):
+ inf = self.inf
+ self.assertEqual(inf.pluralize(None), '')
+ self.assertEqual(inf.singularize(None), '')
+ self.assertEqual(inf.pluralize(''), '')
+ self.assertEqual(inf.singularize(''), '')
+
+ def test_uncountable(self):
+ for word in self.inf.uncountable_words:
+ self.check_pair(word, word)
+
+ def test_irregular(self):
+ for singular, plural in self.inf.irregular_plurals.iteritems():
+ self.check_pair(singular, plural)
+
+ def test_std(self):
+ for singular, plural in self.pairs:
+ self.check_pair(singular, plural)
+
+ #=========================================================
+ #test prefix handling
+ #=========================================================
+ def test_prefixes(self):
+ inf = self.inf
+ for singular, plural in self.pairs:
+ for prefix in self.prefixes:
+ self.check_pair(prefix + singular, prefix + plural)
+
+ #TODO: test caps preservation
+
+ def test_countof(self):
+ inf = self.inf
+ singular = "cow"
+ plural = "cows"
+ self.assertEqual(inf.countof(0, singular), "0 " + plural)
+ self.assertEqual(inf.countof(1, singular), "1 " + singular)
+ self.assertEqual(inf.countof(2, singular), "2 " + plural)
+ self.assertEqual(inf.countof(100, singular), "100 " + plural)
+
+ #=========================================================
+ #test articles
+ #=========================================================
+ oneof_cases = [
+
+ #soft H rule (the exception)
+ ("hourglass", "an hourglass"),
+
+ #hard H rule
+ ("horse", "a horse"),
+ ("hoe", "a hoe"),
+ ("house", "a house"),
+
+ #exceptions to the vowel rule
+ ("university", "a university"), #soft U
+ ("unicorn", "a unicorn"), #soft U
+
+ #normal vowels
+ ("avian", "an avian"),
+ ("avian planet", "an avian planet"), #catches a normalization bug
+ ("umbrella", "an umbrella"),
+
+ #normal consonants
+ ("car", "a car"),
+ ]
+ def test_oneof(self):
+ inf = self.inf
+ for input, output in self.oneof_cases:
+ result = inf.oneof(input)
+ self.assertEqual(result, output)
+
+ #=========================================================
+ #test ordinals
+ #=========================================================
+ ordinal_cases = [
+ (1, "1st"),
+ (2, "2nd"),
+ (3, "3rd"),
+ (5, "5th"),
+ (199, "199th"),
+ (1042, "1042nd")
+ ]
+ def test_ordinals(self):
+ inf = self.inf
+ self.assertRaises(ValueError, inf.ordinal, -1)
+ self.assertRaises(ValueError, inf.ordinal, 0)
+ for input, output in self.ordinal_cases:
+ result = inf.ordinal(input)
+ self.assertEqual(result, output)
+
+ #=========================================================
+ #helpers
+ #=========================================================
+ def check_pair(self, singular, plural):
+ "check a given pair translated back and forth"
+ self.check_pluralize(singular, plural)
+ self.check_singularize(plural, singular)
+
+ def check_pluralize(self, singular, plural):
+ test = self.inf.pluralize(singular)
+ self.assertEqual(test, plural, "Plural of %r is %r, not %r" % (singular, plural, test))
+
+ #TODO: alg isn't idempotent yet
+## test = self.inf.pluralize(plural)
+## self.assertEqual(test, plural, "Plural %r mishandled as %r" % (plural, test))
+
+ def check_singularize(self, plural, singular):
+ test = self.inf.singularize(plural)
+ self.assertEqual(test, singular, "Singular of %r is %r, not %r" % (plural, singular, test))
+
+ #=========================================================
+ #EOC
+ #=========================================================
+
+#=========================================================
+#format introspection tests
+#=========================================================
+class FormatTest(TestCase):
+
+ #TODO: test parse_fmt_string
+ #TODO: test that render_format() works
+
+ def test_parse_fmt_field(self):
+ #detect bug under 2.5 where we get 'None' back
+ self.check_parse_fmt_field("d","d")
+
+ #detect nested attr mode
+ self.check_parse_fmt_field("1[{2}]", 1, (False,"{2}"))
+ self.check_parse_fmt_field("1.{2}", 1, (True,"{2}"))
+
+ #check dup attrs raises error
+ h, t = parse_fmt_field("1..x")
+ self.assertEquals(h, 1, "head:")
+ self.assertRaises(ValueError, tuple, t)
+ #ValueError: Empty attribute in format string
+
+ #allow weird chars (this is what py26 does)
+ self.check_parse_fmt_field("1\x00", '1\x00')
+ self.check_parse_fmt_field("1.\x00", 1, (True,"\x00"))
+ self.check_parse_fmt_field("1[\x00]", 1, (False,"\x00"))
+
+ #not sure what right thing to do here is,
+ #but this is what py26 does
+ self.check_parse_fmt_field("1{2}", "1{2}")
+
+ def check_parse_fmt_field(self, source, head, *tail):
+ h, t = parse_fmt_field(source)
+ self.assertEquals(h,head,"head:")
+ self.assertIsNot(t,None,"tail:") #should always be iter
+ self.assertEquals(tuple(t),tail,"tail:")
+
+ def test_get_fmt_fields(self):
+ self.check_function_results(get_fmt_fields, [
+ (set([0, 'a', 'b', 'c', 'd']), '{0.1:{c}d} {a[{b}]} {d}'),
+
+ #this is what py2.6 does, so I guess it's right..
+ (set([0,1,2,'a{b}']), '{0} {1.{2}} {a{b}}'),
+ ])
+
+ def test_fmt_has_field(self):
+ self.check_function_results(fmt_has_field,[
+ #check numbers
+ (True, "{0} {1} {a:s}", 0),
+ (True, "{0} {1.{2}} {a:s} {b:{c}d}", 1),
+ (True, "{0} {1.{2}} {a:s} {b:{c}d}", 2),
+
+ #check letters
+ (True, "{0} {a:s}", 'a'),
+ (True, "{0} {1} {a:s} {b:{c}d}", 'b'),
+ (True, "{0} {1} {a:s} {b:{c}d}", 'c'),
+
+ #check stringified numbers
+ (False, "{0} {1} {b:d}", '0'),
+ (False, "{0} {1} {b:d}", '1'),
+ (False, "{0} {1} {b:d}", '2'),
+
+ #check missing numbers
+ (False, "{0} {1} {b:d}", 2),
+
+ #check missing letters
+ (False, "{0} {1} {a:s} {b:d}", 'x'),
+ (False, "{0} {1} {a:s} {b:{c}d}", 'd'),
+ ])
+
+#=========================================================
+#email
+#=========================================================
+from bps.unstable import parse_email_addr, compile_email_addr, validate_email_parts, norm_email_addr
+
+class ParseEmailTest(TestCase):
+ "test parse_email_addr()"
+
+ #=========================================================
+ #parse_email_addr
+ #=========================================================
+
+ #addrs that should always parse
+ valid_addrs = [
+ #check simple addrs & chars
+ ("abc@def", None, "abc", "def"),
+ ("abc@def", None, "abc", "def"),
+ ('abc+def@369.live.com', None, 'abc+def', '369.live.com'),
+ (u'Pel\xe9@live.com', None, u'Pel\xe9', u'live.com'),
+
+ #check name parser
+ ("Name <abc@def>", "Name", "abc", "def"),
+ ("John Jackson <abc@def>", "John Jackson", "abc", "def"),
+ ('"John Jackson" <abc@def>', "John Jackson", "abc", "def"),
+ ("'John Jackson' <abc@def>", "John Jackson", "abc", "def"),
+ ("N@me <abc@def>", "N@me", "abc", "def"), #this is questionable
+
+ #check periods in local part
+ ("a.b.c@def", None, "a.b.c","def"),
+
+ #check periods in domain
+ ("abc@def.com", None, "abc", "def.com"),
+ ("abc@def.com.", None, "abc", "def.com."),
+ ("abc@def.abc.com", None, "abc", "def.abc.com"),
+
+ #check hyphens in domain
+ ("abc@def-ghi", None, "abc", "def-ghi"),
+ ("abc@def-ghi.xmas-fun.", None, "abc", "def-ghi.xmas-fun."),
+ ]
+
+ #addrs that require strip=True to parse
+ strip_addrs = [
+ #should parse space between parts & at ends
+ (" user @ example.com ", None, "user","example.com"),
+
+ #should get space w/in brackets
+ ("Jeff Harris < user@example.com >", "Jeff Harris", "user","example.com"),
+
+ #should condense name part
+ (" Jeff Harris< user @ example.com >", "Jeff Harris", "user","example.com"),
+ ]
+
+ #addrs that require strict=False to parse
+ relaxed_addrs = [
+ #source, name, local, domain
+
+ #there only be one '@'
+ ("A@b@c@example.com", None, "A@b@c", "example.com"), # only one @ is allowed outside quotations marks
+ #NOTE: the fact that this parses as A@b@c / example.com, not A / b@c@example.com, is a border case whose behavior is not guaranteed
+
+ #local part can't have periods at start, end, or doubled
+ ("Abc.@example.com", None, "Abc.", "example.com"),
+ (" user. @ example.com ", None, "user.", "example.com"),
+ (" .user @ example.com ", None, ".user", "example.com"),
+ ("Abc..123@example.com", None, "Abc..123", "example.com"),
+ (" user..x @ example.com ", None, "user..x", "example.com"),
+
+ #local part can't have []
+ ("user[xxx]@def.eu", None, "user[xxx]","def.eu"),
+
+ #domain part can't have []
+ ("user@def[xxx].eu", None, "user","def[xxx].eu"),
+
+ #domain part can't have period at start, or doubled
+ ("user@.def.eu", None, "user",".def.eu"),
+ ("user@def..eu", None, "user","def..eu"),
+
+ #domain part can't have hypen at start or end of element
+ ("user@-def", None, "user", "-def"),
+ ("user@abc.-def", None, "user", "abc.-def"),
+ ("user@def-", None, "user", "def-"),
+ ("user@def-.ghi", None, "user", "def-.ghi"),
+
+ #invalid attrs (when not in unicode)
+ ('Pel\x01@live.com', None, 'Pel\x01', 'live.com'),
+ ('Pel@liv\x02.com', None, 'Pel', 'liv\x02.com'),
+ ]
+
+ #addrs that will always be rejected
+ invalid_addrs = [
+ #must at least have local & domain parts
+ " @ ",
+ "l@ ",
+ "@d",
+
+ #must have matching <> in correct spot
+ "n <l@d",
+ "n l@d>",
+ "n <l@d> x",
+ "<n> l@d",
+ "n> l@d",
+
+ #must have @
+ "Abc.example.com",
+ "jimmy abc.example.com",
+
+ #always invalid attrs
+ "xyz<>@example.com",
+ ]
+
+ #addrs that should all parse as empty addresses
+ empty_addrs = [
+ None,
+ "",
+ " \t ",
+ " <>",
+ "'' < > ",
+ ]
+
+ #test addrs that require clarify=True to parse
+ clarify_addrs = [
+ ("steven <jimmy at well dot net>", "steven", "jimmy","well.net"),
+ ("jimmy at well dot net", None, "jimmy","well.net"),
+ ("jimmy (at) well (dot) net", None, "jimmy","well.net"),
+ ("jimmy (at)well(dot) net", None, "jimmy","well.net"),
+ ("jimmy [at] well [dot] net", None, "jimmy","well.net"),
+ ]
+
+ def test_parse_valid(self):
+ "test parse_email_addr() with valid addresses"
+ for addr, name, local, domain in self.valid_addrs:
+ result = parse_email_addr(addr, strip=False)
+ self.assertEquals(result, (name,local,domain))
+
+ def test_parse_strip(self):
+ "test parse_email_addr() with valid addresses that require strip=True"
+ for addr, name, local, domain in self.strip_addrs:
+ self.assertRaises(ValueError, parse_email_addr, addr, strip=False)
+ result = parse_email_addr(addr)
+ self.assertEquals(result, (name,local,domain))
+
+ def test_parse_relaxed(self):
+ "test parse_email_addr() with valid addresses that require strict=False"
+ for addr, name, local, domain in self.relaxed_addrs:
+ self.assertRaises(ValueError, parse_email_addr, addr)
+ result = parse_email_addr(addr, strict=False)
+ self.assertEquals(result, (name,local,domain))
+
+ def test_parse_invalid(self):
+ "test parse_email_addr() with invalid addrs"
+ for addr in self.invalid_addrs:
+ self.assertRaises(ValueError, parse_email_addr, addr, strict=False)
+ self.assertRaises(ValueError, parse_email_addr, addr, strict=False, clarify=True)
+
+ def test_parse_clarify(self):
+ "test parse_email_addr() with valid addresses that require clarify=True"
+ for addr, name, local, domain in self.clarify_addrs:
+ self.assertRaises(ValueError, parse_email_addr, addr)
+ result = parse_email_addr(addr, clarify=True)
+ self.assertEquals(result, (name,local,domain))
+
+ def test_parse_empty(self):
+ "test parse_email_addr() with empty strings"
+ for value in self.empty_addrs:
+ self.assertRaises(ValueError, parse_email_addr, value)
+ result = parse_email_addr(value, allow_empty=True)
+ self.assertEquals(result,(None,None,None))
+
+class ValidateEmailTest(TestCase):
+ "test validate_email_parts()"
+
+ valid_parts = [
+ ("loc", "dom"),
+ ("loc","dom"),
+
+ ("a.b","dom"),
+ ("a.b.c","dom"),
+ ("ab+c","dom"),
+ ("ab-c","dom"),
+
+ ("loc","dom.dom"),
+ ("loc","dom.dom."),
+ ("loc","dom-ghi"),
+ ("loc","3com.com"),
+ ]
+
+ relaxed_parts = [
+ ("loc.", "dom"),
+ (".loc", "dom"),
+ ("loc..loc", "dom"),
+ ("loc loc", "dom"),
+
+ ("loc",".dom"),
+ ("loc","dom..dom"),
+ ("loc","dom-"),
+ ("loc","dom-.dom"),
+ ("loc","-dom"),
+ ("loc","dom.-dom"),
+ ]
+
+ invalid_parts = [
+ ("", "dom"),
+ ("loc", ""),
+ ]
+
+ def test_validate_valid(self):
+ "test validate_email_parts() against valid tuples"
+ n = None
+ for l,d in self.valid_parts:
+ validate_email_parts(n,l,d)
+
+ def test_validate_relaxed(self):
+ "test validate_email_parts() against valid tuples that require strict=False"
+ n = None
+ for l,d in self.relaxed_parts:
+ self.assertRaises(ValueError, validate_email_parts,n,l,d)
+ validate_email_parts(n,l,d, strict=False)
+
+ def test_validate_invalid(self):
+ "test validate_email_parts() against invalid tuples"
+ n = None
+ for l,d in self.invalid_parts:
+ self.assertRaises(ValueError, validate_email_parts,n,l,d)
+ self.assertRaises(ValueError, validate_email_parts,n,l,d, strict=False)
+
+class NormEmailTest(TestCase):
+ "test norm_email_addr()"
+
+ valid_addrs = [
+ ("user@local","user@local"),
+ (" user @ local ","user@local"),
+ ("<user@local>","user@local"),
+
+ ("Name J<user@local>",'"Name J" <user@local>'),
+ (" ' Name J ' <user@local>",'"Name J" <user@local>'),
+ ]
+
+ clarify_addrs =[
+ ("joe at cell dot net","joe@cell.net"),
+ ("joe (at) cell.net","joe@cell.net"),
+ ("joe (at) cell (dot) net","joe@cell.net"),
+ ]
+
+ relaxed_addrs = [
+ ("user..name@local", "user..name@local"),
+ ]
+
+ invalid_addrs = [
+ "user",
+ "user\x01@local",
+ ]
+
+ def test_norm_valid(self):
+ "test norm_email_addr() with valid addrs"
+ for value, real in self.valid_addrs:
+ result = norm_email_addr(value)
+ self.assertEquals(result, real)
+
+ def test_norm_relaxed(self):
+ "test norm_email_addr() with valid addrs which require strict=False"
+ for value, real in self.relaxed_addrs:
+ self.assertRaises(ValueError, norm_email_addr, value)
+ result = norm_email_addr(value, strict=False)
+ self.assertEquals(result, real)
+
+ def test_norm_invalid(self):
+ "test norm_email_addr() with invalid addrs"
+ for value in self.invalid_addrs:
+ self.assertRaises(ValueError, norm_email_addr, value)
+
+ def test_norm_clarify(self):
+ "test norm_email_addr() with obfucated addrs"
+ for value, real in self.clarify_addrs:
+ self.assertRaises(ValueError, norm_email_addr, value)
+ result = norm_email_addr(value, clarify=True)
+ self.assertEquals(result, real)
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_text_format.py b/bps/tests/test_text_format.py
new file mode 100644
index 0000000..ec7b10a
--- /dev/null
+++ b/bps/tests/test_text_format.py
@@ -0,0 +1,1118 @@
+"""tests for bps.text._string_format.
+
+Most of these tests are adapted from the python source,
+to make sure our custom implementation passes all the
+tests the real format() has to pass.
+"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import sys
+from functools import partial
+#site
+#pkg
+import bps.text.patch_format
+import bps.text._string_format as tsf
+#module
+from bps.types import stub
+from bps.meta import Params as ak
+from bps.tests.utils import TestCase
+#=========================================================
+#
+#=========================================================
+
+string = stub(Formatter=tsf.Formatter)
+
+#=========================================================
+#custom string.format tests
+#=========================================================
+class BaseClassTest(TestCase):
+ def setUp(self):
+ self.formatter = tsf.Formatter()
+
+ def test_formatter(self, format=None):
+ if format is None:
+ format = self.formatter.format
+ self.check_function_results(format, [
+ ak("1",
+ "{a}", a=1),
+ ak("1 2",
+ "{0} {a}", 1, a=2),
+ ak("This is a test of } 3e8 hex 3 a 200000{",
+ "This is a test of }} {0:x} {x} {y[2]} {2[2]} {1:5n}{{",
+ 1000, 200000, 'grag', x='hex', y=[1,2,3]),
+ ak("5 5 5 +5", "{0:n} {0: n} {0:-n} {0:+n}", 5),
+ ak("-5 -5 -5 -5", "{0:n} {0: n} {0:-n} {0:+n}", -5),
+ ])
+
+ if sys.version_info >= (2, 6):
+ def test_formatter_test(self):
+ "run test cases through python's builtin format, errors here mean test itself is wrong"
+ def wrapper(s, *a, **k):
+ return s.format(*a, **k)
+ self.test_formatter(wrapper)
+
+class StdlibTest(TestCase):
+ "this is a copy of Python 2.6.2's Formatter tests"
+
+ #from Lib/test/test_builtin line 1368
+ def test_format_builtin(self):
+ # Test the basic machinery of the format() builtin. Don't test
+ # the specifics of the various formatters
+ self.assertEqual(format(3, ''), '3')
+
+ # Returns some classes to use for various tests. There's
+ # an old-style version, and a new-style version
+ def classes_new():
+ class A(object):
+ def __init__(self, x):
+ self.x = x
+ def __format__(self, format_spec):
+ return str(self.x) + format_spec
+ class DerivedFromA(A):
+ pass
+
+ class Simple(object): pass
+ class DerivedFromSimple(Simple):
+ def __init__(self, x):
+ self.x = x
+ def __format__(self, format_spec):
+ return str(self.x) + format_spec
+ class DerivedFromSimple2(DerivedFromSimple): pass
+ return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
+
+ # In 3.0, classes_classic has the same meaning as classes_new
+ def classes_classic():
+ class A:
+ def __init__(self, x):
+ self.x = x
+ def __format__(self, format_spec):
+ return str(self.x) + format_spec
+ class DerivedFromA(A):
+ pass
+
+ class Simple: pass
+ class DerivedFromSimple(Simple):
+ def __init__(self, x):
+ self.x = x
+ def __format__(self, format_spec):
+ return str(self.x) + format_spec
+ class DerivedFromSimple2(DerivedFromSimple): pass
+ return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2
+
+ def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):
+ self.assertEqual(format(A(3), 'spec'), '3spec')
+ self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')
+ self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')
+ self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),
+ '10abcdef')
+
+ class_test(*classes_new())
+ class_test(*classes_classic())
+
+ def empty_format_spec(value):
+ # test that:
+ # format(x, '') == str(x)
+ # format(x) == str(x)
+ self.assertEqual(format(value, ""), str(value))
+ self.assertEqual(format(value), str(value))
+
+ # for builtin types, format(x, "") == str(x)
+ empty_format_spec(17**13)
+ empty_format_spec(1.0)
+ empty_format_spec(3.1415e104)
+ empty_format_spec(-3.1415e104)
+ empty_format_spec(3.1415e-104)
+ empty_format_spec(-3.1415e-104)
+ empty_format_spec(object)
+ empty_format_spec(None)
+
+ # TypeError because self.__format__ returns the wrong type
+ class BadFormatResult:
+ def __format__(self, format_spec):
+ return 1.0
+ self.assertRaises(TypeError, format, BadFormatResult(), "")
+
+ # TypeError because format_spec is not unicode or str
+ self.assertRaises(TypeError, format, object(), 4)
+ self.assertRaises(TypeError, format, object(), object())
+
+ # tests for object.__format__ really belong elsewhere, but
+ # there's no good place to put them
+ #JEC -- replaced below ##x = object().__format__('')
+ x = tsf.object_format(object(), '')
+ self.assert_(x.startswith('<object object at'))
+
+ # first argument to object.__format__ must be string
+ self.assertRaises(TypeError, partial(tsf.object_format, object()), 3)
+ self.assertRaises(TypeError, partial(tsf.object_format, object()), object())
+ self.assertRaises(TypeError, partial(tsf.object_format, object()), None)
+
+ # make sure we can take a subclass of str as a format spec
+ class DerivedFromStr(str): pass
+ self.assertEqual(format(0, DerivedFromStr('10')), ' 0')
+
+ # Lib/test/test_datetime, line 860
+## def test_format_date(self):
+## dt = self.theclass(2007, 9, 10)
+## self.assertEqual(dt.__format__(''), str(dt))
+##
+## # check that a derived class's __str__() gets called
+## class A(self.theclass):
+## def __str__(self):
+## return 'A'
+## a = A(2007, 9, 10)
+## self.assertEqual(a.__format__(''), 'A')
+##
+## # check that a derived class's strftime gets called
+## class B(self.theclass):
+## def strftime(self, format_spec):
+## return 'B'
+## b = B(2007, 9, 10)
+## self.assertEqual(b.__format__(''), str(dt))
+##
+## for fmt in ["m:%m d:%d y:%y",
+## "m:%m d:%d y:%y H:%H M:%M S:%S",
+## "%z %Z",
+## ]:
+## self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
+## self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
+## self.assertEqual(b.__format__(fmt), 'B')
+
+ # Lib/test/test_datetime, line 1169
+## def test_format_datetime(self):
+## dt = self.theclass(2007, 9, 10, 4, 5, 1, 123)
+## self.assertEqual(dt.__format__(''), str(dt))
+##
+## # check that a derived class's __str__() gets called
+## class A(self.theclass):
+## def __str__(self):
+## return 'A'
+## a = A(2007, 9, 10, 4, 5, 1, 123)
+## self.assertEqual(a.__format__(''), 'A')
+##
+## # check that a derived class's strftime gets called
+## class B(self.theclass):
+## def strftime(self, format_spec):
+## return 'B'
+## b = B(2007, 9, 10, 4, 5, 1, 123)
+## self.assertEqual(b.__format__(''), str(dt))
+##
+## for fmt in ["m:%m d:%d y:%y",
+## "m:%m d:%d y:%y H:%H M:%M S:%S",
+## "%z %Z",
+## ]:
+## self.assertEqual(dt.__format__(fmt), dt.strftime(fmt))
+## self.assertEqual(a.__format__(fmt), dt.strftime(fmt))
+## self.assertEqual(b.__format__(fmt), 'B')
+
+ # Lib/test/test_datetime, line 1827
+## def test_format(self):
+## t = self.theclass(1, 2, 3, 4)
+## self.assertEqual(t.__format__(''), str(t))
+##
+## # check that a derived class's __str__() gets called
+## class A(self.theclass):
+## def __str__(self):
+## return 'A'
+## a = A(1, 2, 3, 4)
+## self.assertEqual(a.__format__(''), 'A')
+##
+## # check that a derived class's strftime gets called
+## class B(self.theclass):
+## def strftime(self, format_spec):
+## return 'B'
+## b = B(1, 2, 3, 4)
+## self.assertEqual(b.__format__(''), str(t))
+##
+## for fmt in ['%H %M %S',
+## ]:
+## self.assertEqual(t.__format__(fmt), t.strftime(fmt))
+## self.assertEqual(a.__format__(fmt), t.strftime(fmt))
+## self.assertEqual(b.__format__(fmt), 'B')
+
+
+ #from Lib/test/test_string line 109
+ def test_formatter_class(self):
+ fmt = string.Formatter()
+ self.assertEqual(fmt.format("foo"), "foo")
+
+ self.assertEqual(fmt.format("foo{0}", "bar"), "foobar")
+ self.assertEqual(fmt.format("foo{1}{0}-{1}", "bar", 6), "foo6bar-6")
+ self.assertEqual(fmt.format("-{arg!r}-", arg='test'), "-'test'-")
+
+ # override get_value ############################################
+ class NamespaceFormatter(string.Formatter):
+ def __init__(self, namespace={}):
+ string.Formatter.__init__(self)
+ self.namespace = namespace
+
+ def get_value(self, key, args, kwds):
+ if isinstance(key, str):
+ try:
+ # Check explicitly passed arguments first
+ return kwds[key]
+ except KeyError:
+ return self.namespace[key]
+ else:
+ string.Formatter.get_value(key, args, kwds)
+
+ fmt = NamespaceFormatter({'greeting':'hello'})
+ self.assertEqual(fmt.format("{greeting}, world!"), 'hello, world!')
+
+
+ # override format_field #########################################
+ class CallFormatter(string.Formatter):
+ def format_field(self, value, format_spec):
+ return format(value(), format_spec)
+
+ fmt = CallFormatter()
+ self.assertEqual(fmt.format('*{0}*', lambda : 'result'), '*result*')
+
+
+ # override convert_field ########################################
+ class XFormatter(string.Formatter):
+ def convert_field(self, value, conversion):
+ if conversion == 'x':
+ return None
+ return super(XFormatter, self).convert_field(value, conversion)
+
+ fmt = XFormatter()
+ self.assertEqual(fmt.format("{0!r}:{0!x}", 'foo', 'foo'), "'foo':None")
+
+
+ # override parse ################################################
+ class BarFormatter(string.Formatter):
+ # returns an iterable that contains tuples of the form:
+ # (literal_text, field_name, format_spec, conversion)
+ def parse(self, format_string):
+ for field in format_string.split('|'):
+ if field[0] == '+':
+ # it's markup
+ field_name, _, format_spec = field[1:].partition(':')
+ yield '', field_name, format_spec, None
+ else:
+ yield field, None, None, None
+
+ fmt = BarFormatter()
+ self.assertEqual(fmt.format('*|+0:^10s|*', 'foo'), '* foo *')
+
+ # test all parameters used
+ class CheckAllUsedFormatter(string.Formatter):
+ def check_unused_args(self, used_args, args, kwargs):
+ # Track which arguments actuallly got used
+ unused_args = set(kwargs.keys())
+ unused_args.update(range(0, len(args)))
+
+ for arg in used_args:
+ unused_args.remove(arg)
+
+ if unused_args:
+ raise ValueError("unused arguments")
+
+ fmt = CheckAllUsedFormatter()
+ self.assertEqual(fmt.format("{0}", 10), "10")
+ self.assertEqual(fmt.format("{0}{i}", 10, i=100), "10100")
+ self.assertEqual(fmt.format("{0}{i}{1}", 10, 20, i=100), "1010020")
+ self.assertRaises(ValueError, fmt.format, "{0}{i}{1}", 10, 20, i=100, j=0)
+ self.assertRaises(ValueError, fmt.format, "{0}", 10, 20)
+ self.assertRaises(ValueError, fmt.format, "{0}", 10, 20, i=100)
+ self.assertRaises(ValueError, fmt.format, "{i}", 10, 20, i=100)
+
+ # Alternate formatting is not supported
+ self.assertRaises(ValueError, format, '', '#')
+ self.assertRaises(ValueError, format, '', '#20')
+
+ #from Lib/test/test_str, line 141
+ def test_format(self):
+ self.assertEqual(''.format(), '')
+ self.assertEqual('a'.format(), 'a')
+ self.assertEqual('ab'.format(), 'ab')
+ self.assertEqual('a{{'.format(), 'a{')
+ self.assertEqual('a}}'.format(), 'a}')
+ self.assertEqual('{{b'.format(), '{b')
+ self.assertEqual('}}b'.format(), '}b')
+ self.assertEqual('a{{b'.format(), 'a{b')
+
+ # examples from the PEP:
+ import datetime
+ self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
+ self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
+ "My name is Fred")
+ self.assertEqual("My name is {0} :-{{}}".format('Fred'),
+ "My name is Fred :-{}")
+
+ d = datetime.date(2007, 8, 18)
+ self.assertEqual("The year is {0.year}".format(d),
+ "The year is 2007")
+
+ # classes we'll use for testing
+ class C:
+ def __init__(self, x=100):
+ self._x = x
+ def __format__(self, spec):
+ return spec
+
+ class D:
+ def __init__(self, x):
+ self.x = x
+ def __format__(self, spec):
+ return str(self.x)
+
+ # class with __str__, but no __format__
+ class E:
+ def __init__(self, x):
+ self.x = x
+ def __str__(self):
+ return 'E(' + self.x + ')'
+
+ # class with __repr__, but no __format__ or __str__
+ class F:
+ def __init__(self, x):
+ self.x = x
+ def __repr__(self):
+ return 'F(' + self.x + ')'
+
+ # class with __format__ that forwards to string, for some format_spec's
+ class G:
+ def __init__(self, x):
+ self.x = x
+ def __str__(self):
+ return "string is " + self.x
+ def __format__(self, format_spec):
+ if format_spec == 'd':
+ return 'G(' + self.x + ')'
+ #jec - replaced below
+ return tsf.object_format(self, format_spec)
+
+ # class that returns a bad type from __format__
+ class H:
+ def __format__(self, format_spec):
+ return 1.0
+
+ class I(datetime.date):
+ def __format__(self, format_spec):
+ return self.strftime(format_spec)
+
+ class J(int):
+ def __format__(self, format_spec):
+ #jec -- replaced below
+ return tsf.int_format(self * 2, format_spec)
+
+
+ self.assertEqual(''.format(), '')
+ self.assertEqual('abc'.format(), 'abc')
+ self.assertEqual('{0}'.format('abc'), 'abc')
+ self.assertEqual('{0:}'.format('abc'), 'abc')
+ self.assertEqual('X{0}'.format('abc'), 'Xabc')
+ self.assertEqual('{0}X'.format('abc'), 'abcX')
+ self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
+ self.assertEqual('{1}'.format(1, 'abc'), 'abc')
+ self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
+ self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
+ self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
+ self.assertEqual('{0}'.format(-15), '-15')
+ self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
+ self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
+ self.assertEqual('{{'.format(), '{')
+ self.assertEqual('}}'.format(), '}')
+ self.assertEqual('{{}}'.format(), '{}')
+ self.assertEqual('{{x}}'.format(), '{x}')
+ self.assertEqual('{{{0}}}'.format(123), '{123}')
+ self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
+ self.assertEqual('}}{{'.format(), '}{')
+ self.assertEqual('}}x{{'.format(), '}x{')
+
+ # weird field names
+ self.assertEqual("{0[foo-bar]}".format({'foo-bar':'baz'}), 'baz')
+ self.assertEqual("{0[foo bar]}".format({'foo bar':'baz'}), 'baz')
+ self.assertEqual("{0[ ]}".format({' ':3}), '3')
+
+ self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
+ self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
+ self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
+ self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
+ self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
+ self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
+ self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')
+
+ # strings
+ self.assertEqual('{0:.3s}'.format('abc'), 'abc')
+ self.assertEqual('{0:.3s}'.format('ab'), 'ab')
+ self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
+ self.assertEqual('{0:.0s}'.format('abcdef'), '')
+ self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
+ self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
+ self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
+ self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
+ self.assertEqual('{0:x<0s}'.format('result'), 'result')
+ self.assertEqual('{0:x<5s}'.format('result'), 'result')
+ self.assertEqual('{0:x<6s}'.format('result'), 'result')
+ self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
+ self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
+ self.assertEqual('{0: <7s}'.format('result'), 'result ')
+ self.assertEqual('{0:<7s}'.format('result'), 'result ')
+ self.assertEqual('{0:>7s}'.format('result'), ' result')
+ self.assertEqual('{0:>8s}'.format('result'), ' result')
+ self.assertEqual('{0:^8s}'.format('result'), ' result ')
+ self.assertEqual('{0:^9s}'.format('result'), ' result ')
+ self.assertEqual('{0:^10s}'.format('result'), ' result ')
+ self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
+ self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
+ self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)
+
+ # format specifiers for user defined type
+ self.assertEqual('{0:abc}'.format(C()), 'abc')
+
+ # !r and !s coersions
+ self.assertEqual('{0!s}'.format('Hello'), 'Hello')
+ self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
+ self.assertEqual('{0!s:15}'.format('Hello'), 'Hello ')
+ self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello ')
+ self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
+ self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
+ self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')
+
+ # test fallback to object.__format__
+ self.assertEqual('{0}'.format({}), '{}')
+ self.assertEqual('{0}'.format([]), '[]')
+ self.assertEqual('{0}'.format([1]), '[1]')
+ self.assertEqual('{0}'.format(E('data')), 'E(data)')
+ self.assertEqual('{0:^10}'.format(E('data')), ' E(data) ')
+ self.assertEqual('{0:^10s}'.format(E('data')), ' E(data) ')
+ self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
+ self.assertEqual('{0:>15s}'.format(G('data')), ' string is data')
+ self.assertEqual('{0!s}'.format(G('data')), 'string is data')
+
+ self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
+ month=8,
+ day=27)),
+ "date: 2007-08-27")
+
+ # test deriving from a builtin type and overriding __format__
+ self.assertEqual("{0}".format(J(10)), "20")
+
+
+ # string format specifiers
+ self.assertEqual('{0:}'.format('a'), 'a')
+
+ # computed format specifiers
+ self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
+ self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
+ self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
+ self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
+ self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
+
+ # test various errors
+ self.assertRaises(ValueError, '{'.format)
+ self.assertRaises(ValueError, '}'.format)
+ self.assertRaises(ValueError, 'a{'.format)
+ self.assertRaises(ValueError, 'a}'.format)
+ self.assertRaises(ValueError, '{a'.format)
+ self.assertRaises(ValueError, '}a'.format)
+ self.assertRaises(IndexError, '{0}'.format)
+ self.assertRaises(IndexError, '{1}'.format, 'abc')
+ self.assertRaises(KeyError, '{x}'.format)
+ self.assertRaises(ValueError, "}{".format)
+ self.assertRaises(ValueError, "{".format)
+ self.assertRaises(ValueError, "}".format)
+ self.assertRaises(ValueError, "abc{0:{}".format)
+ self.assertRaises(ValueError, "{0".format)
+ self.assertRaises(IndexError, "{0.}".format)
+ self.assertRaises(ValueError, "{0.}".format, 0)
+ self.assertRaises(IndexError, "{0[}".format)
+ self.assertRaises(ValueError, "{0[}".format, [])
+ self.assertRaises(KeyError, "{0]}".format)
+ self.assertRaises(ValueError, "{0.[]}".format, 0)
+ self.assertRaises(ValueError, "{0..foo}".format, 0)
+ self.assertRaises(ValueError, "{0[0}".format, 0)
+ self.assertRaises(ValueError, "{0[0:foo}".format, 0)
+ self.assertRaises(KeyError, "{c]}".format)
+ self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
+ self.assertRaises(ValueError, "{0}}".format, 0)
+ self.assertRaises(KeyError, "{foo}".format, bar=3)
+ self.assertRaises(ValueError, "{0!x}".format, 3)
+ self.assertRaises(ValueError, "{0!}".format, 0)
+ self.assertRaises(ValueError, "{0!rs}".format, 0)
+ self.assertRaises(ValueError, "{!}".format)
+ self.assertRaises(ValueError, "{:}".format)
+ self.assertRaises(ValueError, "{:s}".format)
+ self.assertRaises(ValueError, "{}".format)
+
+ # can't have a replacement on the field name portion
+ self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
+
+ # exceed maximum recursion depth
+ self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
+ self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
+ 0, 1, 2, 3, 4, 5, 6, 7)
+
+ # string format spec errors
+ self.assertRaises(ValueError, "{0:-s}".format, '')
+ self.assertRaises(ValueError, format, "", "-")
+ self.assertRaises(ValueError, "{0:=s}".format, '')
+
+ # Lib/test/test_types, line 93
+ def test_float_to_string(self):
+ def test(f, result):
+ self.assertEqual(tsf.float_format(f,'e'), result)
+ self.assertEqual('%e' % f, result)
+
+ # test all 2 digit exponents, both with __format__ and with
+ # '%' formatting
+ for i in range(-99, 100):
+ test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i))
+
+ # test some 3 digit exponents
+ self.assertEqual(tsf.float_format(1.5e100, 'e'), '1.500000e+100')
+ self.assertEqual('%e' % 1.5e100, '1.500000e+100')
+
+ self.assertEqual(tsf.float_format(1.5e101, 'e'), '1.500000e+101')
+ self.assertEqual('%e' % 1.5e101, '1.500000e+101')
+
+ self.assertEqual(tsf.float_format(1.5e-100, 'e'), '1.500000e-100')
+ self.assertEqual('%e' % 1.5e-100, '1.500000e-100')
+
+ self.assertEqual(tsf.float_format(1.5e-101, 'e'), '1.500000e-101')
+ self.assertEqual('%e' % 1.5e-101, '1.500000e-101')
+
+ # Lib/test/test_unicode, line 880
+ def test_format_unicode(self):
+ self.assertEqual(u''.format(), u'')
+ self.assertEqual(u'a'.format(), u'a')
+ self.assertEqual(u'ab'.format(), u'ab')
+ self.assertEqual(u'a{{'.format(), u'a{')
+ self.assertEqual(u'a}}'.format(), u'a}')
+ self.assertEqual(u'{{b'.format(), u'{b')
+ self.assertEqual(u'}}b'.format(), u'}b')
+ self.assertEqual(u'a{{b'.format(), u'a{b')
+
+ # examples from the PEP:
+ import datetime
+ self.assertEqual(u"My name is {0}".format(u'Fred'), u"My name is Fred")
+ self.assertEqual(u"My name is {0[name]}".format(dict(name=u'Fred')),
+ u"My name is Fred")
+ self.assertEqual(u"My name is {0} :-{{}}".format(u'Fred'),
+ u"My name is Fred :-{}")
+
+ # datetime.__format__ doesn't work with unicode
+ #d = datetime.date(2007, 8, 18)
+ #self.assertEqual("The year is {0.year}".format(d),
+ # "The year is 2007")
+
+ # classes we'll use for testing
+ class C:
+ def __init__(self, x=100):
+ self._x = x
+ def __format__(self, spec):
+ return spec
+
+ class D:
+ def __init__(self, x):
+ self.x = x
+ def __format__(self, spec):
+ return str(self.x)
+
+ # class with __str__, but no __format__
+ class E:
+ def __init__(self, x):
+ self.x = x
+ def __str__(self):
+ return u'E(' + self.x + u')'
+
+ # class with __repr__, but no __format__ or __str__
+ class F:
+ def __init__(self, x):
+ self.x = x
+ def __repr__(self):
+ return u'F(' + self.x + u')'
+
+ # class with __format__ that forwards to string, for some format_spec's
+ class G:
+ def __init__(self, x):
+ self.x = x
+ def __str__(self):
+ return u"string is " + self.x
+ def __format__(self, format_spec):
+ if format_spec == 'd':
+ return u'G(' + self.x + u')'
+ return tsf.object_format(self, format_spec)
+
+ # class that returns a bad type from __format__
+ class H:
+ def __format__(self, format_spec):
+ return 1.0
+
+ class I(datetime.date):
+ def __format__(self, format_spec):
+ return self.strftime(format_spec)
+
+ class J(int):
+ def __format__(self, format_spec):
+ return tsf.int_format(self * 2, format_spec)
+
+
+ self.assertEqual(u''.format(), u'')
+ self.assertEqual(u'abc'.format(), u'abc')
+ self.assertEqual(u'{0}'.format(u'abc'), u'abc')
+ self.assertEqual(u'{0:}'.format(u'abc'), u'abc')
+ self.assertEqual(u'X{0}'.format(u'abc'), u'Xabc')
+ self.assertEqual(u'{0}X'.format(u'abc'), u'abcX')
+ self.assertEqual(u'X{0}Y'.format(u'abc'), u'XabcY')
+ self.assertEqual(u'{1}'.format(1, u'abc'), u'abc')
+ self.assertEqual(u'X{1}'.format(1, u'abc'), u'Xabc')
+ self.assertEqual(u'{1}X'.format(1, u'abc'), u'abcX')
+ self.assertEqual(u'X{1}Y'.format(1, u'abc'), u'XabcY')
+ self.assertEqual(u'{0}'.format(-15), u'-15')
+ self.assertEqual(u'{0}{1}'.format(-15, u'abc'), u'-15abc')
+ self.assertEqual(u'{0}X{1}'.format(-15, u'abc'), u'-15Xabc')
+ self.assertEqual(u'{{'.format(), u'{')
+ self.assertEqual(u'}}'.format(), u'}')
+ self.assertEqual(u'{{}}'.format(), u'{}')
+ self.assertEqual(u'{{x}}'.format(), u'{x}')
+ self.assertEqual(u'{{{0}}}'.format(123), u'{123}')
+ self.assertEqual(u'{{{{0}}}}'.format(), u'{{0}}')
+ self.assertEqual(u'}}{{'.format(), u'}{')
+ self.assertEqual(u'}}x{{'.format(), u'}x{')
+
+ # weird field names
+ self.assertEqual(u"{0[foo-bar]}".format({u'foo-bar':u'baz'}), u'baz')
+ self.assertEqual(u"{0[foo bar]}".format({u'foo bar':u'baz'}), u'baz')
+ self.assertEqual(u"{0[ ]}".format({u' ':3}), u'3')
+
+ self.assertEqual(u'{foo._x}'.format(foo=C(20)), u'20')
+ self.assertEqual(u'{1}{0}'.format(D(10), D(20)), u'2010')
+ self.assertEqual(u'{0._x.x}'.format(C(D(u'abc'))), u'abc')
+ self.assertEqual(u'{0[0]}'.format([u'abc', u'def']), u'abc')
+ self.assertEqual(u'{0[1]}'.format([u'abc', u'def']), u'def')
+ self.assertEqual(u'{0[1][0]}'.format([u'abc', [u'def']]), u'def')
+ self.assertEqual(u'{0[1][0].x}'.format(['abc', [D(u'def')]]), u'def')
+
+ # strings
+ self.assertEqual(u'{0:.3s}'.format(u'abc'), u'abc')
+ self.assertEqual(u'{0:.3s}'.format(u'ab'), u'ab')
+ self.assertEqual(u'{0:.3s}'.format(u'abcdef'), u'abc')
+ self.assertEqual(u'{0:.0s}'.format(u'abcdef'), u'')
+ self.assertEqual(u'{0:3.3s}'.format(u'abc'), u'abc')
+ self.assertEqual(u'{0:2.3s}'.format(u'abc'), u'abc')
+ self.assertEqual(u'{0:2.2s}'.format(u'abc'), u'ab')
+ self.assertEqual(u'{0:3.2s}'.format(u'abc'), u'ab ')
+ self.assertEqual(u'{0:x<0s}'.format(u'result'), u'result')
+ self.assertEqual(u'{0:x<5s}'.format(u'result'), u'result')
+ self.assertEqual(u'{0:x<6s}'.format(u'result'), u'result')
+ self.assertEqual(u'{0:x<7s}'.format(u'result'), u'resultx')
+ self.assertEqual(u'{0:x<8s}'.format(u'result'), u'resultxx')
+ self.assertEqual(u'{0: <7s}'.format(u'result'), u'result ')
+ self.assertEqual(u'{0:<7s}'.format(u'result'), u'result ')
+ self.assertEqual(u'{0:>7s}'.format(u'result'), u' result')
+ self.assertEqual(u'{0:>8s}'.format(u'result'), u' result')
+ self.assertEqual(u'{0:^8s}'.format(u'result'), u' result ')
+ self.assertEqual(u'{0:^9s}'.format(u'result'), u' result ')
+ self.assertEqual(u'{0:^10s}'.format(u'result'), u' result ')
+ self.assertEqual(u'{0:10000}'.format(u'a'), u'a' + u' ' * 9999)
+ self.assertEqual(u'{0:10000}'.format(u''), u' ' * 10000)
+ self.assertEqual(u'{0:10000000}'.format(u''), u' ' * 10000000)
+
+ # format specifiers for user defined type
+ self.assertEqual(u'{0:abc}'.format(C()), u'abc')
+
+ # !r and !s coersions
+ self.assertEqual(u'{0!s}'.format(u'Hello'), u'Hello')
+ self.assertEqual(u'{0!s:}'.format(u'Hello'), u'Hello')
+ self.assertEqual(u'{0!s:15}'.format(u'Hello'), u'Hello ')
+ self.assertEqual(u'{0!s:15s}'.format(u'Hello'), u'Hello ')
+ self.assertEqual(u'{0!r}'.format(u'Hello'), u"u'Hello'")
+ self.assertEqual(u'{0!r:}'.format(u'Hello'), u"u'Hello'")
+ self.assertEqual(u'{0!r}'.format(F(u'Hello')), u'F(Hello)')
+
+ # test fallback to object.__format__
+ self.assertEqual(u'{0}'.format({}), u'{}')
+ self.assertEqual(u'{0}'.format([]), u'[]')
+ self.assertEqual(u'{0}'.format([1]), u'[1]')
+ self.assertEqual(u'{0}'.format(E(u'data')), u'E(data)')
+ self.assertEqual(u'{0:^10}'.format(E(u'data')), u' E(data) ')
+ self.assertEqual(u'{0:^10s}'.format(E(u'data')), u' E(data) ')
+ self.assertEqual(u'{0:d}'.format(G(u'data')), u'G(data)')
+ self.assertEqual(u'{0:>15s}'.format(G(u'data')), u' string is data')
+ self.assertEqual(u'{0!s}'.format(G(u'data')), u'string is data')
+
+ self.assertEqual("{0:date: %Y-%m-%d}".format(I(year=2007,
+ month=8,
+ day=27)),
+ "date: 2007-08-27")
+
+ # test deriving from a builtin type and overriding __format__
+ self.assertEqual("{0}".format(J(10)), "20")
+
+
+ # string format specifiers
+ self.assertEqual('{0:}'.format('a'), 'a')
+
+ # computed format specifiers
+ self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
+ self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
+ self.assertEqual("{0:.{precision}s}".format('hello world', precision=5), 'hello')
+ self.assertEqual("{0:{width}.{precision}s}".format('hello world', width=10, precision=5), 'hello ')
+ self.assertEqual("{0:{width}.{precision}s}".format('hello world', width='10', precision='5'), 'hello ')
+
+ # test various errors
+ self.assertRaises(ValueError, '{'.format)
+ self.assertRaises(ValueError, '}'.format)
+ self.assertRaises(ValueError, 'a{'.format)
+ self.assertRaises(ValueError, 'a}'.format)
+ self.assertRaises(ValueError, '{a'.format)
+ self.assertRaises(ValueError, '}a'.format)
+ self.assertRaises(IndexError, '{0}'.format)
+ self.assertRaises(IndexError, '{1}'.format, 'abc')
+ self.assertRaises(KeyError, '{x}'.format)
+ self.assertRaises(ValueError, "}{".format)
+ self.assertRaises(ValueError, "{".format)
+ self.assertRaises(ValueError, "}".format)
+ self.assertRaises(ValueError, "abc{0:{}".format)
+ self.assertRaises(ValueError, "{0".format)
+ self.assertRaises(IndexError, "{0.}".format)
+ self.assertRaises(ValueError, "{0.}".format, 0)
+ self.assertRaises(IndexError, "{0[}".format)
+ self.assertRaises(ValueError, "{0[}".format, [])
+ self.assertRaises(KeyError, "{0]}".format)
+ self.assertRaises(ValueError, "{0.[]}".format, 0)
+ self.assertRaises(ValueError, "{0..foo}".format, 0)
+ self.assertRaises(ValueError, "{0[0}".format, 0)
+ self.assertRaises(ValueError, "{0[0:foo}".format, 0)
+ self.assertRaises(KeyError, "{c]}".format)
+ self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
+ self.assertRaises(ValueError, "{0}}".format, 0)
+ self.assertRaises(KeyError, "{foo}".format, bar=3)
+ self.assertRaises(ValueError, "{0!x}".format, 3)
+ self.assertRaises(ValueError, "{0!}".format, 0)
+ self.assertRaises(ValueError, "{0!rs}".format, 0)
+ self.assertRaises(ValueError, "{!}".format)
+ self.assertRaises(ValueError, "{:}".format)
+ self.assertRaises(ValueError, "{:s}".format)
+ self.assertRaises(ValueError, "{}".format)
+
+ # can't have a replacement on the field name portion
+ self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)
+
+ # exceed maximum recursion depth
+ self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
+ self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format,
+ 0, 1, 2, 3, 4, 5, 6, 7)
+
+ # string format spec errors
+ self.assertRaises(ValueError, "{0:-s}".format, '')
+ self.assertRaises(ValueError, format, "", "-")
+ self.assertRaises(ValueError, "{0:=s}".format, '')
+
+ # test combining string and unicode
+ self.assertEqual(u"foo{0}".format('bar'), u'foobar')
+ # This will try to convert the argument from unicode to str, which
+ # will succeed
+ self.assertEqual("foo{0}".format(u'bar'), 'foobar')
+ # This will try to convert the argument from unicode to str, which
+ # will fail
+ self.assertRaises(UnicodeEncodeError, "foo{0}".format, u'\u1000bar')
+
+
+#=========================================================
+# Lib/test/test_format.py, in it's entirety
+#=========================================================
+
+import sys
+verbose = False
+have_unicode = True
+TestFailed = AssertionError
+##from test.test_support import verbose, have_unicode, TestFailed
+##import test.test_support as test_support
+import unittest
+
+##maxsize = test_support.MAX_Py_ssize_t
+maxsize = 1<<32
+
+# test string formatting operator (I am not sure if this is being tested
+# elsewhere but, surely, some of the given cases are *not* tested because
+# they crash python)
+# test on unicode strings as well
+
+overflowok = 1
+overflowrequired = 0
+
+def checkformat(formatstr, args, output=None, limit=None):
+ if verbose:
+ if output:
+ print "%s %% %s =? %s ..." %\
+ (repr(formatstr), repr(args), repr(output)),
+ else:
+ print "%s %% %s works? ..." % (repr(formatstr), repr(args)),
+ try:
+ result = formatstr % args
+ except OverflowError:
+ if not overflowok:
+ raise
+ if verbose:
+ print 'overflow (this is fine)'
+ else:
+ if overflowrequired:
+ if verbose:
+ print 'no'
+ print "overflow expected on %s %% %s" % \
+ (repr(formatstr), repr(args))
+ elif output and limit is None and result != output:
+ if verbose:
+ print 'no'
+ print "%s %% %s == %s != %s" % \
+ (repr(formatstr), repr(args), repr(result), repr(output))
+ # when 'limit' is specified, it determines how many characters
+ # must match exactly; lengths must always match.
+ # ex: limit=5, '12345678' matches '12345___'
+ # (mainly for floating point format tests for which an exact match
+ # can't be guaranteed due to rounding and representation errors)
+ elif output and limit is not None and (
+ len(result)!=len(output) or result[:limit]!=output[:limit]):
+ if verbose:
+ print 'no'
+ print "%s %% %s == %s != %s" % \
+ (repr(formatstr), repr(args), repr(result), repr(output))
+ else:
+ if verbose:
+ print 'yes'
+
+def checkboth(formatstr, *args):
+ checkformat(formatstr, *args)
+ if have_unicode:
+ checkformat(unicode(formatstr), *args)
+
+class FormatTest(unittest.TestCase):
+ def test_format(self):
+ checkboth("%.1d", (1,), "1")
+ checkboth("%.*d", (sys.maxint,1)) # expect overflow
+ checkboth("%.100d", (1,), '0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001')
+ checkboth("%#.117x", (1,), '0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001')
+ checkboth("%#.118x", (1,), '0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001')
+
+ checkboth("%f", (1.0,), "1.000000")
+ # these are trying to test the limits of the internal magic-number-length
+ # formatting buffer, if that number changes then these tests are less
+ # effective
+ checkboth("%#.*g", (109, -1.e+49/3.))
+ checkboth("%#.*g", (110, -1.e+49/3.))
+ checkboth("%#.*g", (110, -1.e+100/3.))
+
+ # test some ridiculously large precision, expect overflow
+ checkboth('%12.*f', (123456, 1.0))
+
+ # check for internal overflow validation on length of precision
+ overflowrequired = 1
+ checkboth("%#.*g", (110, -1.e+100/3.))
+ checkboth("%#.*G", (110, -1.e+100/3.))
+ checkboth("%#.*f", (110, -1.e+100/3.))
+ checkboth("%#.*F", (110, -1.e+100/3.))
+ overflowrequired = 0
+
+ # Formatting of long integers. Overflow is not ok
+ overflowok = 0
+ checkboth("%x", 10L, "a")
+ checkboth("%x", 100000000000L, "174876e800")
+ checkboth("%o", 10L, "12")
+ checkboth("%o", 100000000000L, "1351035564000")
+ checkboth("%d", 10L, "10")
+ checkboth("%d", 100000000000L, "100000000000")
+
+ big = 123456789012345678901234567890L
+ checkboth("%d", big, "123456789012345678901234567890")
+ checkboth("%d", -big, "-123456789012345678901234567890")
+ checkboth("%5d", -big, "-123456789012345678901234567890")
+ checkboth("%31d", -big, "-123456789012345678901234567890")
+ checkboth("%32d", -big, " -123456789012345678901234567890")
+ checkboth("%-32d", -big, "-123456789012345678901234567890 ")
+ checkboth("%032d", -big, "-0123456789012345678901234567890")
+ checkboth("%-032d", -big, "-123456789012345678901234567890 ")
+ checkboth("%034d", -big, "-000123456789012345678901234567890")
+ checkboth("%034d", big, "0000123456789012345678901234567890")
+ checkboth("%0+34d", big, "+000123456789012345678901234567890")
+ checkboth("%+34d", big, " +123456789012345678901234567890")
+ checkboth("%34d", big, " 123456789012345678901234567890")
+ checkboth("%.2d", big, "123456789012345678901234567890")
+ checkboth("%.30d", big, "123456789012345678901234567890")
+ checkboth("%.31d", big, "0123456789012345678901234567890")
+ checkboth("%32.31d", big, " 0123456789012345678901234567890")
+ #python 2.5 chokes on this...
+## checkboth("%d", float(big), "123456________________________", 6)
+
+ big = 0x1234567890abcdef12345L # 21 hex digits
+ checkboth("%x", big, "1234567890abcdef12345")
+ checkboth("%x", -big, "-1234567890abcdef12345")
+ checkboth("%5x", -big, "-1234567890abcdef12345")
+ checkboth("%22x", -big, "-1234567890abcdef12345")
+ checkboth("%23x", -big, " -1234567890abcdef12345")
+ checkboth("%-23x", -big, "-1234567890abcdef12345 ")
+ checkboth("%023x", -big, "-01234567890abcdef12345")
+ checkboth("%-023x", -big, "-1234567890abcdef12345 ")
+ checkboth("%025x", -big, "-0001234567890abcdef12345")
+ checkboth("%025x", big, "00001234567890abcdef12345")
+ checkboth("%0+25x", big, "+0001234567890abcdef12345")
+ checkboth("%+25x", big, " +1234567890abcdef12345")
+ checkboth("%25x", big, " 1234567890abcdef12345")
+ checkboth("%.2x", big, "1234567890abcdef12345")
+ checkboth("%.21x", big, "1234567890abcdef12345")
+ checkboth("%.22x", big, "01234567890abcdef12345")
+ checkboth("%23.22x", big, " 01234567890abcdef12345")
+ checkboth("%-23.22x", big, "01234567890abcdef12345 ")
+ checkboth("%X", big, "1234567890ABCDEF12345")
+ checkboth("%#X", big, "0X1234567890ABCDEF12345")
+ checkboth("%#x", big, "0x1234567890abcdef12345")
+ checkboth("%#x", -big, "-0x1234567890abcdef12345")
+ checkboth("%#.23x", -big, "-0x001234567890abcdef12345")
+ checkboth("%#+.23x", big, "+0x001234567890abcdef12345")
+ checkboth("%# .23x", big, " 0x001234567890abcdef12345")
+ checkboth("%#+.23X", big, "+0X001234567890ABCDEF12345")
+ checkboth("%#-+.23X", big, "+0X001234567890ABCDEF12345")
+ checkboth("%#-+26.23X", big, "+0X001234567890ABCDEF12345")
+ checkboth("%#-+27.23X", big, "+0X001234567890ABCDEF12345 ")
+ checkboth("%#+27.23X", big, " +0X001234567890ABCDEF12345")
+ # next one gets two leading zeroes from precision, and another from the
+ # 0 flag and the width
+ checkboth("%#+027.23X", big, "+0X0001234567890ABCDEF12345")
+ # same, except no 0 flag
+ checkboth("%#+27.23X", big, " +0X001234567890ABCDEF12345")
+ #python 2.5 chokes on this...
+## checkboth("%x", float(big), "123456_______________", 6)
+
+ big = 012345670123456701234567012345670L # 32 octal digits
+ checkboth("%o", big, "12345670123456701234567012345670")
+ checkboth("%o", -big, "-12345670123456701234567012345670")
+ checkboth("%5o", -big, "-12345670123456701234567012345670")
+ checkboth("%33o", -big, "-12345670123456701234567012345670")
+ checkboth("%34o", -big, " -12345670123456701234567012345670")
+ checkboth("%-34o", -big, "-12345670123456701234567012345670 ")
+ checkboth("%034o", -big, "-012345670123456701234567012345670")
+ checkboth("%-034o", -big, "-12345670123456701234567012345670 ")
+ checkboth("%036o", -big, "-00012345670123456701234567012345670")
+ checkboth("%036o", big, "000012345670123456701234567012345670")
+ checkboth("%0+36o", big, "+00012345670123456701234567012345670")
+ checkboth("%+36o", big, " +12345670123456701234567012345670")
+ checkboth("%36o", big, " 12345670123456701234567012345670")
+ checkboth("%.2o", big, "12345670123456701234567012345670")
+ checkboth("%.32o", big, "12345670123456701234567012345670")
+ checkboth("%.33o", big, "012345670123456701234567012345670")
+ checkboth("%34.33o", big, " 012345670123456701234567012345670")
+ checkboth("%-34.33o", big, "012345670123456701234567012345670 ")
+ checkboth("%o", big, "12345670123456701234567012345670")
+ checkboth("%#o", big, "012345670123456701234567012345670")
+ checkboth("%#o", -big, "-012345670123456701234567012345670")
+ checkboth("%#.34o", -big, "-0012345670123456701234567012345670")
+ checkboth("%#+.34o", big, "+0012345670123456701234567012345670")
+ checkboth("%# .34o", big, " 0012345670123456701234567012345670")
+ checkboth("%#+.34o", big, "+0012345670123456701234567012345670")
+ checkboth("%#-+.34o", big, "+0012345670123456701234567012345670")
+ checkboth("%#-+37.34o", big, "+0012345670123456701234567012345670 ")
+ checkboth("%#+37.34o", big, " +0012345670123456701234567012345670")
+ # next one gets one leading zero from precision
+ checkboth("%.33o", big, "012345670123456701234567012345670")
+ # base marker shouldn't change that, since "0" is redundant
+ checkboth("%#.33o", big, "012345670123456701234567012345670")
+ # but reduce precision, and base marker should add a zero
+ checkboth("%#.32o", big, "012345670123456701234567012345670")
+ # one leading zero from precision, and another from "0" flag & width
+ checkboth("%034.33o", big, "0012345670123456701234567012345670")
+ # base marker shouldn't change that
+ checkboth("%0#34.33o", big, "0012345670123456701234567012345670")
+ #python 2.5 chokes on this...
+## checkboth("%o", float(big), "123456__________________________", 6)
+
+ # Some small ints, in both Python int and long flavors).
+ checkboth("%d", 42, "42")
+ checkboth("%d", -42, "-42")
+ checkboth("%d", 42L, "42")
+ checkboth("%d", -42L, "-42")
+ checkboth("%d", 42.0, "42")
+ checkboth("%#x", 1, "0x1")
+ checkboth("%#x", 1L, "0x1")
+ checkboth("%#X", 1, "0X1")
+ checkboth("%#X", 1L, "0X1")
+ checkboth("%#x", 1.0, "0x1")
+ checkboth("%#o", 1, "01")
+ checkboth("%#o", 1L, "01")
+ checkboth("%#o", 0, "0")
+ checkboth("%#o", 0L, "0")
+ checkboth("%o", 0, "0")
+ checkboth("%o", 0L, "0")
+ checkboth("%d", 0, "0")
+ checkboth("%d", 0L, "0")
+ checkboth("%#x", 0, "0x0")
+ checkboth("%#x", 0L, "0x0")
+ checkboth("%#X", 0, "0X0")
+ checkboth("%#X", 0L, "0X0")
+
+ checkboth("%x", 0x42, "42")
+ checkboth("%x", -0x42, "-42")
+ checkboth("%x", 0x42L, "42")
+ checkboth("%x", -0x42L, "-42")
+ checkboth("%x", float(0x42), "42")
+
+ checkboth("%o", 042, "42")
+ checkboth("%o", -042, "-42")
+ checkboth("%o", 042L, "42")
+ checkboth("%o", -042L, "-42")
+ checkboth("%o", float(042), "42")
+
+ # Test exception for unknown format characters
+ if verbose:
+ print 'Testing exceptions'
+
+ def test_exc(formatstr, args, exception, excmsg):
+ try:
+ checkformat(formatstr, args)
+ except exception, exc:
+ if str(exc) == excmsg:
+ if verbose:
+ print "yes"
+ else:
+ if verbose: print 'no'
+ print 'Unexpected ', exception, ':', repr(str(exc))
+ except:
+ if verbose: print 'no'
+ print 'Unexpected exception'
+ raise
+ else:
+ raise TestFailed, 'did not get expected exception: %s' % excmsg
+
+ test_exc('abc %a', 1, ValueError,
+ "unsupported format character 'a' (0x61) at index 5")
+ if have_unicode:
+ test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError,
+ "unsupported format character '?' (0x3000) at index 5")
+
+ test_exc('%d', '1', TypeError, "int argument required") ##"%d format: a number is required, not str")
+ test_exc('%g', '1', TypeError, "float argument required") ##", not str")
+ test_exc('no format', '1', TypeError,
+ "not all arguments converted during string formatting")
+ test_exc('no format', u'1', TypeError,
+ "not all arguments converted during string formatting")
+ test_exc(u'no format', '1', TypeError,
+ "not all arguments converted during string formatting")
+ test_exc(u'no format', u'1', TypeError,
+ "not all arguments converted during string formatting")
+
+ class Foobar(long):
+ def __oct__(self):
+ # Returning a non-string should not blow up.
+ return self + 1
+
+ test_exc('%o', Foobar(), TypeError,
+ "expected string or Unicode object, long found")
+
+ if maxsize == 2**31-1:
+ # crashes 2.2.1 and earlier:
+ try:
+ "%*d"%(maxsize, -127)
+ except MemoryError:
+ pass
+ else:
+ raise TestFailed, '"%*d"%(maxsize, -127) should fail'
+
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_types.py b/bps/tests/test_types.py
new file mode 100644
index 0000000..8b6327b
--- /dev/null
+++ b/bps/tests/test_types.py
@@ -0,0 +1,278 @@
+"""bps.types unittest script -- (c) 2004-2009 Assurance Technologies 2003-2006"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+import os
+import warnings
+import gc
+#site
+#pkg
+from bps.tests.utils import TestCase
+#module
+#=========================================================
+#baseclass
+#=========================================================
+from bps.types import BaseClass
+class BaseClassTest(TestCase):
+
+ def test_multisuper(self):
+ "test MultipleSuperProperty handler for BaseClass"
+ buffer = []
+ class Core(BaseClass):
+ def bob(self):
+ buffer.append("core")
+
+ class Test(Core):
+ "test 1"
+ def bob(self):
+ buffer.append("test1")
+ self.__super.bob()
+ Test1 = Test
+
+ class Test(Test):
+ "test 2"
+ def bob(self):
+ buffer.append("test2")
+ self.__super.bob()
+ Test2 = Test
+
+ #check core
+ del buffer[:]
+ test0 = Core()
+ test0.bob()
+ self.assertEqual(buffer, ['core'])
+
+ #check single-class call
+ del buffer[:]
+ test1 = Test1()
+ test1.bob()
+ self.assertEqual(buffer, ['test1', 'core'])
+
+ #check multi-class call
+ #if MultipleSuperProperty fails, we'll have dups of test1 or test2 in buffer.
+ del buffer[:]
+ test2 = Test2()
+ test2.bob()
+ self.assertEqual(buffer, ['test2', 'test1', 'core'])
+
+#=========================================================
+#closeableclass
+#=========================================================
+from bps.types import CloseableClass
+class CloseableClassTest(TestCase):
+
+ def test_closed_property(self):
+ #check init state
+ c = CloseableClass()
+ self.assert_(not c.closed)
+
+ #make sure it changes
+ c.close()
+ self.assert_(c.closed)
+
+ #make sure double call is NOOP
+ c.close()
+ self.assert_(c.closed)
+
+ def test_close_on_del(self):
+ #NOTE: since this relies on GC flushing, and implicitly calling del
+ #(which CPython doesn't guarantee will happen), this test may fail.
+ #should write better way to test things.
+ d = [False]
+ def setter():
+ d[0] = True
+ c = CloseableClass()
+ c.on_close(setter)
+ del c
+ gc.collect()
+ self.assert_(d[0])
+
+ def test_cleanup(self):
+ class Test(CloseableClass):
+ x = 1
+
+ def _cleanup(self):
+ self.x += 1
+
+ #check init state
+ c = Test()
+ self.assertEquals(c.x, 1)
+
+ #make sure it's called right
+ c.close()
+ self.assertEquals(c.x, 2)
+
+ #make sure it's not double-called
+ c.close()
+ self.assertEquals(c.x, 2)
+
+ #NOTE: 'close' method not explicitly tested,
+ #as at least one of the other tests should fail
+ #if something was wrong with it
+
+ def test_close(self):
+
+ #test init state
+ c = CloseableClass()
+ self.assert_(not c.closed)
+
+ #test 'close' returns true on success
+ self.assert_(c.close())
+ self.assert_(c.closed)
+
+ #test 'close' returns false if already closed
+ self.assert_(not c.close())
+ self.assert_(c.closed)
+
+ def test_recursive_close(self):
+ c = CloseableClass()
+ c._in_closer = False
+
+ def closer():
+ self.assert_(not c._in_closer)
+ c._in_closer = True
+ try:
+ #NOTE: policy is to simply ignore recursive calls, might revise in future
+ self.assert_(not c.closed)
+ r = c.close()
+ self.assert_(not c.closed)
+ self.assertIs(r, None)
+ finally:
+ c._in_closer = False
+ c.on_close(closer)
+
+ r = c.close()
+ self.assert_(r)
+ self.assert_(c.closed)
+
+ #TODO: should decide on / test policy for what happens if on_close() / delete_on_close()
+ # is called AFTER class has been closed!
+
+ def test_on_close_func(self):
+ c = CloseableClass()
+
+ #prepare & register callback
+ d = []
+ def func():
+ d.append(1)
+ c.on_close(func)
+ self.assertEquals(d,[])
+
+ #make sure it's called right
+ c.close()
+ self.assertEquals(d,[1])
+
+ #make sure it's not double-called
+ c.close()
+ self.assertEquals(d,[1])
+
+ def test_on_close_multi_func(self):
+ c = CloseableClass()
+
+ #prepare & register two callbacks
+ d = []
+ c.on_close(d.append, 1)
+ c.on_close(d.append, 2)
+ self.assertEquals(d,[])
+
+ #make sure they're calling in LIFO order
+ c.close()
+ self.assertEquals(d,[2,1])
+
+ #make sure they're not double-called
+ c.close()
+ self.assertEquals(d,[2,1])
+
+ #XXX: if there's cyclic ref in kwds, GC will have loop
+
+ def test_on_close_func_kwds(self):
+ c = CloseableClass()
+
+ #prepare & register callback
+ d = []
+ def func(value=1):
+ d.append(value)
+ c.on_close(func, value=5)
+ self.assertEquals(d,[])
+
+ #make sure it's called right
+ c.close()
+ self.assertEquals(d,[5])
+
+ #make sure it's not double-called
+ c.close()
+ self.assertEquals(d,[5])
+
+ def test_delete_on_close(self):
+ c = CloseableClass()
+
+ #prepare & register attrs to purge
+ c.x = 1
+ c.y = 2
+ c.z = 3
+ c.delete_on_close('x','y')
+
+ #check attrs kept
+ self.assertEquals(c.x, 1)
+ self.assertEquals(c.y, 2)
+ self.assertEquals(c.z, 3)
+
+ #check purge works
+ c.close()
+ self.assertIs(c.x, None)
+ self.assertIs(c.y, None)
+ self.assertEquals(c.z, 3)
+
+ #check purge doesn't get called again (though I guess it could)
+ c.x = 5
+ c.y = 10
+ c.close()
+ self.assertEquals(c.x, 5)
+ self.assertEquals(c.y, 10)
+ self.assertEquals(c.z, 3)
+
+ def test_callback_order(self):
+ #delete_on_close & on_close calls should share same LIFO stack
+ #_cleanup() should be called last
+
+ class Test(CloseableClass):
+ x = 1
+ y = 2
+
+ def __init__(self):
+ self.buf = []
+
+ def _cleanup(self):
+ self.buf.append("cleanup")
+
+ #prepare test to check ordering of events
+ c = Test()
+ def read_x():
+ c.buf.append(c.x)
+ def read_y():
+ c.buf.append(c.y)
+
+ #_cleanup - fourth
+ c.on_close(read_x) #third
+ c.delete_on_close('x','y') #second
+ c.on_close(read_y) #first
+
+ #check init state
+ self.assertEquals(c.buf, [])
+ self.assertEquals(c.x, 1)
+ self.assertEquals(c.y, 2)
+
+ #call
+ c.close()
+ self.assertEquals(c.buf, [2,None,"cleanup"])
+ self.assertIs(c.x, None)
+ self.assertIs(c.y, None)
+
+ #=========================================================
+ #EOC
+ #=========================================================
+#=========================================================
+#EOF
+#=========================================================
diff --git a/bps/tests/test_unstable_ansi.py b/bps/tests/test_unstable_ansi.py
new file mode 100644
index 0000000..80ead52
--- /dev/null
+++ b/bps/tests/test_unstable_ansi.py
@@ -0,0 +1,344 @@
+"""bps.unstable.ansi tests"""
+#=========================================================
+#
+#=========================================================
+from bps.tests.utils import TestCase
+from bps.meta import Params as ak
+from bps.unstable.ansi import CODESET, AnsiCode, \
+ AnsiError, AnsiCommandError, AnsiParseError, \
+ parse_ansi_string
+
+#=========================================================
+#
+#=========================================================
+class AnsiCodeTest(TestCase):
+ "test AnsiCode class"
+
+ #=========================================================
+ #constants
+ #=========================================================
+ c0_good = [
+ #source=code
+ '\x00',
+ '\x01',
+ '\x02',
+ '\x03',
+ '\x04',
+ '\x05',
+ '\x06',
+ '\x07',
+ '\n',
+ ]
+
+ c1_good = [
+ #source, code
+ ('\x1bA','A'),
+ ('\x1bZ','Z'),
+ ]
+
+ icf_good = [
+ #source, code
+ ('\x1b~','~'),
+ ]
+
+ cseq_good = [
+ #source, code, argstr, **other-attrs-to-test
+
+ ak("\x1b[31;33x","x","31;33", args=(31,33)),
+
+ ak("\x1b[A","A","", args=(), offset=1),
+ ak("\x1b[1A","A","1", args=(1,), offset=1),
+ ak("\x1b[3A","A","3", args=(3,), offset=3),
+
+ ak("\x1b[m","m","", args=()),
+ ak("\x1b[31m","m","31", args=(31,)),
+ ak("\x1b[31;32;33m","m","31;32;33", args=(31,32,33)),
+
+ ak("\x1b[31!x", "!x","31"),
+ ]
+
+ bad_parse = [
+ "", #empty string not allowed
+ " ",
+ "a",
+ "abc",
+ "\x1b", #raw ESC isn't allowed
+ "\x1b\x7F", #code not in c1 or icf range
+ "\x1b[", #raw CSI isn't allowed
+ "\x1b[31~x", #'~' not a valid intermediate byte
+ "\x1b[31!31x", #'!' valid intermediate byte, but can't be interspersed w/ params
+ "\x1b[!", #not a valid code
+ ]
+
+ #source strings which should parse correctly, and are in normalized form
+ all_good = c0_good + \
+ [ x[0] for x in c1_good ] + \
+ [ x[0] for x in icf_good ] + \
+ [ x[0] for x in cseq_good ]
+
+ #source strings which should get normalized
+ all_unnormalized = [
+ ("\x1b[0;0f", "\x1b[0;0H"),
+ ]
+
+ #=========================================================
+ #parse tests
+ #=========================================================
+ def test_c0_good(self):
+ "test known good c0 codes parse"
+ codeset = CODESET.C0
+ for source in self.c0_good:
+ code = source
+ c = AnsiCode.parse(source)
+ self.assertEqual(c.codeset, codeset)
+ self.assertEqual(c.code, code)
+ self.assertEqual(repr(c), repr(AnsiCode(codeset, code)))
+
+ def test_c1_good(self):
+ "test known good c1 codes parse"
+ codeset = CODESET.C1
+ for source, code in self.c1_good:
+ c = AnsiCode.parse(source)
+ self.assertEqual(c.codeset, codeset)
+ self.assertEqual(c.code, code)
+ self.assertEqual(repr(c), repr(AnsiCode(codeset, code)))
+
+ def test_icf_good(self):
+ "test known good c1 codes parse"
+ codeset = CODESET.ICF
+ for source, code in self.icf_good:
+ c = AnsiCode.parse(source)
+ self.assertEqual(c.codeset, codeset)
+ self.assertEqual(c.code, code)
+ self.assertEqual(repr(c), repr(AnsiCode(codeset, code)))
+
+ def test_cseq_good(self):
+ "test known good cseq codes parse"
+ codeset = CODESET.CSEQ
+ for row in self.cseq_good:
+ source, code, argstr = row.args
+ c = AnsiCode.parse(source)
+ self.assertEqual(c.codeset, codeset)
+ self.assertEqual(c.code, code)
+ self.assertEqual(c.argstr, argstr)
+ for k,v in row.kwds.iteritems():
+ self.assertEqual(getattr(c,k),v)
+ self.assertEqual(repr(c), repr(AnsiCode(codeset, code, argstr=argstr)))
+
+ def test_bad(self):
+ "test known bad codes don't parse"
+ for source in self.bad_parse:
+ self.assertRaises(AnsiParseError, AnsiCode.parse, source)
+
+ #=========================================================
+ #test try-parse
+ #=========================================================
+ def test_try_parse_good(self):
+ for source in self.all_good:
+ ok, result = AnsiCode.try_parse(source)
+ self.assert_(ok)
+ self.assertIsInstance(result, AnsiCode)
+ self.assertEqual(result.render(), source)
+
+ def test_try_parse_bad(self):
+ for source in self.bad_parse:
+ ok, result = AnsiCode.try_parse(source)
+ self.assert_(not ok)
+ self.assertIsInstance(result, AnsiParseError)
+
+ #=========================================================
+ #render
+ #=========================================================
+ def test_render_good(self):
+ "test known good codes render/str like source"
+ for source in self.all_good:
+ c = AnsiCode.parse(source)
+ self.assertEquals(c.render(), source)
+ self.assertEquals(str(c), source)
+
+ def test_render_normalized(self):
+ "test known redundant codes render/str properly"
+ for source, result in self.all_unnormalized:
+ c = AnsiCode.parse(source)
+ norm = c.render()
+ self.assertEquals(norm, result)
+ self.assertEquals(str(c), source) #since this contains 'source', will render original
+ c2 = AnsiCode.parse(norm)
+ self.assertEquals(c2.render(), result)
+ self.assertEquals(str(c2), result)
+
+ #=========================================================
+ #repr
+ #=========================================================
+ def test_repr(self):
+ "test known good codes have working repr"
+ for source in self.all_good:
+ c = AnsiCode.parse(source)
+ c2 = eval(repr(c))
+ self.assertEqual(repr(c), repr(c2))
+ c2.source = source #so dicts match
+ self.assertEquals(c.__dict__, c2.__dict__)
+
+ def test_repr_normalized(self):
+ for source, result in self.all_unnormalized:
+ c = AnsiCode.parse(source)
+ c2 = eval(repr(c))
+ self.assertEqual(repr(c), repr(c2))
+ #NOTE: 'source' should have been preserved in repr
+ self.assertEquals(c2.source, source)
+ self.assertEquals(c.__dict__, c2.__dict__)
+
+ #TODO: test malformed
+
+ #=========================================================
+ #test eq
+ #=========================================================
+ def test_eq(self):
+ "test known good codes have working __eq__"
+ codeset = CODESET.C0
+ for source in self.all_good:
+ c1 = AnsiCode.parse(source)
+ for other in self.all_good:
+ c2 = AnsiCode.parse(other)
+ if other == source:
+ self.assert_(c1 == c2)
+ self.assert_(not c1 != c2)
+ else:
+ self.assert_(not c1 == c2)
+ self.assert_(c1 != c2)
+
+ #TODO: test malformed
+
+ #=========================================================
+ #xxx_code attrs
+ #=========================================================
+ def test_code_attrs(self):
+ for source in self.all_good:
+ c = AnsiCode.parse(source)
+ for cs in (CODESET.C0, CODESET.C1, CODESET.ICF, CODESET.CSEQ):
+ v = getattr(c, cs + "_code")
+ if cs == c.codeset:
+ self.assertEquals(v, c.code)
+ else:
+ self.assertIs(v,None)
+
+ #=========================================================
+ #test specific init funcs
+ #=========================================================
+
+ #=========================================================
+ #test malformed methods (kwd, is_malformed, get_malformed_reasons)
+ #=========================================================
+
+ #=========================================================
+ #eoc
+ #=========================================================
+
+#=========================================================
+#utils
+#=========================================================
+class UtilTest(TestCase):
+ "test util funcs"
+
+ # is_ansi_code
+ # is_malformed_ansi_code
+ # len_ansi_string
+ # strip_ansi_string
+
+class AnsiStripperTest(TestCase):
+ "test AnsiStripper class"
+
+#=========================================================
+#
+#=========================================================
+class ParseTest(TestCase):
+ 'test parse_ansi_string(source, rtype=list, malformed_codes="ignore")'
+
+ def test_sample_normal(self):
+ "test normal functioning"
+ text = "\x1b[34mXYZ\x1b[Dtest test\x1b(sdasda\x00asdasda\x1b~sdfsdf\n\nrwerwer"
+ result = parse_ansi_string(text)
+ self.assertEquals(result,[
+ AnsiCode('cseq','m','34'),
+ 'XYZ',
+ AnsiCode('cseq','D'),
+ 'test test',
+ AnsiCode('c1','('),
+ "sdasda",
+ AnsiCode('c0','\x00'),
+ 'asdasda',
+ AnsiCode('icf','~'),
+ 'sdfsdf\n\nrwerwer',
+ ])
+
+ def test_empty(self):
+ result = parse_ansi_string("")
+ self.assertEquals(result,[""])
+
+ def test_alpha(self):
+ result = parse_ansi_string("abc")
+ self.assertEquals(result,["abc"])
+
+ def test_1code(self):
+ result = parse_ansi_string("\x1b[X")
+ self.assertEquals(result,[AnsiCode("cseq",'X')])
+
+ def test_rtype(self):
+ "test rtype kwd"
+ text = "abc\ndef\x1b[34mghi\x1b~"
+ correct = [
+ 'abc\ndef',
+ AnsiCode('cseq','m','34'),
+ 'ghi',
+ AnsiCode('icf','~'),
+ ]
+
+ #test 'list'
+ result = parse_ansi_string(text)
+ self.assertIsInstance(result,list)
+ self.assertEquals(result, correct)
+
+ #test 'iter'
+ result = parse_ansi_string(text, rtype=iter)
+ self.assert_(hasattr(result,"next"))
+ self.assertIs(iter(result),result)
+ self.assertEquals(list(result), correct)
+
+ #test 'tuple'
+ result = parse_ansi_string(text, rtype=tuple)
+ self.assertIsInstance(result,tuple)
+ self.assertEquals(list(result), correct)
+
+ def test_sample_malformed_codes(self):
+ "test malformed_codes kwd"
+ text = "XYZ\x1b[4;Dtest test"
+
+ #try the default ("ignore")
+ result = parse_ansi_string(text)
+ self.assertEquals(result,[
+ 'XYZ',
+ '\x1b[4;D',
+ 'test test',
+ ])
+
+ #try explicit parse mode
+ result = parse_ansi_string(text, malformed_codes="parse")
+ self.assertEquals(result,[
+ 'XYZ',
+ AnsiCode(None, None, malformed="argstr contains non-integer: '4;'", source='\x1b[4;D'),
+ 'test test',
+ ])
+
+ #try strip mode
+ result = parse_ansi_string(text, malformed_codes="strip")
+ self.assertEquals(result,[
+ 'XYZ',
+ 'test test',
+ ])
+
+ #try raise-error mode
+ self.assertRaises(AnsiParseError, parse_ansi_string, text, malformed_codes="raise")
+
+#=========================================================
+#
+#=========================================================
diff --git a/bps/tests/test_warndep.py b/bps/tests/test_warndep.py
new file mode 100644
index 0000000..ba4b525
--- /dev/null
+++ b/bps/tests/test_warndep.py
@@ -0,0 +1,480 @@
+"""tests for bps.warnup -- (c) Assurance Technologies 2009"""
+#=========================================================
+#imports
+#=========================================================
+from __future__ import with_statement
+#core
+from unittest import __file__ as ut_file
+#site
+#pkg
+from bps import warndep, filepath
+from bps.error.types import ParamError
+#module
+from bps.tests.utils import TestCase, catch_warnings, __file__ as util_file
+
+def print_warnings(msgs):
+ print "warning list: %r warnings" % len(msgs)
+ for idx, msg in enumerate(msgs):
+ print "\t%d: %s" % (idx,msg)
+ print
+
+#=========================================================
+#dep func
+#=========================================================
+class DepFuncTest(TestCase):
+ "test deprecated_function decorator"
+
+ # use, name, msg, removal
+
+ def test_plain(self):
+ "test basic depfunc call"
+ @warndep.deprecated_function()
+ def myfunc(a,b=2):
+ return a*b
+ with catch_warnings(record=True) as msgs:
+ #make sure func can be called in various ways
+ self.assertEquals(myfunc(3), 6)
+ self.assertEquals(myfunc(2.5,b=3), 7.5)
+ #and fails if not called correctly
+ self.assertRaises(TypeError, myfunc)
+## print_warnings(msgs)
+ x = "bps.tests.test_warndep: function 'myfunc' is deprecated"
+ self.assert_warning(msgs.pop(0), message=x, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_removal(self):
+ "test depfunc removal kwd"
+ @warndep.deprecated_function(removal=True)
+ def myfunc1():
+ return 1
+ @warndep.deprecated_function(removal="2009-10-1")
+ def myfunc2():
+ return 2
+ with catch_warnings(record=True) as msgs:
+ myfunc1()
+ myfunc2()
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'myfunc1' is deprecated; it will be removed in the future"
+ x2 = "bps.tests.test_warndep: function 'myfunc2' is deprecated; it will be removed after 2009-10-1"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x2, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_use(self):
+ "test depfunc use kwd"
+ @warndep.deprecated_function(use="otherfunc")
+ def myfunc():
+ return 1
+ with catch_warnings(record=True) as msgs:
+ myfunc()
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'myfunc' is deprecated, use 'otherfunc' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_use_old(self):
+ "test depfunc use kwd"
+ @warndep.deprecated_function(use="otherfunc")
+ def myfunc():
+ return 1
+ with catch_warnings(record=True) as msgs:
+ myfunc()
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'myfunc' is deprecated, use 'otherfunc' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_name(self):
+ "test depfunc name kwd"
+ @warndep.deprecated_function(name="otherfunc")
+ def myfunc():
+ return 1
+ with catch_warnings(record=True) as msgs:
+ myfunc()
+ x1 = "bps.tests.test_warndep: function 'otherfunc' is deprecated"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_name_old(self):
+ "test depfunc name kwd"
+ @warndep.deprecated_function(name="otherfunc")
+ def myfunc():
+ return 1
+ with catch_warnings(record=True) as msgs:
+ myfunc()
+ x1 = "bps.tests.test_warndep: function 'otherfunc' is deprecated"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_msg(self):
+ "test depfunc msg kwd"
+ @warndep.deprecated_function(msg="help me, %(name)s")
+ def myfunc():
+ return 1
+ with catch_warnings(record=True) as msgs:
+ myfunc()
+ x1 = "bps.tests.test_warndep: help me, myfunc"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_msg2(self):
+ "test depfunc msg kwd 2"
+ @warndep.deprecated_function(msg="help me, %(mod)s.%(name)s")
+ def myfunc():
+ return 1
+ with catch_warnings(record=True) as msgs:
+ myfunc()
+ x1 = "help me, bps.tests.test_warndep.myfunc"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+def rf_01(x=1,y=2):
+ return (x,y)
+
+#NOTE: this is wrong, "name" and "use" are flipped,
+# used for unittest
+rf_02 = warndep.relocated_function("rf_01", "rf_02")
+
+class RelFuncTest(TestCase):
+ "test relocated function proxy-maker"
+
+ def test_basic_00(self):
+ "basic operation w/ explicit module path"
+ b = warndep.relocated_function("b", __name__ + ".rf_01")
+ self.assertEquals(b.__name__, "b")
+ with catch_warnings(record=True) as msgs:
+ self.assertEqual(b(5,y=3), (5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep.rf_01' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_basic_01(self):
+ "basic operation w/ explicit module path 2"
+ b = warndep.relocated_function("b", __name__ + ":rf_01")
+ self.assertEquals(b.__name__, "b")
+ with catch_warnings(record=True) as msgs:
+ self.assertEqual(b(5,y=3), (5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep.rf_01' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_basic_02(self):
+ "basic operation w/in module"
+ b = warndep.relocated_function("b", "rf_01")
+ self.assertEquals(b.__name__, "b")
+ with catch_warnings(record=True) as msgs:
+ self.assertEqual(b(5,y=3), (5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep.rf_01' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_basic_03(self):
+ "basic operation w/callable"
+ b = warndep.relocated_function("b", rf_01)
+ self.assertEquals(b.__name__, "b")
+ with catch_warnings(record=True) as msgs:
+ self.assertEqual(b(5,y=3), (5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep.rf_01' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_nonlazy(self):
+ "basic operation w/in module"
+ #FIXME: do something harser to test for sure, such as contained module.
+ b = warndep.relocated_function("b", "rf_01", lazy=False)
+ with catch_warnings(record=True) as msgs:
+ self.assertEqual(b(5,y=3), (5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep.rf_01' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_removal(self):
+ "test depfunc removal kwd"
+ f1 = warndep.relocated_function("b1", "rf_01", removal=True)
+ f2 = warndep.relocated_function("b2", "rf_01", removal="2009-10-1")
+ self.assertEquals(f1.__name__, "b1")
+ self.assertEquals(f2.__name__, "b2")
+ with catch_warnings(record=True) as msgs:
+ f1()
+ f2()
+ x1 = "bps.tests.test_warndep: function 'b1' is deprecated, use 'bps.tests.test_warndep.rf_01' instead; it will be removed in the future"
+ x2 = "bps.tests.test_warndep: function 'b2' is deprecated, use 'bps.tests.test_warndep.rf_01' instead; it will be removed after 2009-10-1"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x2, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_mistake_00_reversed(self):
+ with catch_warnings(record=True) as msgs:
+ self.assertRaises(ParamError,rf_02)
+ #^ "name and use parameters reversed"
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'rf_01' is deprecated, use 'bps.tests.test_warndep.rf_02' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_mistake_01_missing_module(self):
+ b = warndep.relocated_function("b", __name__ + "_xxx.rf_01")
+ with catch_warnings(record=True) as msgs:
+ self.assertRaises(ImportError,b)
+ #^ no such module test_warndepxxx
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep_xxx.rf_01' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_mistake_02_missing_func(self):
+ b = warndep.relocated_function("b", __name__ + ".rf_xxx")
+ with catch_warnings(record=True) as msgs:
+ self.assertRaises(AttributeError,b)
+ #^ module has no such attr rf_xxx
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep: function 'b' is deprecated, use 'bps.tests.test_warndep.rf_xxx' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_mistake_03_missing_nonlazy(self):
+ self.assertRaises(AttributeError, warndep.relocated_function, "b", __name__ + ".rf_xxx", lazy=False)
+ self.assertRaises(ImportError, warndep.relocated_function, "b", __name__ + "_xxx.rf_01", lazy=False)
+
+#=========================================================
+#dep meth
+#=========================================================
+class DepMethTest(TestCase):
+ "test deprecated_method decorator"
+
+ def test_plain(self):
+ "test basic depmeth call"
+ class Test:
+ @warndep.deprecated_method()
+ def myfunc(self,a,b=2):
+ return self,a,b
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ #make sure func can be called in various ways
+ self.assertEquals(t.myfunc(3), (t,3,2))
+ self.assertEquals(t.myfunc(2.5,b=3), (t,2.5,3))
+ #and fails if not called correctly
+ self.assertRaises(TypeError, t.myfunc)
+## print_warnings(msgs)
+ x = "bps.tests.test_warndep.Test: method 'myfunc' is deprecated"
+ self.assert_warning(msgs.pop(0), message=x, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_removal(self):
+ "test depmeth removal kwd"
+ class Test:
+ @warndep.deprecated_method(removal=True)
+ def myfunc1(self):
+ return 1
+ @warndep.deprecated_method(removal="2009-10-1")
+ def myfunc2(self):
+ return 2
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc1()
+ t.myfunc2()
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'myfunc1' is deprecated; it will be removed in the future"
+ x2 = "bps.tests.test_warndep.Test: method 'myfunc2' is deprecated; it will be removed after 2009-10-1"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x2, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_use(self):
+ "test depmeth use kwd"
+ class Test:
+ @warndep.deprecated_method(use="otherfunc")
+ def myfunc(self):
+ return 1
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc()
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'myfunc' is deprecated, use 'otherfunc' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_use_old(self):
+ "test depmeth use kwd"
+ class Test:
+ @warndep.deprecated_method(use="otherfunc")
+ def myfunc(self):
+ return 1
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc()
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'myfunc' is deprecated, use 'otherfunc' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_name(self):
+ "test depmeth name kwd"
+ class Test:
+ @warndep.deprecated_method(name="otherfunc")
+ def myfunc(self):
+ return 1
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc()
+ x1 = "bps.tests.test_warndep.Test: method 'otherfunc' is deprecated"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_name_old(self):
+ "test depmeth name kwd"
+ class Test:
+ @warndep.deprecated_method(name="otherfunc")
+ def myfunc(self):
+ return 1
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc()
+ x1 = "bps.tests.test_warndep.Test: method 'otherfunc' is deprecated"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_msg(self):
+ "test depmeth msg kwd"
+ class Test:
+ @warndep.deprecated_method(msg="help me, %(name)s")
+ def myfunc(self):
+ return 1
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc()
+ x1 = "bps.tests.test_warndep.Test: help me, myfunc"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_msg2(self):
+ "test depmeth msg kwd"
+ class Test:
+ @warndep.deprecated_method(msg="help me, %(mod)s.%(cls)s:%(name)s")
+ def myfunc(self):
+ return 1
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.myfunc()
+ x1 = "help me, bps.tests.test_warndep.Test:myfunc"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+class RelMethTest(TestCase):
+ "test relocated method proxy-maker"
+
+ def test_basic_00(self):
+ "basic operation w/ method name"
+ class Test:
+ def a(self,x=1,y=2):
+ return (self,x,y)
+ b = warndep.relocated_method("b","a")
+ self.assertEquals(Test.b.__name__, "b")
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ self.assertEqual(t.b(5,y=3), (t,5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'b' is deprecated, use 'a' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_basic_01(self):
+ "basic operation w/ method callable"
+ class Test:
+ def a(self,x=1,y=2):
+ return (self,x,y)
+ b = warndep.relocated_method("b", a)
+ self.assertEquals(Test.b.__name__, "b")
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ self.assertEqual(t.b(5,y=3), (t,5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'b' is deprecated, use 'a' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_name_detect(self):
+ "basic operation w/ name not specified"
+ class Test:
+ def a(self,x=1,y=2):
+ return (self,x,y)
+ b = warndep.relocated_method(None, "a")
+ self.assertEquals(Test.b.__name__, "<deprecated alias for 'a'>")
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ self.assertEqual(t.b(5,y=3), (t,5,3))
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'b' is deprecated, use 'a' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_removal(self):
+ "test depfunc removal kwd"
+ class Test:
+ def a(self,x=1,y=2):
+ return (self,x,y)
+ f1 = warndep.relocated_method("b1", "a", removal=True)
+ f2 = warndep.relocated_method("b2", "a", removal="2009-10-1")
+ self.assertEquals(Test.f1.__name__, "b1")
+ self.assertEquals(Test.f2.__name__, "b2")
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ t.f1()
+ t.f2()
+ x1 = "bps.tests.test_warndep.Test: method 'b1' is deprecated, use 'a' instead; it will be removed in the future"
+ x2 = "bps.tests.test_warndep.Test: method 'b2' is deprecated, use 'a' instead; it will be removed after 2009-10-1"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=__file__)
+ self.assert_warning(msgs.pop(0), message=x2, category=DeprecationWarning, filename=__file__)
+ self.assert_(not msgs)
+
+ def test_mistake_00_reversed(self):
+ class Test:
+ def a(self,x=1,y=2):
+ return (self,x,y)
+ b = warndep.relocated_method("a", "b")
+ self.assertEquals(Test.b.__name__,"a")
+ self.assertEquals(Test.a.__name__,"a")
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ self.assertRaises(ParamError, t.b)
+ #^ "name and use parameters reversed"
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'a' is deprecated, use 'b' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_mistake_01_missing_attr(self):
+ class Test:
+ b = warndep.relocated_method("b", "a")
+ self.assertEquals(Test.b.__name__,"b")
+ with catch_warnings(record=True) as msgs:
+ t = Test()
+ self.assertRaises(AttributeError,t.b)
+ #^ module has no such attr rf_xxx
+## print_warnings(msgs)
+ x1 = "bps.tests.test_warndep.Test: method 'b' is deprecated, use 'a' instead"
+ self.assert_warning(msgs.pop(0), message=x1, category=DeprecationWarning, filename=util_file)
+ self.assert_(not msgs)
+
+ def test_mistake_02_no_use(self):
+ self.assertRaises(ValueError, warndep.relocated_method,"a",None)
+
+#=========================================================
+#dep attr
+#=========================================================
+#TODO: deprecated_property -
+# test basic functionality,
+# test options,
+# test that deprecated_method wrapped funcs are unwrapped via ._deprecated_func
+
+#=========================================================
+#eof
+#=========================================================
diff --git a/bps/tests/utils.py b/bps/tests/utils.py
new file mode 100644
index 0000000..03a9b4a
--- /dev/null
+++ b/bps/tests/utils.py
@@ -0,0 +1,384 @@
+"""helpers for bps unittests"""
+#=========================================================
+#imports
+#=========================================================
+#core
+import warnings
+import os
+import atexit
+import tempfile
+import unittest
+import sys
+from logging import getLogger; log = getLogger(__name__)
+from cStringIO import StringIO
+import logging
+#pkg
+from bps.types import BaseClass
+from bps.fs import filepath
+from bps.meta import Params, is_oseq, is_iter
+from bps.logs import config_logging
+from bps.logs.handlers import purge_handlers
+#local
+__all__ = [
+ 'ak'
+ 'TestCase',
+ 'get_tmp_path', 'enable_suite',
+ 'catch_warnings', 'capture_logger',
+]
+
+ak = Params
+
+#=========================================================
+#custom test base
+#=========================================================
+class TestCase(unittest.TestCase, BaseClass):
+ "bps-specific test case class, mainly contains messaging enhancements"
+
+ _prefix = None
+
+ def __init__(self, *a, **k):
+ #set the doc strings to begin w/ prefix
+ #yes, this is incredibly hacked
+ prefix = self._prefix
+ if prefix:
+ if callable(prefix):
+ prefix = prefix()
+ for attr in dir(self):
+ if not attr.startswith("test_"):
+ continue
+ v = getattr(self, attr)
+ d = v.im_func.__doc__ or v.im_func.__name__
+ idx = d.find(": ")
+ if idx > -1:
+ d = d[idx+1:]
+ v.im_func.__doc__ = d = "%s: %s" % (prefix, d.lstrip())
+ assert v.__doc__ == d
+ unittest.TestCase.__init__(self, *a, **k)
+
+ def assertEquals(self, real, correct, msg=None):
+ #NOTE: overriding this to get msg formatting capability
+ msg = self._format_msg(msg, "got %r, expected would equal %r", real, correct)
+ return self.assert_(real == correct, msg)
+
+## assert_equals = assertEquals
+
+ def assertEqual(self, *a, **k):
+ return self.assertEquals(*a, **k)
+
+ def assertElementsEqual(self, real, correct, msg=None):
+ "test that two objects have same set of elements"
+ real = set(real)
+ correct = set(correct)
+ msg = self._format_msg(msg, "got %r, expected would have same elements as %r", sorted(real), sorted(correct))
+ return self.assert_(real == correct, msg)
+ assert_sets_equal = assertElementsEqual #deprecated
+ assert_same_set = assertElementsEqual #preferred
+
+ def assert_same_order(self, real, correct, msg=None):
+ "test that two objects are sequences w/ same elements in same order"
+ real = list(real)
+ correct = list(correct)
+ msg = self._format_msg(msg, "got %r, expected would have same elements, in same order, as %r", real, correct)
+ return self.assert_(real == correct, msg)
+
+ def assertNotEquals(self, real, correct, msg=None):
+ #NOTE: overriding this to get msg formatting capability
+ msg = self._format_msg(msg, "got %r, expected would equal %r", real, correct)
+ return self.assert_(real != correct, msg)
+## assert_not_equals = assertNotEquals
+
+ def assertNotEqual(self, *a, **k):
+ return self.assertNotEquals(*a, **k)
+
+ def assertIs(self, real, correct, msg=None):
+ msg = self._format_msg(msg, "got %r, expected would be %r", real, correct)
+ return self.assert_(real is correct, msg)
+
+ def assertIsNot(self, real, correct, msg=None):
+ msg = self._format_msg(msg, "expected would not be %r", real)
+ return self.assert_(real is not correct, msg)
+
+ def assertIsInstance(self, obj, klass, msg=None):
+ msg = self._format_msg(msg, "got %r, expected instance of %r", obj, klass)
+ return self.assert_(isinstance(obj, klass), msg)
+
+ def assertRaises(self, type, func, *args, **kwds):
+ msg = kwds.pop("__msg__", None)
+ err = None
+ try:
+ result = func(*args, **kwds)
+ except Exception, err:
+ pass
+ if err is None:
+ msg = self._format_msg(msg, "function returned %r, expected it to raise %r", result, type)
+ raise AssertionError(msg)
+ elif not isinstance(err, type):
+ msg = self._format_msg(msg, "function raised %r, expected %r", err, type)
+ raise AssertionError(msg)
+
+ def assertAttrRaises(self, excClass, obj, attr):
+ #XXX: default msg?
+ self.assertRaises(excClass, getattr, obj, attr)
+
+ def assertWarningEquals(self, warning, **kwds):
+ "check if WarningMessage instance matches parameters"
+ for key in ("message", "category", "filename", "lineno", "file", "line"):
+ if key not in kwds:
+ continue
+ real = getattr(warning, key)
+ if key == "message":
+ real = str(real) #usually a UserWarning(value), etc
+ value = kwds[key]
+ if key == "filename":
+ if value.endswith(".pyc") or value.endswith(".pyo"):
+ value = value[:-1]
+ if real != value:
+ raise AssertionError("warning %s doesn't match pattern %r" % (warning, kwds))
+
+ assert_warning = assertWarningEquals
+
+ def check_function_results(self, func, cases):
+ "helper for running through function call cases"
+ #cases should be list of ak objects,
+ #whose first element is the function's return value
+ for elem in cases:
+ elem = Params.normalize(elem)
+ correct = elem.args[0]
+ result = func(*elem.args[1:], **elem.kwds)
+ self.assertEqual(result, correct,
+ "error for case %s: got %r, expected would equal %r" % (elem.render(1), result, correct)
+ )
+
+ def check_function_rtype(self, func, retval=None, rtype=None, ordered=False):
+ """helper for testing functions that allow return type to be specified via rtype kwd.
+
+ :arg func: function (w/ parameters bound via partial)
+ :arg retval: expected result (can be set, list, etc)
+ :arg rtype: default rtype
+ :param ordered: if order must match retval when rtype is ordered
+ """
+ #NOTE: 'self' should be test case
+ has_retval = (retval is not None)
+
+ #check default rtype is correct
+ result = func()
+ if rtype is None:
+ pass
+ elif rtype is iter:
+ self.assert_(is_iter(result))
+ else:
+ self.assertIsInstance(result, rtype)
+ if has_retval:
+ if ordered and (is_oseq(result) or is_iter(result)):
+ self.assert_same_order(result, retval)
+ else:
+ self.assert_same_set(result, retval)
+
+ #check unordered types work
+ for t in (set, frozenset):
+ result = func(rtype=t)
+ self.assertIsInstance(result,t)
+ if has_retval:
+ self.assert_same_set(result, retval)
+
+ #check ordered types work
+ for t in (list, tuple):
+ result = func(rtype=t)
+ self.assertIsInstance(result,t)
+ if has_retval:
+ if ordered:
+ self.assert_same_order(result, retval)
+ else:
+ self.assert_same_set(result, retval)
+
+ #check rtype=iter works
+ result = func(rtype=iter)
+ self.assert_(is_iter(result))
+ if has_retval:
+ if ordered:
+ self.assert_same_order(result, retval)
+ else:
+ self.assert_same_set(result, retval)
+
+ def _format_msg(self, msg, template, *args, **kwds):
+ if msg and not msg.endswith(":"):
+ return msg
+ if args:
+ template %= args
+ if kwds:
+ template %= kwds
+ if msg:
+ return msg + " " + template
+ return template
+
+#=========================================================
+#helper funcs
+#=========================================================
+_tmp_files = []
+def _tmpfile_cleaner():
+ for path in _tmp_files:
+ try:
+ path.discard()
+ except:
+ log.warning("error removing temp file: %r", path, exc_info=True)
+atexit.register(_tmpfile_cleaner)
+def get_tmp_path():
+ "returns a temporary path suitable for any use, which will be removed on exit"
+ fd, path = tempfile.mkstemp(prefix=__name__ + "-")
+ os.close(fd) #close the descriptor
+ path = filepath(path)
+ _tmp_files.append(path) #register it with cleanup routine
+ path.remove() #remove the file which was there
+ assert path.ismissing
+ return path
+
+def enable_suite(name):
+ """check if a given test should be included based on the env var.
+
+ test flags:
+ bcrypt enable basic bcrypt tests
+ slow_bcrypt enable extra check for slow bcrypt implementation
+ pwgen_dups enable duplication rate checks for pwgen
+ """
+ _flags = [ v.strip()
+ for v
+ in os.environ.get("BPS_TEST_SUITE", "").lower().split(",")
+ ]
+ if 'all' in _flags:
+ return True
+ if name in _flags:
+ return True
+ return False
+
+#=========================================================
+#python backports
+#=========================================================
+
+#this was copied from the python 2.6.2 warnings.py file,
+#so it would always be available for unit-tests
+try:
+ from warnings import catch_warnings, WarningMessage
+except ImportError:
+ class WarningMessage(object):
+
+ """Holds the result of a single showwarning() call."""
+
+ _WARNING_DETAILS = ("message", "category", "filename", "lineno", "file",
+ "line")
+
+ def __init__(self, message, category, filename, lineno, file=None,
+ line=None):
+ local_values = locals()
+ for attr in self._WARNING_DETAILS:
+ setattr(self, attr, local_values[attr])
+ self._category_name = category.__name__ if category else None
+
+ def __str__(self):
+ return ("{message : %r, category : %r, filename : %r, lineno : %s, "
+ "line : %r}" % (self.message, self._category_name,
+ self.filename, self.lineno, self.line))
+
+ class catch_warnings(object):
+
+ """A context manager that copies and restores the warnings filter upon
+ exiting the context.
+
+ The 'record' argument specifies whether warnings should be captured by a
+ custom implementation of warnings.showwarning() and be appended to a list
+ returned by the context manager. Otherwise None is returned by the context
+ manager. The objects appended to the list are arguments whose attributes
+ mirror the arguments to showwarning().
+
+ The 'module' argument is to specify an alternative module to the module
+ named 'warnings' and imported under that name. This argument is only useful
+ when testing the warnings module itself.
+
+ """
+
+ def __init__(self, record=False, module=None):
+ """Specify whether to record warnings and if an alternative module
+ should be used other than sys.modules['warnings'].
+
+ For compatibility with Python 3.0, please consider all arguments to be
+ keyword-only.
+
+ """
+ self._record = record
+ self._module = sys.modules['warnings'] if module is None else module
+ self._entered = False
+
+ def __repr__(self):
+ args = []
+ if self._record:
+ args.append("record=True")
+ if self._module is not sys.modules['warnings']:
+ args.append("module=%r" % self._module)
+ name = type(self).__name__
+ return "%s(%s)" % (name, ", ".join(args))
+
+ def __enter__(self):
+ if self._entered:
+ raise RuntimeError("Cannot enter %r twice" % self)
+ self._entered = True
+ self._filters = self._module.filters
+ self._module.filters = self._filters[:]
+ self._showwarning = self._module.showwarning
+ if self._record:
+ log = []
+ def showwarning(*args, **kwargs):
+ log.append(WarningMessage(*args, **kwargs))
+ self._module.showwarning = showwarning
+ return log
+ else:
+ return None
+
+ def __exit__(self, *exc_info):
+ if not self._entered:
+ raise RuntimeError("Cannot exit %r without entering first" % self)
+ self._module.filters = self._filters
+ self._module.showwarning = self._showwarning
+
+class catch_all_warnings(catch_warnings):
+ "wrap which ensures all warnings are logged to buffer"
+ def __init__(self):
+ self.__super = super(catch_all_warnings,self)
+ self.__super.__init__(record=True)
+ def __enter__(self):
+ log = self.__super.__enter__()
+ warnings.filterwarnings("always")
+ return log
+
+#=========================================================
+#capture logging output
+#=========================================================
+
+class capture_logger(object):
+ "capture output of logger, returning StringIO buffer output is written to"
+
+ def __init__(self, name=""):
+ self.log = getLogger(name)
+
+ def __enter__(self):
+ #remove handlers but don't delete them (we'll restore later)
+ self.propagate = self.log.propagate
+ self.handlers = purge_handlers(self.log, close=False)
+
+ #create new handler
+ buffer = StringIO()
+ handler = logging.StreamHandler(buffer)
+ handler.formatter = logging.Formatter("%(name)s: %(levelname)s: %(message)s")
+ self.log.addHandler(handler)
+ self.log.propagate = False
+ return buffer
+
+ def __exit__(self, *exc_info):
+ #remove handler we added
+ purge_handlers(self.log)
+
+ #restore original list of handlers
+ self.log.handlers[:] = self.handlers
+ self.log.propagate = self.propagate
+
+#=========================================================
+#EOF
+#=========================================================