PageRenderTime 1164ms CodeModel.GetById 160ms app.highlight 781ms RepoModel.GetById 216ms app.codeStats 0ms

/Lib/test/test_operator.py

http://unladen-swallow.googlecode.com/
Python | 529 lines | 493 code | 36 blank | 0 comment | 0 complexity | 8e007ef3df61f31e9aa2148d4c0a5bf9 MD5 | raw file
  1import operator
  2import unittest
  3
  4from test import test_support
  5
  6class Seq1:
  7    def __init__(self, lst):
  8        self.lst = lst
  9    def __len__(self):
 10        return len(self.lst)
 11    def __getitem__(self, i):
 12        return self.lst[i]
 13    def __add__(self, other):
 14        return self.lst + other.lst
 15    def __mul__(self, other):
 16        return self.lst * other
 17    def __rmul__(self, other):
 18        return other * self.lst
 19
 20class Seq2(object):
 21    def __init__(self, lst):
 22        self.lst = lst
 23    def __len__(self):
 24        return len(self.lst)
 25    def __getitem__(self, i):
 26        return self.lst[i]
 27    def __add__(self, other):
 28        return self.lst + other.lst
 29    def __mul__(self, other):
 30        return self.lst * other
 31    def __rmul__(self, other):
 32        return other * self.lst
 33
 34
 35class OperatorTestCase(unittest.TestCase):
 36    def test_lt(self):
 37        self.failUnlessRaises(TypeError, operator.lt)
 38        self.failUnlessRaises(TypeError, operator.lt, 1j, 2j)
 39        self.failIf(operator.lt(1, 0))
 40        self.failIf(operator.lt(1, 0.0))
 41        self.failIf(operator.lt(1, 1))
 42        self.failIf(operator.lt(1, 1.0))
 43        self.failUnless(operator.lt(1, 2))
 44        self.failUnless(operator.lt(1, 2.0))
 45
 46    def test_le(self):
 47        self.failUnlessRaises(TypeError, operator.le)
 48        self.failUnlessRaises(TypeError, operator.le, 1j, 2j)
 49        self.failIf(operator.le(1, 0))
 50        self.failIf(operator.le(1, 0.0))
 51        self.failUnless(operator.le(1, 1))
 52        self.failUnless(operator.le(1, 1.0))
 53        self.failUnless(operator.le(1, 2))
 54        self.failUnless(operator.le(1, 2.0))
 55
 56    def test_eq(self):
 57        class C(object):
 58            def __eq__(self, other):
 59                raise SyntaxError
 60            __hash__ = None # Silence Py3k warning
 61        self.failUnlessRaises(TypeError, operator.eq)
 62        self.failUnlessRaises(SyntaxError, operator.eq, C(), C())
 63        self.failIf(operator.eq(1, 0))
 64        self.failIf(operator.eq(1, 0.0))
 65        self.failUnless(operator.eq(1, 1))
 66        self.failUnless(operator.eq(1, 1.0))
 67        self.failIf(operator.eq(1, 2))
 68        self.failIf(operator.eq(1, 2.0))
 69
 70    def test_ne(self):
 71        class C(object):
 72            def __ne__(self, other):
 73                raise SyntaxError
 74        self.failUnlessRaises(TypeError, operator.ne)
 75        self.failUnlessRaises(SyntaxError, operator.ne, C(), C())
 76        self.failUnless(operator.ne(1, 0))
 77        self.failUnless(operator.ne(1, 0.0))
 78        self.failIf(operator.ne(1, 1))
 79        self.failIf(operator.ne(1, 1.0))
 80        self.failUnless(operator.ne(1, 2))
 81        self.failUnless(operator.ne(1, 2.0))
 82
 83    def test_ge(self):
 84        self.failUnlessRaises(TypeError, operator.ge)
 85        self.failUnlessRaises(TypeError, operator.ge, 1j, 2j)
 86        self.failUnless(operator.ge(1, 0))
 87        self.failUnless(operator.ge(1, 0.0))
 88        self.failUnless(operator.ge(1, 1))
 89        self.failUnless(operator.ge(1, 1.0))
 90        self.failIf(operator.ge(1, 2))
 91        self.failIf(operator.ge(1, 2.0))
 92
 93    def test_gt(self):
 94        self.failUnlessRaises(TypeError, operator.gt)
 95        self.failUnlessRaises(TypeError, operator.gt, 1j, 2j)
 96        self.failUnless(operator.gt(1, 0))
 97        self.failUnless(operator.gt(1, 0.0))
 98        self.failIf(operator.gt(1, 1))
 99        self.failIf(operator.gt(1, 1.0))
