blob: 5078a2e94f18ec0e56c05da19a7c533aa67ac883 [file] [log] [blame]
Raymond Hettinger9c323f82005-02-28 19:39:44 +00001import functional
2import unittest
3from test import test_support
Raymond Hettingerc8b6d1b2005-03-08 06:14:50 +00004from weakref import proxy
Raymond Hettinger9c323f82005-02-28 19:39:44 +00005
6@staticmethod
7def PythonPartial(func, *args, **keywords):
8 'Pure Python approximation of partial()'
9 def newfunc(*fargs, **fkeywords):
10 newkeywords = keywords.copy()
11 newkeywords.update(fkeywords)
12 return func(*(args + fargs), **newkeywords)
13 newfunc.func = func
14 newfunc.args = args
15 newfunc.keywords = keywords
16 return newfunc
17
18def capture(*args, **kw):
19 """capture all positional and keyword arguments"""
20 return args, kw
21
22class TestPartial(unittest.TestCase):
23
24 thetype = functional.partial
25
26 def test_basic_examples(self):
27 p = self.thetype(capture, 1, 2, a=10, b=20)
28 self.assertEqual(p(3, 4, b=30, c=40),
29 ((1, 2, 3, 4), dict(a=10, b=30, c=40)))
30 p = self.thetype(map, lambda x: x*10)
31 self.assertEqual(p([1,2,3,4]), [10, 20, 30, 40])
32
33 def test_attributes(self):
34 p = self.thetype(capture, 1, 2, a=10, b=20)
35 # attributes should be readable
36 self.assertEqual(p.func, capture)
37 self.assertEqual(p.args, (1, 2))
38 self.assertEqual(p.keywords, dict(a=10, b=20))
39 # attributes should not be writable
40 if not isinstance(self.thetype, type):
41 return
42 self.assertRaises(TypeError, setattr, p, 'func', map)
43 self.assertRaises(TypeError, setattr, p, 'args', (1, 2))
44 self.assertRaises(TypeError, setattr, p, 'keywords', dict(a=1, b=2))
45
46 def test_argument_checking(self):
47 self.assertRaises(TypeError, self.thetype) # need at least a func arg
48 try:
49 self.thetype(2)()
50 except TypeError:
51 pass
52 else:
53 self.fail('First arg not checked for callability')
54
55 def test_protection_of_callers_dict_argument(self):
56 # a caller's dictionary should not be altered by partial
57 def func(a=10, b=20):
58 return a
59 d = {'a':3}
60 p = self.thetype(func, a=5)
61 self.assertEqual(p(**d), 3)
62 self.assertEqual(d, {'a':3})
63 p(b=7)
64 self.assertEqual(d, {'a':3})
65
66 def test_arg_combinations(self):
67 # exercise special code paths for zero args in either partial
68 # object or the caller
69 p = self.thetype(capture)
70 self.assertEqual(p(), ((), {}))
71 self.assertEqual(p(1,2), ((1,2), {}))
72 p = self.thetype(capture, 1, 2)
73 self.assertEqual(p(), ((1,2), {}))
74 self.assertEqual(p(3,4), ((1,2,3,4), {}))
75
76 def test_kw_combinations(self):
77 # exercise special code paths for no keyword args in
78 # either the partial object or the caller
79 p = self.thetype(capture)
80 self.assertEqual(p(), ((), {}))
81 self.assertEqual(p(a=1), ((), {'a':1}))
82 p = self.thetype(capture, a=1)
83 self.assertEqual(p(), ((), {'a':1}))
84 self.assertEqual(p(b=2), ((), {'a':1, 'b':2}))
85 # keyword args in the call override those in the partial object
86 self.assertEqual(p(a=3, b=2), ((), {'a':3, 'b':2}))
87
88 def test_positional(self):
89 # make sure positional arguments are captured correctly
90 for args in [(), (0,), (0,1), (0,1,2), (0,1,2,3)]:
91 p = self.thetype(capture, *args)
92 expected = args + ('x',)
93 got, empty = p('x')
94 self.failUnless(expected == got and empty == {})
95
96 def test_keyword(self):
97 # make sure keyword arguments are captured correctly
98 for a in ['a', 0, None, 3.5]:
99 p = self.thetype(capture, a=a)
100 expected = {'a':a,'x':None}
101 empty, got = p(x=None)
102 self.failUnless(expected == got and empty == ())
103
104 def test_no_side_effects(self):
105 # make sure there are no side effects that affect subsequent calls
106 p = self.thetype(capture, 0, a=1)
107 args1, kw1 = p(1, b=2)
108 self.failUnless(args1 == (0,1) and kw1 == {'a':1,'b':2})
109 args2, kw2 = p()
110 self.failUnless(args2 == (0,) and kw2 == {'a':1})
111
112 def test_error_propagation(self):
113 def f(x, y):
114 x / y
115 self.assertRaises(ZeroDivisionError, self.thetype(f, 1, 0))
116 self.assertRaises(ZeroDivisionError, self.thetype(f, 1), 0)
117 self.assertRaises(ZeroDivisionError, self.thetype(f), 1, 0)
118 self.assertRaises(ZeroDivisionError, self.thetype(f, y=0), 1)
119
Raymond Hettingerc8b6d1b2005-03-08 06:14:50 +0000120 def test_attributes(self):
121 p = self.thetype(hex)
122 try:
123 del p.__dict__
124 except TypeError:
125 pass
126 else:
127 self.fail('partial object allowed __dict__ to be deleted')
128
129 def test_weakref(self):
130 f = self.thetype(int, base=16)
131 p = proxy(f)
132 self.assertEqual(f.func, p.func)
133 f = None
134 self.assertRaises(ReferenceError, getattr, p, 'func')
135
Raymond Hettinger26e512a2005-03-11 06:48:49 +0000136 def test_with_bound_and_unbound_methods(self):
137 data = map(str, range(10))
138 join = self.thetype(str.join, '')
139 self.assertEqual(join(data), '0123456789')
140 join = self.thetype(''.join)
141 self.assertEqual(join(data), '0123456789')
Tim Peterseba28be2005-03-28 01:08:02 +0000142
Raymond Hettinger9c323f82005-02-28 19:39:44 +0000143class PartialSubclass(functional.partial):
144 pass
145
146class TestPartialSubclass(TestPartial):
147
148 thetype = PartialSubclass
149
150
151class TestPythonPartial(TestPartial):
152
153 thetype = PythonPartial
154
155
156
157def test_main(verbose=None):
158 import sys
159 test_classes = (
160 TestPartial,
161 TestPartialSubclass,
162 TestPythonPartial,
163 )
164 test_support.run_unittest(*test_classes)
165
166 # verify reference counting
167 if verbose and hasattr(sys, "gettotalrefcount"):
168 import gc
169 counts = [None] * 5
170 for i in xrange(len(counts)):
171 test_support.run_unittest(*test_classes)
172 gc.collect()
173 counts[i] = sys.gettotalrefcount()
174 print counts
175
176if __name__ == '__main__':
177 test_main(verbose=True)