2 from test
import test_support
3 from weakref
import proxy
8 from random
import randrange
, shuffle
11 class PassThru(Exception):
14 def check_pass_thru():
21 def __cmp__(self
, other
):
24 class TestJointOps(unittest
.TestCase
):
25 # Tests common to both set and frozenset
28 self
.word
= word
= 'simsalabim'
29 self
.otherword
= 'madagascar'
30 self
.letters
= 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
31 self
.s
= self
.thetype(word
)
32 self
.d
= dict.fromkeys(word
)
34 def test_new_or_init(self
):
35 self
.assertRaises(TypeError, self
.thetype
, [], 2)
37 def test_uniquification(self
):
38 actual
= sorted(self
.s
)
39 expected
= sorted(self
.d
)
40 self
.assertEqual(actual
, expected
)
41 self
.assertRaises(PassThru
, self
.thetype
, check_pass_thru())
42 self
.assertRaises(TypeError, self
.thetype
, [[]])
45 self
.assertEqual(len(self
.s
), len(self
.d
))
47 def test_contains(self
):
48 for c
in self
.letters
:
49 self
.assertEqual(c
in self
.s
, c
in self
.d
)
50 self
.assertRaises(TypeError, self
.s
.__contains
__, [[]])
51 s
= self
.thetype([frozenset(self
.letters
)])
52 self
.assert_(self
.thetype(self
.letters
) in s
)
55 u
= self
.s
.union(self
.otherword
)
56 for c
in self
.letters
:
57 self
.assertEqual(c
in u
, c
in self
.d
or c
in self
.otherword
)
58 self
.assertEqual(self
.s
, self
.thetype(self
.word
))
59 self
.assertEqual(type(u
), self
.thetype
)
60 self
.assertRaises(PassThru
, self
.s
.union
, check_pass_thru())
61 self
.assertRaises(TypeError, self
.s
.union
, [[]])
62 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
63 self
.assertEqual(self
.thetype('abcba').union(C('cdc')), set('abcd'))
64 self
.assertEqual(self
.thetype('abcba').union(C('efgfe')), set('abcefg'))
65 self
.assertEqual(self
.thetype('abcba').union(C('ccb')), set('abc'))
66 self
.assertEqual(self
.thetype('abcba').union(C('ef')), set('abcef'))
69 i
= self
.s
.union(self
.otherword
)
70 self
.assertEqual(self
.s |
set(self
.otherword
), i
)
71 self
.assertEqual(self
.s |
frozenset(self
.otherword
), i
)
73 self
.s | self
.otherword
77 self
.fail("s|t did not screen-out general iterables")
79 def test_intersection(self
):
80 i
= self
.s
.intersection(self
.otherword
)
81 for c
in self
.letters
:
82 self
.assertEqual(c
in i
, c
in self
.d
and c
in self
.otherword
)
83 self
.assertEqual(self
.s
, self
.thetype(self
.word
))
84 self
.assertEqual(type(i
), self
.thetype
)
85 self
.assertRaises(PassThru
, self
.s
.intersection
, check_pass_thru())
86 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
87 self
.assertEqual(self
.thetype('abcba').intersection(C('cdc')), set('cc'))
88 self
.assertEqual(self
.thetype('abcba').intersection(C('efgfe')), set(''))
89 self
.assertEqual(self
.thetype('abcba').intersection(C('ccb')), set('bc'))
90 self
.assertEqual(self
.thetype('abcba').intersection(C('ef')), set(''))
93 i
= self
.s
.intersection(self
.otherword
)
94 self
.assertEqual(self
.s
& set(self
.otherword
), i
)
95 self
.assertEqual(self
.s
& frozenset(self
.otherword
), i
)
97 self
.s
& self
.otherword
101 self
.fail("s&t did not screen-out general iterables")
103 def test_difference(self
):
104 i
= self
.s
.difference(self
.otherword
)
105 for c
in self
.letters
:
106 self
.assertEqual(c
in i
, c
in self
.d
and c
not in self
.otherword
)
107 self
.assertEqual(self
.s
, self
.thetype(self
.word
))
108 self
.assertEqual(type(i
), self
.thetype
)
109 self
.assertRaises(PassThru
, self
.s
.difference
, check_pass_thru())
110 self
.assertRaises(TypeError, self
.s
.difference
, [[]])
111 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
112 self
.assertEqual(self
.thetype('abcba').difference(C('cdc')), set('ab'))
113 self
.assertEqual(self
.thetype('abcba').difference(C('efgfe')), set('abc'))
114 self
.assertEqual(self
.thetype('abcba').difference(C('ccb')), set('a'))
115 self
.assertEqual(self
.thetype('abcba').difference(C('ef')), set('abc'))
118 i
= self
.s
.difference(self
.otherword
)
119 self
.assertEqual(self
.s
- set(self
.otherword
), i
)
120 self
.assertEqual(self
.s
- frozenset(self
.otherword
), i
)
122 self
.s
- self
.otherword
126 self
.fail("s-t did not screen-out general iterables")
128 def test_symmetric_difference(self
):
129 i
= self
.s
.symmetric_difference(self
.otherword
)
130 for c
in self
.letters
:
131 self
.assertEqual(c
in i
, (c
in self
.d
) ^
(c
in self
.otherword
))
132 self
.assertEqual(self
.s
, self
.thetype(self
.word
))
133 self
.assertEqual(type(i
), self
.thetype
)
134 self
.assertRaises(PassThru
, self
.s
.symmetric_difference
, check_pass_thru())
135 self
.assertRaises(TypeError, self
.s
.symmetric_difference
, [[]])
136 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
137 self
.assertEqual(self
.thetype('abcba').symmetric_difference(C('cdc')), set('abd'))
138 self
.assertEqual(self
.thetype('abcba').symmetric_difference(C('efgfe')), set('abcefg'))
139 self
.assertEqual(self
.thetype('abcba').symmetric_difference(C('ccb')), set('a'))
140 self
.assertEqual(self
.thetype('abcba').symmetric_difference(C('ef')), set('abcef'))
143 i
= self
.s
.symmetric_difference(self
.otherword
)
144 self
.assertEqual(self
.s ^
set(self
.otherword
), i
)
145 self
.assertEqual(self
.s ^
frozenset(self
.otherword
), i
)
147 self
.s ^ self
.otherword
151 self
.fail("s^t did not screen-out general iterables")
153 def test_equality(self
):
154 self
.assertEqual(self
.s
, set(self
.word
))
155 self
.assertEqual(self
.s
, frozenset(self
.word
))
156 self
.assertEqual(self
.s
== self
.word
, False)
157 self
.assertNotEqual(self
.s
, set(self
.otherword
))
158 self
.assertNotEqual(self
.s
, frozenset(self
.otherword
))
159 self
.assertEqual(self
.s
!= self
.word
, True)
161 def test_setOfFrozensets(self
):
162 t
= map(frozenset, ['abcdef', 'bcd', 'bdcb', 'fed', 'fedccba'])
164 self
.assertEqual(len(s
), 3)
166 def test_compare(self
):
167 self
.assertRaises(TypeError, self
.s
.__cmp
__, self
.s
)
169 def test_sub_and_super(self
):
170 p
, q
, r
= map(self
.thetype
, ['ab', 'abcde', 'def'])
180 self
.assert_(set('a').issubset('abc'))
181 self
.assert_(set('abc').issuperset('a'))
182 self
.failIf(set('a').issubset('cbs'))
183 self
.failIf(set('cbs').issuperset('a'))
185 def test_pickling(self
):
187 p
= pickle
.dumps(self
.s
, i
)
188 dup
= pickle
.loads(p
)
189 self
.assertEqual(self
.s
, dup
, "%s != %s" % (self
.s
, dup
))
190 if type(self
.s
) not in (set, frozenset):
192 p
= pickle
.dumps(self
.s
)
193 dup
= pickle
.loads(p
)
194 self
.assertEqual(self
.s
.x
, dup
.x
)
196 def test_deepcopy(self
):
198 def __init__(self
, value
):
202 def __deepcopy__(self
, memo
=None):
203 return Tracer(self
.value
+ 1)
205 s
= self
.thetype([t
])
206 dup
= copy
.deepcopy(s
)
207 self
.assertNotEqual(id(s
), id(dup
))
210 self
.assertNotEqual(id(t
), id(newt
))
211 self
.assertEqual(t
.value
+ 1, newt
.value
)
214 # Create a nest of cycles to exercise overall ref count check
217 s
= set(A() for i
in xrange(1000))
221 elem
.set = set([elem
])
223 def test_subclass_with_custom_hash(self
):
225 class H(self
.thetype
):
236 def test_badcmp(self
):
237 s
= self
.thetype([BadCmp()])
238 # Detect comparison errors during insertion and lookup
239 self
.assertRaises(RuntimeError, self
.thetype
, [BadCmp(), BadCmp()])
240 self
.assertRaises(RuntimeError, s
.__contains
__, BadCmp())
241 # Detect errors during mutating operations
242 if hasattr(s
, 'add'):
243 self
.assertRaises(RuntimeError, s
.add
, BadCmp())
244 self
.assertRaises(RuntimeError, s
.discard
, BadCmp())
245 self
.assertRaises(RuntimeError, s
.remove
, BadCmp())
247 class TestSet(TestJointOps
):
252 s
.__init
__(self
.word
)
253 self
.assertEqual(s
, set(self
.word
))
254 s
.__init
__(self
.otherword
)
255 self
.assertEqual(s
, set(self
.otherword
))
256 self
.assertRaises(TypeError, s
.__init
__, s
, 2);
257 self
.assertRaises(TypeError, s
.__init
__, 1);
259 def test_constructor_identity(self
):
260 s
= self
.thetype(range(3))
262 self
.assertNotEqual(id(s
), id(t
))
265 self
.assertRaises(TypeError, hash, self
.s
)
267 def test_clear(self
):
269 self
.assertEqual(self
.s
, set())
270 self
.assertEqual(len(self
.s
), 0)
274 self
.assertEqual(self
.s
, dup
)
275 self
.assertNotEqual(id(self
.s
), id(dup
))
279 self
.assert_('Q' in self
.s
)
282 self
.assertEqual(self
.s
, dup
)
283 self
.assertRaises(TypeError, self
.s
.add
, [])
285 def test_remove(self
):
287 self
.assert_('a' not in self
.s
)
288 self
.assertRaises(KeyError, self
.s
.remove
, 'Q')
289 self
.assertRaises(TypeError, self
.s
.remove
, [])
290 s
= self
.thetype([frozenset(self
.word
)])
291 self
.assert_(self
.thetype(self
.word
) in s
)
292 s
.remove(self
.thetype(self
.word
))
293 self
.assert_(self
.thetype(self
.word
) not in s
)
294 self
.assertRaises(KeyError, self
.s
.remove
, self
.thetype(self
.word
))
296 def test_discard(self
):
298 self
.assert_('a' not in self
.s
)
300 self
.assertRaises(TypeError, self
.s
.discard
, [])
301 s
= self
.thetype([frozenset(self
.word
)])
302 self
.assert_(self
.thetype(self
.word
) in s
)
303 s
.discard(self
.thetype(self
.word
))
304 self
.assert_(self
.thetype(self
.word
) not in s
)
305 s
.discard(self
.thetype(self
.word
))
308 for i
in xrange(len(self
.s
)):
310 self
.assert_(elem
not in self
.s
)
311 self
.assertRaises(KeyError, self
.s
.pop
)
313 def test_update(self
):
314 retval
= self
.s
.update(self
.otherword
)
315 self
.assertEqual(retval
, None)
316 for c
in (self
.word
+ self
.otherword
):
317 self
.assert_(c
in self
.s
)
318 self
.assertRaises(PassThru
, self
.s
.update
, check_pass_thru())
319 self
.assertRaises(TypeError, self
.s
.update
, [[]])
320 for p
, q
in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
321 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
322 s
= self
.thetype('abcba')
323 self
.assertEqual(s
.update(C(p
)), None)
324 self
.assertEqual(s
, set(q
))
327 self
.s |
= set(self
.otherword
)
328 for c
in (self
.word
+ self
.otherword
):
329 self
.assert_(c
in self
.s
)
331 def test_intersection_update(self
):
332 retval
= self
.s
.intersection_update(self
.otherword
)
333 self
.assertEqual(retval
, None)
334 for c
in (self
.word
+ self
.otherword
):
335 if c
in self
.otherword
and c
in self
.word
:
336 self
.assert_(c
in self
.s
)
338 self
.assert_(c
not in self
.s
)
339 self
.assertRaises(PassThru
, self
.s
.intersection_update
, check_pass_thru())
340 self
.assertRaises(TypeError, self
.s
.intersection_update
, [[]])
341 for p
, q
in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')):
342 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
343 s
= self
.thetype('abcba')
344 self
.assertEqual(s
.intersection_update(C(p
)), None)
345 self
.assertEqual(s
, set(q
))
348 self
.s
&= set(self
.otherword
)
349 for c
in (self
.word
+ self
.otherword
):
350 if c
in self
.otherword
and c
in self
.word
:
351 self
.assert_(c
in self
.s
)
353 self
.assert_(c
not in self
.s
)
355 def test_difference_update(self
):
356 retval
= self
.s
.difference_update(self
.otherword
)
357 self
.assertEqual(retval
, None)
358 for c
in (self
.word
+ self
.otherword
):
359 if c
in self
.word
and c
not in self
.otherword
:
360 self
.assert_(c
in self
.s
)
362 self
.assert_(c
not in self
.s
)
363 self
.assertRaises(PassThru
, self
.s
.difference_update
, check_pass_thru())
364 self
.assertRaises(TypeError, self
.s
.difference_update
, [[]])
365 self
.assertRaises(TypeError, self
.s
.symmetric_difference_update
, [[]])
366 for p
, q
in (('cdc', 'ab'), ('efgfe', 'abc'), ('ccb', 'a'), ('ef', 'abc')):
367 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
368 s
= self
.thetype('abcba')
369 self
.assertEqual(s
.difference_update(C(p
)), None)
370 self
.assertEqual(s
, set(q
))
373 self
.s
-= set(self
.otherword
)
374 for c
in (self
.word
+ self
.otherword
):
375 if c
in self
.word
and c
not in self
.otherword
:
376 self
.assert_(c
in self
.s
)
378 self
.assert_(c
not in self
.s
)
380 def test_symmetric_difference_update(self
):
381 retval
= self
.s
.symmetric_difference_update(self
.otherword
)
382 self
.assertEqual(retval
, None)
383 for c
in (self
.word
+ self
.otherword
):
384 if (c
in self
.word
) ^
(c
in self
.otherword
):
385 self
.assert_(c
in self
.s
)
387 self
.assert_(c
not in self
.s
)
388 self
.assertRaises(PassThru
, self
.s
.symmetric_difference_update
, check_pass_thru())
389 self
.assertRaises(TypeError, self
.s
.symmetric_difference_update
, [[]])
390 for p
, q
in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')):
391 for C
in set, frozenset, dict.fromkeys
, str, unicode, list, tuple:
392 s
= self
.thetype('abcba')
393 self
.assertEqual(s
.symmetric_difference_update(C(p
)), None)
394 self
.assertEqual(s
, set(q
))
397 self
.s ^
= set(self
.otherword
)
398 for c
in (self
.word
+ self
.otherword
):
399 if (c
in self
.word
) ^
(c
in self
.otherword
):
400 self
.assert_(c
in self
.s
)
402 self
.assert_(c
not in self
.s
)
404 def test_inplace_on_self(self
):
407 self
.assertEqual(t
, self
.s
)
409 self
.assertEqual(t
, self
.s
)
411 self
.assertEqual(t
, self
.thetype())
414 self
.assertEqual(t
, self
.thetype())
416 def test_weakref(self
):
417 s
= self
.thetype('gallahad')
419 self
.assertEqual(str(p
), str(s
))
421 self
.assertRaises(ReferenceError, str, p
)
423 # C API test only available in a debug build
424 if hasattr(sys
, "gettotalrefcount"):
425 def test_c_api(self
):
426 self
.assertEqual(set('abc').test_c_api(), True)
428 class SetSubclass(set):
431 class TestSetSubclass(TestSet
):
432 thetype
= SetSubclass
434 class TestFrozenSet(TestJointOps
):
438 s
= self
.thetype(self
.word
)
439 s
.__init
__(self
.otherword
)
440 self
.assertEqual(s
, set(self
.word
))
442 def test_singleton_empty_frozenset(self
):
444 efs
= [frozenset(), frozenset([]), frozenset(()), frozenset(''),
445 frozenset(), frozenset([]), frozenset(()), frozenset(''),
446 frozenset(xrange(0)), frozenset(frozenset()),
448 # All of the empty frozensets should have just one id()
449 self
.assertEqual(len(set(map(id, efs
))), 1)
451 def test_constructor_identity(self
):
452 s
= self
.thetype(range(3))
454 self
.assertEqual(id(s
), id(t
))
457 self
.assertEqual(hash(self
.thetype('abcdeb')),
458 hash(self
.thetype('ebecda')))
460 # make sure that all permutations give the same hash value
462 seq
= [randrange(n
) for i
in xrange(n
)]
464 for i
in xrange(200):
466 results
.add(hash(self
.thetype(seq
)))
467 self
.assertEqual(len(results
), 1)
471 self
.assertEqual(id(self
.s
), id(dup
))
473 def test_frozen_as_dictkey(self
):
474 seq
= range(10) + list('abcdefg') + ['apple']
475 key1
= self
.thetype(seq
)
476 key2
= self
.thetype(reversed(seq
))
477 self
.assertEqual(key1
, key2
)
478 self
.assertNotEqual(id(key1
), id(key2
))
481 self
.assertEqual(d
[key2
], 42)
483 def test_hash_caching(self
):
484 f
= self
.thetype('abcdcda')
485 self
.assertEqual(hash(f
), hash(f
))
487 def test_hash_effectiveness(self
):
490 addhashvalue
= hashvalues
.add
491 elemmasks
= [(i
+1, 1<<i
) for i
in range(n
)]
492 for i
in xrange(2**n
):
493 addhashvalue(hash(frozenset([e
for e
, m
in elemmasks
if m
&i
])))
494 self
.assertEqual(len(hashvalues
), 2**n
)
496 class FrozenSetSubclass(frozenset):
499 class TestFrozenSetSubclass(TestFrozenSet
):
500 thetype
= FrozenSetSubclass
502 def test_constructor_identity(self
):
503 s
= self
.thetype(range(3))
505 self
.assertNotEqual(id(s
), id(t
))
509 self
.assertNotEqual(id(self
.s
), id(dup
))
511 def test_nested_empty_constructor(self
):
514 self
.assertEqual(s
, t
)
516 def test_singleton_empty_frozenset(self
):
517 Frozenset
= self
.thetype
520 efs
= [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
521 Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
522 Frozenset(xrange(0)), Frozenset(Frozenset()),
523 Frozenset(frozenset()), f
, F
, Frozenset(f
), Frozenset(F
)]
524 # All empty frozenset subclass instances should have different ids
525 self
.assertEqual(len(set(map(id, efs
))), len(efs
))
527 # Tests taken from test_sets.py =============================================
531 #==============================================================================
533 class TestBasicOps(unittest
.TestCase
):
536 if self
.repr is not None:
537 self
.assertEqual(repr(self
.set), self
.repr)
539 def test_print(self
):
541 fo
= open(test_support
.TESTFN
, "wb")
542 print >> fo
, self
.set,
544 fo
= open(test_support
.TESTFN
, "rb")
545 self
.assertEqual(fo
.read(), repr(self
.set))
548 os
.remove(test_support
.TESTFN
)
550 def test_length(self
):
551 self
.assertEqual(len(self
.set), self
.length
)
553 def test_self_equality(self
):
554 self
.assertEqual(self
.set, self
.set)
556 def test_equivalent_equality(self
):
557 self
.assertEqual(self
.set, self
.dup
)
560 self
.assertEqual(self
.set.copy(), self
.dup
)
562 def test_self_union(self
):
563 result
= self
.set | self
.set
564 self
.assertEqual(result
, self
.dup
)
566 def test_empty_union(self
):
567 result
= self
.set | empty_set
568 self
.assertEqual(result
, self
.dup
)
570 def test_union_empty(self
):
571 result
= empty_set | self
.set
572 self
.assertEqual(result
, self
.dup
)
574 def test_self_intersection(self
):
575 result
= self
.set & self
.set
576 self
.assertEqual(result
, self
.dup
)
578 def test_empty_intersection(self
):
579 result
= self
.set & empty_set
580 self
.assertEqual(result
, empty_set
)
582 def test_intersection_empty(self
):
583 result
= empty_set
& self
.set
584 self
.assertEqual(result
, empty_set
)
586 def test_self_symmetric_difference(self
):
587 result
= self
.set ^ self
.set
588 self
.assertEqual(result
, empty_set
)
590 def checkempty_symmetric_difference(self
):
591 result
= self
.set ^ empty_set
592 self
.assertEqual(result
, self
.set)
594 def test_self_difference(self
):
595 result
= self
.set - self
.set
596 self
.assertEqual(result
, empty_set
)
598 def test_empty_difference(self
):
599 result
= self
.set - empty_set
600 self
.assertEqual(result
, self
.dup
)
602 def test_empty_difference_rev(self
):
603 result
= empty_set
- self
.set
604 self
.assertEqual(result
, empty_set
)
606 def test_iteration(self
):
608 self
.assert_(v
in self
.values
)
609 setiter
= iter(self
.set)
610 # note: __length_hint__ is an internal undocumented API,
611 # don't rely on it in your own programs
612 self
.assertEqual(setiter
.__length
_hint
__(), len(self
.set))
614 def test_pickling(self
):
615 p
= pickle
.dumps(self
.set)
616 copy
= pickle
.loads(p
)
617 self
.assertEqual(self
.set, copy
,
618 "%s != %s" % (self
.set, copy
))
620 #------------------------------------------------------------------------------
622 class TestBasicOpsEmpty(TestBasicOps
):
624 self
.case
= "empty set"
626 self
.set = set(self
.values
)
627 self
.dup
= set(self
.values
)
629 self
.repr = "set([])"
631 #------------------------------------------------------------------------------
633 class TestBasicOpsSingleton(TestBasicOps
):
635 self
.case
= "unit set (number)"
637 self
.set = set(self
.values
)
638 self
.dup
= set(self
.values
)
640 self
.repr = "set([3])"
643 self
.failUnless(3 in self
.set)
645 def test_not_in(self
):
646 self
.failUnless(2 not in self
.set)
648 #------------------------------------------------------------------------------
650 class TestBasicOpsTuple(TestBasicOps
):
652 self
.case
= "unit set (tuple)"
653 self
.values
= [(0, "zero")]
654 self
.set = set(self
.values
)
655 self
.dup
= set(self
.values
)
657 self
.repr = "set([(0, 'zero')])"
660 self
.failUnless((0, "zero") in self
.set)
662 def test_not_in(self
):
663 self
.failUnless(9 not in self
.set)
665 #------------------------------------------------------------------------------
667 class TestBasicOpsTriple(TestBasicOps
):
669 self
.case
= "triple set"
670 self
.values
= [0, "zero", operator
.add
]
671 self
.set = set(self
.values
)
672 self
.dup
= set(self
.values
)
676 #==============================================================================
685 class TestExceptionPropagation(unittest
.TestCase
):
686 """SF 628246: Set constructor should not trap iterator TypeErrors"""
688 def test_instanceWithException(self
):
689 self
.assertRaises(TypeError, set, baditer())
691 def test_instancesWithoutException(self
):
692 # All of these iterables should load without exception.
695 set({'one':1, 'two':2, 'three':3})
700 def test_changingSizeWhileIterating(self
):
708 self
.fail("no exception when changing size during iteration")
710 #==============================================================================
712 class TestSetOfSets(unittest
.TestCase
):
713 def test_constructor(self
):
714 inner
= frozenset([1])
716 element
= outer
.pop()
717 self
.assertEqual(type(element
), frozenset)
718 outer
.add(inner
) # Rebuild set of sets with .add method
720 self
.assertEqual(outer
, set()) # Verify that remove worked
721 outer
.discard(inner
) # Absence of KeyError indicates working fine
723 #==============================================================================
725 class TestBinaryOps(unittest
.TestCase
):
727 self
.set = set((2, 4, 6))
729 def test_eq(self
): # SF bug 643115
730 self
.assertEqual(self
.set, set({2:1,4:3,6:5}))
732 def test_union_subset(self
):
733 result
= self
.set |
set([2])
734 self
.assertEqual(result
, set((2, 4, 6)))
736 def test_union_superset(self
):
737 result
= self
.set |
set([2, 4, 6, 8])
738 self
.assertEqual(result
, set([2, 4, 6, 8]))
740 def test_union_overlap(self
):
741 result
= self
.set |
set([3, 4, 5])
742 self
.assertEqual(result
, set([2, 3, 4, 5, 6]))
744 def test_union_non_overlap(self
):
745 result
= self
.set |
set([8])
746 self
.assertEqual(result
, set([2, 4, 6, 8]))
748 def test_intersection_subset(self
):
749 result
= self
.set & set((2, 4))
750 self
.assertEqual(result
, set((2, 4)))
752 def test_intersection_superset(self
):
753 result
= self
.set & set([2, 4, 6, 8])
754 self
.assertEqual(result
, set([2, 4, 6]))
756 def test_intersection_overlap(self
):
757 result
= self
.set & set([3, 4, 5])
758 self
.assertEqual(result
, set([4]))
760 def test_intersection_non_overlap(self
):
761 result
= self
.set & set([8])
762 self
.assertEqual(result
, empty_set
)
764 def test_sym_difference_subset(self
):
765 result
= self
.set ^
set((2, 4))
766 self
.assertEqual(result
, set([6]))
768 def test_sym_difference_superset(self
):
769 result
= self
.set ^
set((2, 4, 6, 8))
770 self
.assertEqual(result
, set([8]))
772 def test_sym_difference_overlap(self
):
773 result
= self
.set ^
set((3, 4, 5))
774 self
.assertEqual(result
, set([2, 3, 5, 6]))
776 def test_sym_difference_non_overlap(self
):
777 result
= self
.set ^
set([8])
778 self
.assertEqual(result
, set([2, 4, 6, 8]))
781 a
, b
= set('a'), set('b')
782 self
.assertRaises(TypeError, cmp, a
, b
)
784 # You can view this as a buglet: cmp(a, a) does not raise TypeError,
785 # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True,
786 # which Python thinks is good enough to synthesize a cmp() result
787 # without calling __cmp__.
788 self
.assertEqual(cmp(a
, a
), 0)
790 self
.assertRaises(TypeError, cmp, a
, 12)
791 self
.assertRaises(TypeError, cmp, "abc", a
)
793 #==============================================================================
795 class TestUpdateOps(unittest
.TestCase
):
797 self
.set = set((2, 4, 6))
799 def test_union_subset(self
):
801 self
.assertEqual(self
.set, set((2, 4, 6)))
803 def test_union_superset(self
):
804 self
.set |
= set([2, 4, 6, 8])
805 self
.assertEqual(self
.set, set([2, 4, 6, 8]))
807 def test_union_overlap(self
):
808 self
.set |
= set([3, 4, 5])
809 self
.assertEqual(self
.set, set([2, 3, 4, 5, 6]))
811 def test_union_non_overlap(self
):
813 self
.assertEqual(self
.set, set([2, 4, 6, 8]))
815 def test_union_method_call(self
):
816 self
.set.update(set([3, 4, 5]))
817 self
.assertEqual(self
.set, set([2, 3, 4, 5, 6]))
819 def test_intersection_subset(self
):
820 self
.set &= set((2, 4))
821 self
.assertEqual(self
.set, set((2, 4)))
823 def test_intersection_superset(self
):
824 self
.set &= set([2, 4, 6, 8])
825 self
.assertEqual(self
.set, set([2, 4, 6]))
827 def test_intersection_overlap(self
):
828 self
.set &= set([3, 4, 5])
829 self
.assertEqual(self
.set, set([4]))
831 def test_intersection_non_overlap(self
):
833 self
.assertEqual(self
.set, empty_set
)
835 def test_intersection_method_call(self
):
836 self
.set.intersection_update(set([3, 4, 5]))
837 self
.assertEqual(self
.set, set([4]))
839 def test_sym_difference_subset(self
):
840 self
.set ^
= set((2, 4))
841 self
.assertEqual(self
.set, set([6]))
843 def test_sym_difference_superset(self
):
844 self
.set ^
= set((2, 4, 6, 8))
845 self
.assertEqual(self
.set, set([8]))
847 def test_sym_difference_overlap(self
):
848 self
.set ^
= set((3, 4, 5))
849 self
.assertEqual(self
.set, set([2, 3, 5, 6]))
851 def test_sym_difference_non_overlap(self
):
853 self
.assertEqual(self
.set, set([2, 4, 6, 8]))
855 def test_sym_difference_method_call(self
):
856 self
.set.symmetric_difference_update(set([3, 4, 5]))
857 self
.assertEqual(self
.set, set([2, 3, 5, 6]))
859 def test_difference_subset(self
):
860 self
.set -= set((2, 4))
861 self
.assertEqual(self
.set, set([6]))
863 def test_difference_superset(self
):
864 self
.set -= set((2, 4, 6, 8))
865 self
.assertEqual(self
.set, set([]))
867 def test_difference_overlap(self
):
868 self
.set -= set((3, 4, 5))
869 self
.assertEqual(self
.set, set([2, 6]))
871 def test_difference_non_overlap(self
):
873 self
.assertEqual(self
.set, set([2, 4, 6]))
875 def test_difference_method_call(self
):
876 self
.set.difference_update(set([3, 4, 5]))
877 self
.assertEqual(self
.set, set([2, 6]))
879 #==============================================================================
881 class TestMutate(unittest
.TestCase
):
883 self
.values
= ["a", "b", "c"]
884 self
.set = set(self
.values
)
886 def test_add_present(self
):
888 self
.assertEqual(self
.set, set("abc"))
890 def test_add_absent(self
):
892 self
.assertEqual(self
.set, set("abcd"))
894 def test_add_until_full(self
):
897 for v
in self
.values
:
900 self
.assertEqual(len(tmp
), expected_len
)
901 self
.assertEqual(tmp
, self
.set)
903 def test_remove_present(self
):
905 self
.assertEqual(self
.set, set("ac"))
907 def test_remove_absent(self
):
910 self
.fail("Removing missing element should have raised LookupError")
914 def test_remove_until_empty(self
):
915 expected_len
= len(self
.set)
916 for v
in self
.values
:
919 self
.assertEqual(len(self
.set), expected_len
)
921 def test_discard_present(self
):
922 self
.set.discard("c")
923 self
.assertEqual(self
.set, set("ab"))
925 def test_discard_absent(self
):
926 self
.set.discard("d")
927 self
.assertEqual(self
.set, set("abc"))
929 def test_clear(self
):
931 self
.assertEqual(len(self
.set), 0)
936 popped
[self
.set.pop()] = None
937 self
.assertEqual(len(popped
), len(self
.values
))
938 for v
in self
.values
:
939 self
.failUnless(v
in popped
)
941 def test_update_empty_tuple(self
):
943 self
.assertEqual(self
.set, set(self
.values
))
945 def test_update_unit_tuple_overlap(self
):
946 self
.set.update(("a",))
947 self
.assertEqual(self
.set, set(self
.values
))
949 def test_update_unit_tuple_non_overlap(self
):
950 self
.set.update(("a", "z"))
951 self
.assertEqual(self
.set, set(self
.values
+ ["z"]))
953 #==============================================================================
955 class TestSubsets(unittest
.TestCase
):
957 case2method
= {"<=": "issubset",
961 reverse
= {"==": "==",
969 def test_issubset(self
):
972 for case
in "!=", "==", "<", "<=", ">", ">=":
973 expected
= case
in self
.cases
974 # Test the binary infix spelling.
975 result
= eval("x" + case
+ "y", locals())
976 self
.assertEqual(result
, expected
)
977 # Test the "friendly" method-name spelling, if one exists.
978 if case
in TestSubsets
.case2method
:
979 method
= getattr(x
, TestSubsets
.case2method
[case
])
981 self
.assertEqual(result
, expected
)
983 # Now do the same for the operands reversed.
984 rcase
= TestSubsets
.reverse
[case
]
985 result
= eval("y" + rcase
+ "x", locals())
986 self
.assertEqual(result
, expected
)
987 if rcase
in TestSubsets
.case2method
:
988 method
= getattr(y
, TestSubsets
.case2method
[rcase
])
990 self
.assertEqual(result
, expected
)
991 #------------------------------------------------------------------------------
993 class TestSubsetEqualEmpty(TestSubsets
):
997 cases
= "==", "<=", ">="
999 #------------------------------------------------------------------------------
1001 class TestSubsetEqualNonEmpty(TestSubsets
):
1005 cases
= "==", "<=", ">="
1007 #------------------------------------------------------------------------------
1009 class TestSubsetEmptyNonEmpty(TestSubsets
):
1012 name
= "one empty, one non-empty"
1013 cases
= "!=", "<", "<="
1015 #------------------------------------------------------------------------------
1017 class TestSubsetPartial(TestSubsets
):
1020 name
= "one a non-empty proper subset of other"
1021 cases
= "!=", "<", "<="
1023 #------------------------------------------------------------------------------
1025 class TestSubsetNonOverlap(TestSubsets
):
1028 name
= "neither empty, neither contains"
1031 #==============================================================================
1033 class TestOnlySetsInBinaryOps(unittest
.TestCase
):
1035 def test_eq_ne(self
):
1036 # Unlike the others, this is testing that == and != *are* allowed.
1037 self
.assertEqual(self
.other
== self
.set, False)
1038 self
.assertEqual(self
.set == self
.other
, False)
1039 self
.assertEqual(self
.other
!= self
.set, True)
1040 self
.assertEqual(self
.set != self
.other
, True)
1042 def test_ge_gt_le_lt(self
):
1043 self
.assertRaises(TypeError, lambda: self
.set < self
.other
)
1044 self
.assertRaises(TypeError, lambda: self
.set <= self
.other
)
1045 self
.assertRaises(TypeError, lambda: self
.set > self
.other
)
1046 self
.assertRaises(TypeError, lambda: self
.set >= self
.other
)
1048 self
.assertRaises(TypeError, lambda: self
.other
< self
.set)
1049 self
.assertRaises(TypeError, lambda: self
.other
<= self
.set)
1050 self
.assertRaises(TypeError, lambda: self
.other
> self
.set)
1051 self
.assertRaises(TypeError, lambda: self
.other
>= self
.set)
1053 def test_update_operator(self
):
1055 self
.set |
= self
.other
1059 self
.fail("expected TypeError")
1061 def test_update(self
):
1062 if self
.otherIsIterable
:
1063 self
.set.update(self
.other
)
1065 self
.assertRaises(TypeError, self
.set.update
, self
.other
)
1067 def test_union(self
):
1068 self
.assertRaises(TypeError, lambda: self
.set | self
.other
)
1069 self
.assertRaises(TypeError, lambda: self
.other | self
.set)
1070 if self
.otherIsIterable
:
1071 self
.set.union(self
.other
)
1073 self
.assertRaises(TypeError, self
.set.union
, self
.other
)
1075 def test_intersection_update_operator(self
):
1077 self
.set &= self
.other
1081 self
.fail("expected TypeError")
1083 def test_intersection_update(self
):
1084 if self
.otherIsIterable
:
1085 self
.set.intersection_update(self
.other
)
1087 self
.assertRaises(TypeError,
1088 self
.set.intersection_update
,
1091 def test_intersection(self
):
1092 self
.assertRaises(TypeError, lambda: self
.set & self
.other
)
1093 self
.assertRaises(TypeError, lambda: self
.other
& self
.set)
1094 if self
.otherIsIterable
:
1095 self
.set.intersection(self
.other
)
1097 self
.assertRaises(TypeError, self
.set.intersection
, self
.other
)
1099 def test_sym_difference_update_operator(self
):
1101 self
.set ^
= self
.other
1105 self
.fail("expected TypeError")
1107 def test_sym_difference_update(self
):
1108 if self
.otherIsIterable
:
1109 self
.set.symmetric_difference_update(self
.other
)
1111 self
.assertRaises(TypeError,
1112 self
.set.symmetric_difference_update
,
1115 def test_sym_difference(self
):
1116 self
.assertRaises(TypeError, lambda: self
.set ^ self
.other
)
1117 self
.assertRaises(TypeError, lambda: self
.other ^ self
.set)
1118 if self
.otherIsIterable
:
1119 self
.set.symmetric_difference(self
.other
)
1121 self
.assertRaises(TypeError, self
.set.symmetric_difference
, self
.other
)
1123 def test_difference_update_operator(self
):
1125 self
.set -= self
.other
1129 self
.fail("expected TypeError")
1131 def test_difference_update(self
):
1132 if self
.otherIsIterable
:
1133 self
.set.difference_update(self
.other
)
1135 self
.assertRaises(TypeError,
1136 self
.set.difference_update
,
1139 def test_difference(self
):
1140 self
.assertRaises(TypeError, lambda: self
.set - self
.other
)
1141 self
.assertRaises(TypeError, lambda: self
.other
- self
.set)
1142 if self
.otherIsIterable
:
1143 self
.set.difference(self
.other
)
1145 self
.assertRaises(TypeError, self
.set.difference
, self
.other
)
1147 #------------------------------------------------------------------------------
1149 class TestOnlySetsNumeric(TestOnlySetsInBinaryOps
):
1151 self
.set = set((1, 2, 3))
1153 self
.otherIsIterable
= False
1155 #------------------------------------------------------------------------------
1157 class TestOnlySetsDict(TestOnlySetsInBinaryOps
):
1159 self
.set = set((1, 2, 3))
1160 self
.other
= {1:2, 3:4}
1161 self
.otherIsIterable
= True
1163 #------------------------------------------------------------------------------
1165 class TestOnlySetsOperator(TestOnlySetsInBinaryOps
):
1167 self
.set = set((1, 2, 3))
1168 self
.other
= operator
.add
1169 self
.otherIsIterable
= False
1171 #------------------------------------------------------------------------------
1173 class TestOnlySetsTuple(TestOnlySetsInBinaryOps
):
1175 self
.set = set((1, 2, 3))
1176 self
.other
= (2, 4, 6)
1177 self
.otherIsIterable
= True
1179 #------------------------------------------------------------------------------
1181 class TestOnlySetsString(TestOnlySetsInBinaryOps
):
1183 self
.set = set((1, 2, 3))
1185 self
.otherIsIterable
= True
1187 #------------------------------------------------------------------------------
1189 class TestOnlySetsGenerator(TestOnlySetsInBinaryOps
):
1192 for i
in xrange(0, 10, 2):
1194 self
.set = set((1, 2, 3))
1196 self
.otherIsIterable
= True
1198 #==============================================================================
1200 class TestCopying(unittest
.TestCase
):
1202 def test_copy(self
):
1203 dup
= self
.set.copy()
1204 dup_list
= list(dup
); dup_list
.sort()
1205 set_list
= list(self
.set); set_list
.sort()
1206 self
.assertEqual(len(dup_list
), len(set_list
))
1207 for i
in range(len(dup_list
)):
1208 self
.failUnless(dup_list
[i
] is set_list
[i
])
1210 def test_deep_copy(self
):
1211 dup
= copy
.deepcopy(self
.set)
1212 ##print type(dup), repr(dup)
1213 dup_list
= list(dup
); dup_list
.sort()
1214 set_list
= list(self
.set); set_list
.sort()
1215 self
.assertEqual(len(dup_list
), len(set_list
))
1216 for i
in range(len(dup_list
)):
1217 self
.assertEqual(dup_list
[i
], set_list
[i
])
1219 #------------------------------------------------------------------------------
1221 class TestCopyingEmpty(TestCopying
):
1225 #------------------------------------------------------------------------------
1227 class TestCopyingSingleton(TestCopying
):
1229 self
.set = set(["hello"])
1231 #------------------------------------------------------------------------------
1233 class TestCopyingTriple(TestCopying
):
1235 self
.set = set(["zero", 0, None])
1237 #------------------------------------------------------------------------------
1239 class TestCopyingTuple(TestCopying
):
1241 self
.set = set([(1, 2)])
1243 #------------------------------------------------------------------------------
1245 class TestCopyingNested(TestCopying
):
1247 self
.set = set([((1, 2), (3, 4))])
1249 #==============================================================================
1251 class TestIdentities(unittest
.TestCase
):
1253 self
.a
= set('abracadabra')
1254 self
.b
= set('alacazam')
1256 def test_binopsVsSubsets(self
):
1257 a
, b
= self
.a
, self
.b
1258 self
.assert_(a
- b
< a
)
1259 self
.assert_(b
- a
< b
)
1260 self
.assert_(a
& b
< a
)
1261 self
.assert_(a
& b
< b
)
1262 self
.assert_(a | b
> a
)
1263 self
.assert_(a | b
> b
)
1264 self
.assert_(a ^ b
< a | b
)
1266 def test_commutativity(self
):
1267 a
, b
= self
.a
, self
.b
1268 self
.assertEqual(a
&b
, b
&a
)
1269 self
.assertEqual(a|b
, b|a
)
1270 self
.assertEqual(a^b
, b^a
)
1272 self
.assertNotEqual(a
-b
, b
-a
)
1274 def test_summations(self
):
1275 # check that sums of parts equal the whole
1276 a
, b
= self
.a
, self
.b
1277 self
.assertEqual((a
-b
)|
(a
&b
)|
(b
-a
), a|b
)
1278 self
.assertEqual((a
&b
)|
(a^b
), a|b
)
1279 self
.assertEqual(a|
(b
-a
), a|b
)
1280 self
.assertEqual((a
-b
)|b
, a|b
)
1281 self
.assertEqual((a
-b
)|
(a
&b
), a
)
1282 self
.assertEqual((b
-a
)|
(a
&b
), b
)
1283 self
.assertEqual((a
-b
)|
(b
-a
), a^b
)
1285 def test_exclusion(self
):
1286 # check that inverse operations show non-overlap
1287 a
, b
, zero
= self
.a
, self
.b
, set()
1288 self
.assertEqual((a
-b
)&b
, zero
)
1289 self
.assertEqual((b
-a
)&a
, zero
)
1290 self
.assertEqual((a
&b
)&(a^b
), zero
)
1292 # Tests derived from test_itertools.py =======================================
1300 'Sequence using __getitem__'
1301 def __init__(self
, seqn
):
1303 def __getitem__(self
, i
):
1307 'Sequence using iterator protocol'
1308 def __init__(self
, seqn
):
1314 if self
.i
>= len(self
.seqn
): raise StopIteration
1315 v
= self
.seqn
[self
.i
]
1320 'Sequence using iterator protocol defined with a generator'
1321 def __init__(self
, seqn
):
1325 for val
in self
.seqn
:
1329 'Missing __getitem__ and __iter__'
1330 def __init__(self
, seqn
):
1334 if self
.i
>= len(self
.seqn
): raise StopIteration
1335 v
= self
.seqn
[self
.i
]
1340 'Iterator missing next()'
1341 def __init__(self
, seqn
):
1348 'Test propagation of exceptions'
1349 def __init__(self
, seqn
):
1358 'Test immediate stop'
1359 def __init__(self
, seqn
):
1366 from itertools
import chain
, imap
1368 'Test multiple tiers of iterators'
1369 return chain(imap(lambda x
:x
, R(Ig(G(seqn
)))))
1371 class TestVariousIteratorArgs(unittest
.TestCase
):
1373 def test_constructor(self
):
1374 for cons
in (set, frozenset):
1375 for s
in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
1376 for g
in (G
, I
, Ig
, S
, L
, R
):
1377 self
.assertEqual(sorted(cons(g(s
))), sorted(g(s
)))
1378 self
.assertRaises(TypeError, cons
, X(s
))
1379 self
.assertRaises(TypeError, cons
, N(s
))
1380 self
.assertRaises(ZeroDivisionError, cons
, E(s
))
1382 def test_inline_methods(self
):
1384 for data
in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5), 'december'):
1385 for meth
in (s
.union
, s
.intersection
, s
.difference
, s
.symmetric_difference
):
1386 for g
in (G
, I
, Ig
, L
, R
):
1387 expected
= meth(data
)
1388 actual
= meth(G(data
))
1389 self
.assertEqual(sorted(actual
), sorted(expected
))
1390 self
.assertRaises(TypeError, meth
, X(s
))
1391 self
.assertRaises(TypeError, meth
, N(s
))
1392 self
.assertRaises(ZeroDivisionError, meth
, E(s
))
1394 def test_inplace_methods(self
):
1395 for data
in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5), 'december'):
1396 for methname
in ('update', 'intersection_update',
1397 'difference_update', 'symmetric_difference_update'):
1398 for g
in (G
, I
, Ig
, S
, L
, R
):
1401 getattr(s
, methname
)(list(g(data
)))
1402 getattr(t
, methname
)(g(data
))
1403 self
.assertEqual(sorted(s
), sorted(t
))
1405 self
.assertRaises(TypeError, getattr(set('january'), methname
), X(data
))
1406 self
.assertRaises(TypeError, getattr(set('january'), methname
), N(data
))
1407 self
.assertRaises(ZeroDivisionError, getattr(set('january'), methname
), E(data
))
1409 #==============================================================================
1411 def test_main(verbose
=None):
1412 from test
import test_sets
1417 TestFrozenSetSubclass
,
1419 TestExceptionPropagation
,
1421 TestBasicOpsSingleton
,
1427 TestSubsetEqualEmpty
,
1428 TestSubsetEqualNonEmpty
,
1429 TestSubsetEmptyNonEmpty
,
1431 TestSubsetNonOverlap
,
1432 TestOnlySetsNumeric
,
1434 TestOnlySetsOperator
,
1437 TestOnlySetsGenerator
,
1439 TestCopyingSingleton
,
1444 TestVariousIteratorArgs
,
1447 test_support
.run_unittest(*test_classes
)
1449 # verify reference counting
1450 if verbose
and hasattr(sys
, "gettotalrefcount"):
1453 for i
in xrange(len(counts
)):
1454 test_support
.run_unittest(*test_classes
)
1456 counts
[i
] = sys
.gettotalrefcount()
1459 if __name__
== "__main__":
1460 test_main(verbose
=True)