100        self.failIf(operator.gt(1, 2))
101        self.failIf(operator.gt(1, 2.0))
102
103    def test_abs(self):
104        self.failUnlessRaises(TypeError, operator.abs)
105        self.failUnlessRaises(TypeError, operator.abs, None)
106        self.failUnless(operator.abs(-1) == 1)
107        self.failUnless(operator.abs(1) == 1)
108
109    def test_add(self):
110        self.failUnlessRaises(TypeError, operator.add)
111        self.failUnlessRaises(TypeError, operator.add, None, None)
112        self.failUnless(operator.add(3, 4) == 7)
113
114    def test_bitwise_and(self):
115        self.failUnlessRaises(TypeError, operator.and_)
116        self.failUnlessRaises(TypeError, operator.and_, None, None)
117        self.failUnless(operator.and_(0xf, 0xa) == 0xa)
118
119    def test_concat(self):
120        self.failUnlessRaises(TypeError, operator.concat)
121        self.failUnlessRaises(TypeError, operator.concat, None, None)
122        self.failUnless(operator.concat('py', 'thon') == 'python')
123        self.failUnless(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])
124        self.failUnless(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])
125        self.failUnless(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])
126        self.failUnlessRaises(TypeError, operator.concat, 13, 29)
127
128    def test_countOf(self):
129        self.failUnlessRaises(TypeError, operator.countOf)
130        self.failUnlessRaises(TypeError, operator.countOf, None, None)
131        self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
132        self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
133
134    def test_delitem(self):
135        a = [4, 3, 2, 1]
136        self.failUnlessRaises(TypeError, operator.delitem, a)
137        self.failUnlessRaises(TypeError, operator.delitem, a, None)
138        self.failUnless(operator.delitem(a, 1) is None)
139        self.assert_(a == [4, 2, 1])
140
141    def test_delslice(self):
142        a = range(10)
143        self.failUnlessRaises(TypeError, operator.delslice, a)
144        self.failUnlessRaises(TypeError, operator.delslice, a, None, None)
145        self.failUnless(operator.delslice(a, 2, 8) is None)
146        self.assert_(a == [0, 1, 8, 9])
147        operator.delslice(a, 0, test_support.MAX_Py_ssize_t)
148        self.assert_(a == [])
149
150    def test_div(self):
151        self.failUnlessRaises(TypeError, operator.div, 5)
152        self.failUnlessRaises(TypeError, operator.div, None, None)
153        self.failUnless(operator.floordiv(5, 2) == 2)
154
155    def test_floordiv(self):
156        self.failUnlessRaises(TypeError, operator.floordiv, 5)
157        self.failUnlessRaises(TypeError, operator.floordiv, None, None)
158        self.failUnless(operator.floordiv(5, 2) == 2)
159
160    def test_truediv(self):
161        self.failUnlessRaises(TypeError, operator.truediv, 5)
162        self.failUnlessRaises(TypeError, operator.truediv, None, None)
163        self.failUnless(operator.truediv(5, 2) == 2.5)
164
165    def test_getitem(self):
166        a = range(10)
167        self.failUnlessRaises(TypeError, operator.getitem)
168        self.failUnlessRaises(TypeError, operator.getitem, a, None)
169        self.failUnless(operator.getitem(a, 2) == 2)
170
171    def test_getslice(self):
172        a = range(10)
173        self.failUnlessRaises(TypeError, operator.getslice)
174        self.failUnlessRaises(TypeError, operator.getslice, a, None, None)
175        self.failUnless(operator.getslice(a, 4, 6) == [4, 5])
176        b = operator.getslice(a, 0, test_support.MAX_Py_ssize_t)
177        self.assert_(b == a)
178
179    def test_indexOf(self):
180        self.failUnlessRaises(TypeError, operator.indexOf)
181        self.failUnlessRaises(TypeError, operator.indexOf, None, None)
182        self.failUnless(operator.indexOf([4, 3, 2, 1], 3) == 1)
183        self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)
184
185    def test_invert(self):
186        self.failUnlessRaises(TypeError, operator.invert)
187        self.failUnlessRaises(TypeError, operator.invert, None)
188        self.failUnless(operator.inv(4) == -5)
189
190    def test_isCallable(self):
191        self.failUnlessRaises(TypeError, operator.isCallable)
192        class C:
193            pass
194        def check(self, o, v):
195            self.assert_(operator.isCallable(o) == callable(o) == v)
196        check(self, 4, 0)
197        check(self, operator.isCallable, 1)
198        check(self, C, 1)
199        check(self, C(), 0)
200
201    def test_isMappingType(self):
202        self.failUnlessRaises(TypeError, operator.isMappingType)
203        self.failIf(operator.isMappingType(1))
204        self.failIf(operator.isMappingType(operator.isMappingType))
205        self.failUnless(operator.isMappingType(operator.__dict__))
206        self.failUnless(operator.isMappingType({}))
207
208    def test_isNumberType(self):
209        self.failUnlessRaises(TypeError, operator.isNumberType)
210        self.failUnless(operator.isNumberType(8))
211        self.failUnless(operator.isNumberType(8j))
212        self.failUnless(operator.isNumberType(8L))
213        self.failUnless(operator.isNumberType(8.3))
214        self.failIf(operator.isNumberType(dir()))
215
216    def test_isSequenceType(self):
217        self.failUnlessRaises(TypeError, operator.isSequenceType)
218        self.failUnless(operator.isSequenceType(dir()))
219        self.failUnless(operator.isSequenceType(()))
220        self.failUnless(operator.isSequenceType(xrange(10)))
221        self.failUnless(operator.isSequenceType('yeahbuddy'))
222        self.failIf(operator.isSequenceType(3))
223        class Dict(dict): pass
224        self.failIf(operator.isSequenceType(Dict()))
225
226    def test_lshift(self):
227        self.failUnlessRaises(TypeError, operator.lshift)
228        self.failUnlessRaises(TypeError, operator.lshift, None, 42)
229        self.failUnless(operator.lshift(5, 1) == 10)
230        self.failUnless(operator.lshift(5, 0) == 5)
231        self.assertRaises(ValueError, operator.lshift, 2, -1)
232
233    def test_mod(self):
234        self.failUnlessRaises(TypeError, operator.mod)
235        self.failUnlessRaises(TypeError, operator.mod, None, 42)
236        self.failUnless(operator.mod(5, 2) == 1)
237
238    def test_mul(self):
239        self.failUnlessRaises(TypeError, operator.mul)
240        self.failUnlessRaises(TypeError, operator.mul, None, None)
241        self.failUnless(operator.mul(5, 2) == 10)
242
243    def test_neg(self):
244        self.failUnlessRaises(TypeError, operator.neg)
245        self.failUnlessRaises(TypeError, operator.neg, None)
246        self.failUnless(operator.neg(5) == -5)
247        self.failUnless(operator.neg(-5) == 5)
248        self.failUnless(operator.neg(0) == 0)
249        self.failUnless(operator.neg(-0) == 0)
250
251    def test_bitwise_or(self):
252        self.failUnlessRaises(TypeError, operator.or_)
253        self.failUnlessRaises(TypeError, operator.or_, None, None)
254        self.failUnless(operator.or_(0xa, 0x5) == 0xf)
255
256    def test_pos(self):
257        self.failUnlessRaises(TypeError, operator.pos)
258        self.failUnlessRaises(TypeError, operator.pos, None)
259        self.failUnless(operator.pos(5) == 5)
260        self.failUnless(operator.pos(-5) == -5)
261        self.failUnless(operator.pos(0) == 0)
262        self.failUnless(operator.pos(-0) == 0)
263
264    def test_pow(self):
265        self.failUnlessRaises(TypeError, operator.pow)
266        self.failUnlessRaises(TypeError, operator.pow, None, None)
267        self.failUnless(operator.pow(3,5) == 3**5)
268        self.failUnless(operator.__pow__(3,5) == 3**5)
269        self.assertRaises(TypeError, operator.pow, 1)
270        self.assertRaises(TypeError, operator.pow, 1, 2, 3)
271
272    def test_repeat(self):
273        a = range(3)
274        self.failUnlessRaises(TypeError, operator.repeat)
275        self.failUnlessRaises(TypeError, operator.repeat, a, None)
276        self.failUnless(operator.repeat(a, 2) == a+a)
277        self.failUnless(operator.repeat(a, 1) == a)
278        self.failUnless(operator.repeat(a, 0) == [])
279        a = (1, 2, 3)
280        self.failUnless(operator.repeat(a, 2) == a+a)
281        self.failUnless(operator.repeat(a, 1) == a)
282        self.failUnless(operator.repeat(a, 0) == ())
283        a = '123'
284        self.failUnless(operator.repeat(a, 2) == a+a)
285        self.failUnless(operator.repeat(a, 1) == a)
286        self.failUnless(operator.repeat(a, 0) == '')
287        a = Seq1([4, 5, 6])
288        self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6])
289        self.failUnless(operator.repeat(a, 1) == [4, 5, 6])
290        self.failUnless(operator.repeat(a, 0) == [])
291        a = Seq2([4, 5, 6])
292        self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6])
293        self.failUnless(operator.repeat(a, 1) == [4, 5, 6])
294        self.failUnless(operator.repeat(a, 0) == [])
295        self.failUnlessRaises(TypeError, operator.repeat, 6, 7)
296
297    def test_rshift(self):
298        self.failUnlessRaises(TypeError, operator.rshift)
299        self.failUnlessRaises(TypeError, operator.rshift, None, 42)
300        self.failUnless(operator.rshift(5, 1) == 2)
301        self.failUnless(operator.rshift(5, 0) == 5)
302        self.assertRaises(ValueError, operator.rshift, 2, -1)
303
304    def test_contains(self):
305        self.failUnlessRaises(TypeError, operator.contains)
306        self.failUnlessRaises(TypeError, operator.contains, None, None)
307        self.failUnless(operator.contains(range(4), 2))
308        self.failIf(operator.contains(range(4), 5))
309        self.failUnless(operator.sequenceIncludes(range(4), 2))
310        self.failIf(operator.sequenceIncludes(range(4), 5))
311
312    def test_setitem(self):
313        a = range(3)
314        self.failUnlessRaises(TypeError, operator.setitem, a)
315        self.failUnlessRaises(TypeError, operator.setitem, a, None, None)
316        self.failUnless(operator.setitem(a, 0, 2) is None)
317        self.assert_(a == [2, 1, 2])
318        self.assertRaises(IndexError, operator.setitem, a, 4, 2)
319
320    def test_setslice(self):
321        a = range(4)
322        self.failUnlessRaises(TypeError, operator.setslice, a)
323        self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None)
324        self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None)
325        self.assert_(a == [0, 2, 1, 3])
326        operator.setslice(a, 0, test_support.MAX_Py_ssize_t, [])
327        self.assert_(a == [])
328
329    def test_sub(self):
330        self.failUnlessRaises(TypeError, operator.sub)
331        self.failUnlessRaises(TypeError, operator.sub, None, None)
332        self.failUnless(operator.sub(5, 2) == 3)
333
334    def test_truth(self):
335        class C(object):
336            def __nonzero__(self):
337                raise SyntaxError
338        self.failUnlessRaises(TypeError, operator.truth)
339        self.failUnlessRaises(SyntaxError, operator.truth, C())
340        self.failUnless(operator.truth(5))
341        self.failUnless(operator.truth([0]))
342        self.failIf(operator.truth(0))
343        self.failIf(operator.truth([]))
344
345    def test_bitwise_xor(self):
346        self.failUnlessRaises(TypeError, operator.xor)
347        self.failUnlessRaises(TypeError, operator.xor, None, None)
348        self.failUnless(operator.xor(0xb, 0xc) == 0x7)
349
350    def test_is(self):
351        a = b = 'xyzpdq'
352        c = a[:3] + b[3:]
353        self.failUnlessRaises(TypeError, operator.is_)
354        self.failUnless(operator.is_(a, b))
355        self.failIf(operator.is_(a,c))
356
357    def test_is_not(self):
358        a = b = 'xyzpdq'
359        c = a[:3] + b[3:]
360        self.failUnlessRaises(TypeError, operator.is_not)
361        self.failIf(operator.is_not(a, b))
362        self.failUnless(operator.is_not(a,c))
363
364    def test_attrgetter(self):
365        class A:
366            pass
367        a = A()
368        a.name = 'arthur'
369        f = operator.attrgetter('name')
370        self.assertEqual(f(a), 'arthur')
371        f = operator.attrgetter('rank')
372        self.assertRaises(AttributeError, f, a)
373        f = operator.attrgetter(2)
374        self.assertRaises(TypeError, f, a)
375        self.assertRaises(TypeError, operator.attrgetter)
376
377        # multiple gets
378        record = A()
379        record.x = 'X'
380        record.y = 'Y'
381        record.z = 'Z'
382        self.assertEqual(operator.attrgetter('x','z','y')(record), ('X', 'Z', 'Y'))
383        self.assertRaises(TypeError, operator.attrgetter('x', (), 'y'), record)
384
385        class C(object):
386            def __getattr__(self, name):
387                raise SyntaxError
388        self.failUnlessRaises(SyntaxError, operator.attrgetter('foo'), C())
389
390        # recursive gets
391        a = A()
392        a.name = 'arthur'
393        a.child = A()
394        a.child.name = 'thomas'
395        f = operator.attrgetter('child.name')
396        self.assertEqual(f(a), 'thomas')
397        self.assertRaises(AttributeError, f, a.child)
398        f = operator.attrgetter('name', 'child.name')
399        self.assertEqual(f(a), ('arthur', 'thomas'))
400        f = operator.attrgetter('name', 'child.name', 'child.child.name')
401        self.assertRaises(AttributeError, f, a)
402
403        a.child.child = A()
404        a.child.child.name = 'johnson'
405        f = operator.attrgetter('child.child.name')
406        self.assertEqual(f(a), 'johnson')
407        f = operator.attrgetter('name', 'child.name', 'child.child.name')
408        self.assertEqual(f(a), ('arthur', 'thomas', 'johnson'))
409
410    def test_itemgetter(self):
411        a = 'ABCDE'
412        f = operator.itemgetter(2)
413        self.assertEqual(f(a), 'C')
414        f = operator.itemgetter(10)
415        self.assertRaises(IndexError, f, a)
416
417        class C(object):
418            def __getitem__(self, name):
419                raise SyntaxError
420        self.failUnlessRaises(SyntaxError, operator.itemgetter(42), C())
421
422        f = operator.itemgetter('name')
423        self.assertRaises(TypeError, f, a)
424        self.assertRaises(TypeError, operator.itemgetter)
425
426        d = dict(key='val')
427        f = operator.itemgetter('key')
428        self.assertEqual(f(d), 'val')
429        f = operator.itemgetter('nonkey')
430        self.assertRaises(KeyError, f, d)
431
432        # example used in the docs
433        inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
434        getcount = operator.itemgetter(1)
435        self.assertEqual(map(getcount, inventory), [3, 2, 5, 1])
436        self.assertEqual(sorted(inventory, key=getcount),
437            [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])
438
439        # multiple gets
440        data = map(str, range(20))
441        self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))
442        self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)
443
444    def test_methodcaller(self):
445        self.assertRaises(TypeError, operator.methodcaller)
446        class A:
447            def foo(self, *args, **kwds):
448                return args[0] + args[1]
449            def bar(self, f=42):
450                return f
451        a = A()
452        f = operator.methodcaller('foo')
453        self.assertRaises(IndexError, f, a)
454        f = operator.methodcaller('foo', 1, 2)
455        self.assertEquals(f(a), 3)
456        f = operator.methodcaller('bar')
457        self.assertEquals(f(a), 42)
458        self.assertRaises(TypeError, f, a, a)
459        f = operator.methodcaller('bar', f=5)
460        self.assertEquals(f(a), 5)
461
462    def test_inplace(self):
463        class C(object):
464            def __iadd__     (self, other): return "iadd"
465            def __iand__     (self, other): return "iand"
466            def __idiv__     (self, other): return "idiv"
467            def __ifloordiv__(self, other): return "ifloordiv"
468            def __ilshift__  (self, other): return "ilshift"
469            def __imod__     (self, other): return "imod"
470            def __imul__     (self, other): return "imul"
471            def __ior__      (self, other): return "ior"
472            def __ipow__     (self, other): return "ipow"
473            def __irshift__  (self, other): return "irshift"
474            def __isub__     (self, other): return "isub"
475            def __itruediv__ (self, other): return "itruediv"
476            def __ixor__     (self, other): return "ixor"
477            def __getitem__(self, other): return 5  # so that C is a sequence
478        c = C()
479        self.assertEqual(operator.iadd     (c, 5), "iadd")
480        self.assertEqual(operator.iand     (c, 5), "iand")
481        self.assertEqual(operator.idiv     (c, 5), "idiv")
482        self.assertEqual(operator.ifloordiv(c, 5), "ifloordiv")
483        self.assertEqual(operator.ilshift  (c, 5), "ilshift")
484        self.assertEqual(operator.imod     (c, 5), "imod")
485        self.assertEqual(operator.imul     (c, 5), "imul")
486        self.assertEqual(operator.ior      (c, 5), "ior")
487        self.assertEqual(operator.ipow     (c, 5), "ipow")
488        self.assertEqual(operator.irshift  (c, 5), "irshift")
489        self.assertEqual(operator.isub     (c, 5), "isub")
490        self.assertEqual(operator.itruediv (c, 5), "itruediv")
491        self.assertEqual(operator.ixor     (c, 5), "ixor")
492        self.assertEqual(operator.iconcat  (c, c), "iadd")
493        self.assertEqual(operator.irepeat  (c, 5), "imul")
494        self.assertEqual(operator.__iadd__     (c, 5), "iadd")
495        self.assertEqual(operator.__iand__     (c, 5), "iand")
496        self.assertEqual(operator.__idiv__     (c, 5), "idiv")
497        self.assertEqual(operator.__ifloordiv__(c, 5), "ifloordiv")
498        self.assertEqual(operator.__ilshift__  (c, 5), "ilshift")
499        self.assertEqual(operator.__imod__     (c, 5), "imod")
500        self.assertEqual(operator.__imul__     (c, 5), "imul")
501        self.assertEqual(operator.__ior__      (c, 5), "ior")
502        self.assertEqual(operator.__ipow__     (c, 5), "ipow")
503        self.assertEqual(operator.__irshift__  (c, 5), "irshift")
504        self.assertEqual(operator.__isub__     (c, 5), "isub")
505        self.assertEqual(operator.__itruediv__ (c, 5), "itruediv")
506        self.assertEqual(operator.__ixor__     (c, 5), "ixor")
507        self.assertEqual(operator.__iconcat__  (c, c), "iadd")
508        self.assertEqual(operator.__irepeat__  (c, 5), "imul")
509
510def test_main(verbose=None):
511    import sys
512    test_classes = (
513        OperatorTestCase,
514    )
515
516    test_support.run_unittest(*test_classes)
517
518    # verify reference counting
519    if verbose and hasattr(sys, "gettotalrefcount"):
520        import gc
521        counts = [None] * 5
522        for i in xrange(len(counts)):
523            test_support.run_unittest(*test_classes)
524            gc.collect()
525            counts[i] = sys.gettotalrefcount()
526        print counts
527
528if __name__ == "__main__":
529    test_main(verbose=True)