ยปCore Development>Code coverage>Lib/test/test_set.py

Python code coverage for Lib/test/test_set.py

#countcontent
1n/aimport unittest
2n/afrom test import support
3n/aimport gc
4n/aimport weakref
5n/aimport operator
6n/aimport copy
7n/aimport pickle
8n/afrom random import randrange, shuffle
9n/aimport warnings
10n/aimport collections
11n/aimport collections.abc
12n/aimport itertools
13n/a
14n/aclass PassThru(Exception):
15n/a pass
16n/a
17n/adef check_pass_thru():
18n/a raise PassThru
19n/a yield 1
20n/a
21n/aclass BadCmp:
22n/a def __hash__(self):
23n/a return 1
24n/a def __eq__(self, other):
25n/a raise RuntimeError
26n/a
27n/aclass ReprWrapper:
28n/a 'Used to test self-referential repr() calls'
29n/a def __repr__(self):
30n/a return repr(self.value)
31n/a
32n/aclass HashCountingInt(int):
33n/a 'int-like object that counts the number of times __hash__ is called'
34n/a def __init__(self, *args):
35n/a self.hash_count = 0
36n/a def __hash__(self):
37n/a self.hash_count += 1
38n/a return int.__hash__(self)
39n/a
40n/aclass TestJointOps:
41n/a # Tests common to both set and frozenset
42n/a
43n/a def setUp(self):
44n/a self.word = word = 'simsalabim'
45n/a self.otherword = 'madagascar'
46n/a self.letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
47n/a self.s = self.thetype(word)
48n/a self.d = dict.fromkeys(word)
49n/a
50n/a def test_new_or_init(self):
51n/a self.assertRaises(TypeError, self.thetype, [], 2)
52n/a self.assertRaises(TypeError, set().__init__, a=1)
53n/a
54n/a def test_uniquification(self):
55n/a actual = sorted(self.s)
56n/a expected = sorted(self.d)
57n/a self.assertEqual(actual, expected)
58n/a self.assertRaises(PassThru, self.thetype, check_pass_thru())
59n/a self.assertRaises(TypeError, self.thetype, [[]])
60n/a
61n/a def test_len(self):
62n/a self.assertEqual(len(self.s), len(self.d))
63n/a
64n/a def test_contains(self):
65n/a for c in self.letters:
66n/a self.assertEqual(c in self.s, c in self.d)
67n/a self.assertRaises(TypeError, self.s.__contains__, [[]])
68n/a s = self.thetype([frozenset(self.letters)])
69n/a self.assertIn(self.thetype(self.letters), s)
70n/a
71n/a def test_union(self):
72n/a u = self.s.union(self.otherword)
73n/a for c in self.letters:
74n/a self.assertEqual(c in u, c in self.d or c in self.otherword)
75n/a self.assertEqual(self.s, self.thetype(self.word))
76n/a self.assertEqual(type(u), self.basetype)
77n/a self.assertRaises(PassThru, self.s.union, check_pass_thru())
78n/a self.assertRaises(TypeError, self.s.union, [[]])
79n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
80n/a self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd'))
81n/a self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg'))
82n/a self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc'))
83n/a self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef'))
84n/a self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg'))
85n/a
86n/a # Issue #6573
87n/a x = self.thetype()
88n/a self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2]))
89n/a
90n/a def test_or(self):
91n/a i = self.s.union(self.otherword)
92n/a self.assertEqual(self.s | set(self.otherword), i)
93n/a self.assertEqual(self.s | frozenset(self.otherword), i)
94n/a try:
95n/a self.s | self.otherword
96n/a except TypeError:
97n/a pass
98n/a else:
99n/a self.fail("s|t did not screen-out general iterables")
100n/a
101n/a def test_intersection(self):
102n/a i = self.s.intersection(self.otherword)
103n/a for c in self.letters:
104n/a self.assertEqual(c in i, c in self.d and c in self.otherword)
105n/a self.assertEqual(self.s, self.thetype(self.word))
106n/a self.assertEqual(type(i), self.basetype)
107n/a self.assertRaises(PassThru, self.s.intersection, check_pass_thru())
108n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
109n/a self.assertEqual(self.thetype('abcba').intersection(C('cdc')), set('cc'))
110n/a self.assertEqual(self.thetype('abcba').intersection(C('efgfe')), set(''))
111n/a self.assertEqual(self.thetype('abcba').intersection(C('ccb')), set('bc'))
112n/a self.assertEqual(self.thetype('abcba').intersection(C('ef')), set(''))
113n/a self.assertEqual(self.thetype('abcba').intersection(C('cbcf'), C('bag')), set('b'))
114n/a s = self.thetype('abcba')
115n/a z = s.intersection()
116n/a if self.thetype == frozenset():
117n/a self.assertEqual(id(s), id(z))
118n/a else:
119n/a self.assertNotEqual(id(s), id(z))
120n/a
121n/a def test_isdisjoint(self):
122n/a def f(s1, s2):
123n/a 'Pure python equivalent of isdisjoint()'
124n/a return not set(s1).intersection(s2)
125n/a for larg in '', 'a', 'ab', 'abc', 'ababac', 'cdc', 'cc', 'efgfe', 'ccb', 'ef':
126n/a s1 = self.thetype(larg)
127n/a for rarg in '', 'a', 'ab', 'abc', 'ababac', 'cdc', 'cc', 'efgfe', 'ccb', 'ef':
128n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
129n/a s2 = C(rarg)
130n/a actual = s1.isdisjoint(s2)
131n/a expected = f(s1, s2)
132n/a self.assertEqual(actual, expected)
133n/a self.assertTrue(actual is True or actual is False)
134n/a
135n/a def test_and(self):
136n/a i = self.s.intersection(self.otherword)
137n/a self.assertEqual(self.s & set(self.otherword), i)
138n/a self.assertEqual(self.s & frozenset(self.otherword), i)
139n/a try:
140n/a self.s & self.otherword
141n/a except TypeError:
142n/a pass
143n/a else:
144n/a self.fail("s&t did not screen-out general iterables")
145n/a
146n/a def test_difference(self):
147n/a i = self.s.difference(self.otherword)
148n/a for c in self.letters:
149n/a self.assertEqual(c in i, c in self.d and c not in self.otherword)
150n/a self.assertEqual(self.s, self.thetype(self.word))
151n/a self.assertEqual(type(i), self.basetype)
152n/a self.assertRaises(PassThru, self.s.difference, check_pass_thru())
153n/a self.assertRaises(TypeError, self.s.difference, [[]])
154n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
155n/a self.assertEqual(self.thetype('abcba').difference(C('cdc')), set('ab'))
156n/a self.assertEqual(self.thetype('abcba').difference(C('efgfe')), set('abc'))
157n/a self.assertEqual(self.thetype('abcba').difference(C('ccb')), set('a'))
158n/a self.assertEqual(self.thetype('abcba').difference(C('ef')), set('abc'))
159n/a self.assertEqual(self.thetype('abcba').difference(), set('abc'))
160n/a self.assertEqual(self.thetype('abcba').difference(C('a'), C('b')), set('c'))
161n/a
162n/a def test_sub(self):
163n/a i = self.s.difference(self.otherword)
164n/a self.assertEqual(self.s - set(self.otherword), i)
165n/a self.assertEqual(self.s - frozenset(self.otherword), i)
166n/a try:
167n/a self.s - self.otherword
168n/a except TypeError:
169n/a pass
170n/a else:
171n/a self.fail("s-t did not screen-out general iterables")
172n/a
173n/a def test_symmetric_difference(self):
174n/a i = self.s.symmetric_difference(self.otherword)
175n/a for c in self.letters:
176n/a self.assertEqual(c in i, (c in self.d) ^ (c in self.otherword))
177n/a self.assertEqual(self.s, self.thetype(self.word))
178n/a self.assertEqual(type(i), self.basetype)
179n/a self.assertRaises(PassThru, self.s.symmetric_difference, check_pass_thru())
180n/a self.assertRaises(TypeError, self.s.symmetric_difference, [[]])
181n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
182n/a self.assertEqual(self.thetype('abcba').symmetric_difference(C('cdc')), set('abd'))
183n/a self.assertEqual(self.thetype('abcba').symmetric_difference(C('efgfe')), set('abcefg'))
184n/a self.assertEqual(self.thetype('abcba').symmetric_difference(C('ccb')), set('a'))
185n/a self.assertEqual(self.thetype('abcba').symmetric_difference(C('ef')), set('abcef'))
186n/a
187n/a def test_xor(self):
188n/a i = self.s.symmetric_difference(self.otherword)
189n/a self.assertEqual(self.s ^ set(self.otherword), i)
190n/a self.assertEqual(self.s ^ frozenset(self.otherword), i)
191n/a try:
192n/a self.s ^ self.otherword
193n/a except TypeError:
194n/a pass
195n/a else:
196n/a self.fail("s^t did not screen-out general iterables")
197n/a
198n/a def test_equality(self):
199n/a self.assertEqual(self.s, set(self.word))
200n/a self.assertEqual(self.s, frozenset(self.word))
201n/a self.assertEqual(self.s == self.word, False)
202n/a self.assertNotEqual(self.s, set(self.otherword))
203n/a self.assertNotEqual(self.s, frozenset(self.otherword))
204n/a self.assertEqual(self.s != self.word, True)
205n/a
206n/a def test_setOfFrozensets(self):
207n/a t = map(frozenset, ['abcdef', 'bcd', 'bdcb', 'fed', 'fedccba'])
208n/a s = self.thetype(t)
209n/a self.assertEqual(len(s), 3)
210n/a
211n/a def test_sub_and_super(self):
212n/a p, q, r = map(self.thetype, ['ab', 'abcde', 'def'])
213n/a self.assertTrue(p < q)
214n/a self.assertTrue(p <= q)
215n/a self.assertTrue(q <= q)
216n/a self.assertTrue(q > p)
217n/a self.assertTrue(q >= p)
218n/a self.assertFalse(q < r)
219n/a self.assertFalse(q <= r)
220n/a self.assertFalse(q > r)
221n/a self.assertFalse(q >= r)
222n/a self.assertTrue(set('a').issubset('abc'))
223n/a self.assertTrue(set('abc').issuperset('a'))
224n/a self.assertFalse(set('a').issubset('cbs'))
225n/a self.assertFalse(set('cbs').issuperset('a'))
226n/a
227n/a def test_pickling(self):
228n/a for i in range(pickle.HIGHEST_PROTOCOL + 1):
229n/a p = pickle.dumps(self.s, i)
230n/a dup = pickle.loads(p)
231n/a self.assertEqual(self.s, dup, "%s != %s" % (self.s, dup))
232n/a if type(self.s) not in (set, frozenset):
233n/a self.s.x = 10
234n/a p = pickle.dumps(self.s, i)
235n/a dup = pickle.loads(p)
236n/a self.assertEqual(self.s.x, dup.x)
237n/a
238n/a def test_iterator_pickling(self):
239n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
240n/a itorg = iter(self.s)
241n/a data = self.thetype(self.s)
242n/a d = pickle.dumps(itorg, proto)
243n/a it = pickle.loads(d)
244n/a # Set iterators unpickle as list iterators due to the
245n/a # undefined order of set items.
246n/a # self.assertEqual(type(itorg), type(it))
247n/a self.assertIsInstance(it, collections.abc.Iterator)
248n/a self.assertEqual(self.thetype(it), data)
249n/a
250n/a it = pickle.loads(d)
251n/a try:
252n/a drop = next(it)
253n/a except StopIteration:
254n/a continue
255n/a d = pickle.dumps(it, proto)
256n/a it = pickle.loads(d)
257n/a self.assertEqual(self.thetype(it), data - self.thetype((drop,)))
258n/a
259n/a def test_deepcopy(self):
260n/a class Tracer:
261n/a def __init__(self, value):
262n/a self.value = value
263n/a def __hash__(self):
264n/a return self.value
265n/a def __deepcopy__(self, memo=None):
266n/a return Tracer(self.value + 1)
267n/a t = Tracer(10)
268n/a s = self.thetype([t])
269n/a dup = copy.deepcopy(s)
270n/a self.assertNotEqual(id(s), id(dup))
271n/a for elem in dup:
272n/a newt = elem
273n/a self.assertNotEqual(id(t), id(newt))
274n/a self.assertEqual(t.value + 1, newt.value)
275n/a
276n/a def test_gc(self):
277n/a # Create a nest of cycles to exercise overall ref count check
278n/a class A:
279n/a pass
280n/a s = set(A() for i in range(1000))
281n/a for elem in s:
282n/a elem.cycle = s
283n/a elem.sub = elem
284n/a elem.set = set([elem])
285n/a
286n/a def test_subclass_with_custom_hash(self):
287n/a # Bug #1257731
288n/a class H(self.thetype):
289n/a def __hash__(self):
290n/a return int(id(self) & 0x7fffffff)
291n/a s=H()
292n/a f=set()
293n/a f.add(s)
294n/a self.assertIn(s, f)
295n/a f.remove(s)
296n/a f.add(s)
297n/a f.discard(s)
298n/a
299n/a def test_badcmp(self):
300n/a s = self.thetype([BadCmp()])
301n/a # Detect comparison errors during insertion and lookup
302n/a self.assertRaises(RuntimeError, self.thetype, [BadCmp(), BadCmp()])
303n/a self.assertRaises(RuntimeError, s.__contains__, BadCmp())
304n/a # Detect errors during mutating operations
305n/a if hasattr(s, 'add'):
306n/a self.assertRaises(RuntimeError, s.add, BadCmp())
307n/a self.assertRaises(RuntimeError, s.discard, BadCmp())
308n/a self.assertRaises(RuntimeError, s.remove, BadCmp())
309n/a
310n/a def test_cyclical_repr(self):
311n/a w = ReprWrapper()
312n/a s = self.thetype([w])
313n/a w.value = s
314n/a if self.thetype == set:
315n/a self.assertEqual(repr(s), '{set(...)}')
316n/a else:
317n/a name = repr(s).partition('(')[0] # strip class name
318n/a self.assertEqual(repr(s), '%s({%s(...)})' % (name, name))
319n/a
320n/a def test_cyclical_print(self):
321n/a w = ReprWrapper()
322n/a s = self.thetype([w])
323n/a w.value = s
324n/a fo = open(support.TESTFN, "w")
325n/a try:
326n/a fo.write(str(s))
327n/a fo.close()
328n/a fo = open(support.TESTFN, "r")
329n/a self.assertEqual(fo.read(), repr(s))
330n/a finally:
331n/a fo.close()
332n/a support.unlink(support.TESTFN)
333n/a
334n/a def test_do_not_rehash_dict_keys(self):
335n/a n = 10
336n/a d = dict.fromkeys(map(HashCountingInt, range(n)))
337n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
338n/a s = self.thetype(d)
339n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
340n/a s.difference(d)
341n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
342n/a if hasattr(s, 'symmetric_difference_update'):
343n/a s.symmetric_difference_update(d)
344n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
345n/a d2 = dict.fromkeys(set(d))
346n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
347n/a d3 = dict.fromkeys(frozenset(d))
348n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
349n/a d3 = dict.fromkeys(frozenset(d), 123)
350n/a self.assertEqual(sum(elem.hash_count for elem in d), n)
351n/a self.assertEqual(d3, dict.fromkeys(d, 123))
352n/a
353n/a def test_container_iterator(self):
354n/a # Bug #3680: tp_traverse was not implemented for set iterator object
355n/a class C(object):
356n/a pass
357n/a obj = C()
358n/a ref = weakref.ref(obj)
359n/a container = set([obj, 1])
360n/a obj.x = iter(container)
361n/a del obj, container
362n/a gc.collect()
363n/a self.assertTrue(ref() is None, "Cycle was not collected")
364n/a
365n/a def test_free_after_iterating(self):
366n/a support.check_free_after_iterating(self, iter, self.thetype)
367n/a
368n/aclass TestSet(TestJointOps, unittest.TestCase):
369n/a thetype = set
370n/a basetype = set
371n/a
372n/a def test_init(self):
373n/a s = self.thetype()
374n/a s.__init__(self.word)
375n/a self.assertEqual(s, set(self.word))
376n/a s.__init__(self.otherword)
377n/a self.assertEqual(s, set(self.otherword))
378n/a self.assertRaises(TypeError, s.__init__, s, 2);
379n/a self.assertRaises(TypeError, s.__init__, 1);
380n/a
381n/a def test_constructor_identity(self):
382n/a s = self.thetype(range(3))
383n/a t = self.thetype(s)
384n/a self.assertNotEqual(id(s), id(t))
385n/a
386n/a def test_set_literal(self):
387n/a s = set([1,2,3])
388n/a t = {1,2,3}
389n/a self.assertEqual(s, t)
390n/a
391n/a def test_set_literal_insertion_order(self):
392n/a # SF Issue #26020 -- Expect left to right insertion
393n/a s = {1, 1.0, True}
394n/a self.assertEqual(len(s), 1)
395n/a stored_value = s.pop()
396n/a self.assertEqual(type(stored_value), int)
397n/a
398n/a def test_set_literal_evaluation_order(self):
399n/a # Expect left to right expression evaluation
400n/a events = []
401n/a def record(obj):
402n/a events.append(obj)
403n/a s = {record(1), record(2), record(3)}
404n/a self.assertEqual(events, [1, 2, 3])
405n/a
406n/a def test_hash(self):
407n/a self.assertRaises(TypeError, hash, self.s)
408n/a
409n/a def test_clear(self):
410n/a self.s.clear()
411n/a self.assertEqual(self.s, set())
412n/a self.assertEqual(len(self.s), 0)
413n/a
414n/a def test_copy(self):
415n/a dup = self.s.copy()
416n/a self.assertEqual(self.s, dup)
417n/a self.assertNotEqual(id(self.s), id(dup))
418n/a self.assertEqual(type(dup), self.basetype)
419n/a
420n/a def test_add(self):
421n/a self.s.add('Q')
422n/a self.assertIn('Q', self.s)
423n/a dup = self.s.copy()
424n/a self.s.add('Q')
425n/a self.assertEqual(self.s, dup)
426n/a self.assertRaises(TypeError, self.s.add, [])
427n/a
428n/a def test_remove(self):
429n/a self.s.remove('a')
430n/a self.assertNotIn('a', self.s)
431n/a self.assertRaises(KeyError, self.s.remove, 'Q')
432n/a self.assertRaises(TypeError, self.s.remove, [])
433n/a s = self.thetype([frozenset(self.word)])
434n/a self.assertIn(self.thetype(self.word), s)
435n/a s.remove(self.thetype(self.word))
436n/a self.assertNotIn(self.thetype(self.word), s)
437n/a self.assertRaises(KeyError, self.s.remove, self.thetype(self.word))
438n/a
439n/a def test_remove_keyerror_unpacking(self):
440n/a # bug: www.python.org/sf/1576657
441n/a for v1 in ['Q', (1,)]:
442n/a try:
443n/a self.s.remove(v1)
444n/a except KeyError as e:
445n/a v2 = e.args[0]
446n/a self.assertEqual(v1, v2)
447n/a else:
448n/a self.fail()
449n/a
450n/a def test_remove_keyerror_set(self):
451n/a key = self.thetype([3, 4])
452n/a try:
453n/a self.s.remove(key)
454n/a except KeyError as e:
455n/a self.assertTrue(e.args[0] is key,
456n/a "KeyError should be {0}, not {1}".format(key,
457n/a e.args[0]))
458n/a else:
459n/a self.fail()
460n/a
461n/a def test_discard(self):
462n/a self.s.discard('a')
463n/a self.assertNotIn('a', self.s)
464n/a self.s.discard('Q')
465n/a self.assertRaises(TypeError, self.s.discard, [])
466n/a s = self.thetype([frozenset(self.word)])
467n/a self.assertIn(self.thetype(self.word), s)
468n/a s.discard(self.thetype(self.word))
469n/a self.assertNotIn(self.thetype(self.word), s)
470n/a s.discard(self.thetype(self.word))
471n/a
472n/a def test_pop(self):
473n/a for i in range(len(self.s)):
474n/a elem = self.s.pop()
475n/a self.assertNotIn(elem, self.s)
476n/a self.assertRaises(KeyError, self.s.pop)
477n/a
478n/a def test_update(self):
479n/a retval = self.s.update(self.otherword)
480n/a self.assertEqual(retval, None)
481n/a for c in (self.word + self.otherword):
482n/a self.assertIn(c, self.s)
483n/a self.assertRaises(PassThru, self.s.update, check_pass_thru())
484n/a self.assertRaises(TypeError, self.s.update, [[]])
485n/a for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
486n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
487n/a s = self.thetype('abcba')
488n/a self.assertEqual(s.update(C(p)), None)
489n/a self.assertEqual(s, set(q))
490n/a for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
491n/a q = 'ahi'
492n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
493n/a s = self.thetype('abcba')
494n/a self.assertEqual(s.update(C(p), C(q)), None)
495n/a self.assertEqual(s, set(s) | set(p) | set(q))
496n/a
497n/a def test_ior(self):
498n/a self.s |= set(self.otherword)
499n/a for c in (self.word + self.otherword):
500n/a self.assertIn(c, self.s)
501n/a
502n/a def test_intersection_update(self):
503n/a retval = self.s.intersection_update(self.otherword)
504n/a self.assertEqual(retval, None)
505n/a for c in (self.word + self.otherword):
506n/a if c in self.otherword and c in self.word:
507n/a self.assertIn(c, self.s)
508n/a else:
509n/a self.assertNotIn(c, self.s)
510n/a self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru())
511n/a self.assertRaises(TypeError, self.s.intersection_update, [[]])
512n/a for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')):
513n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
514n/a s = self.thetype('abcba')
515n/a self.assertEqual(s.intersection_update(C(p)), None)
516n/a self.assertEqual(s, set(q))
517n/a ss = 'abcba'
518n/a s = self.thetype(ss)
519n/a t = 'cbc'
520n/a self.assertEqual(s.intersection_update(C(p), C(t)), None)
521n/a self.assertEqual(s, set('abcba')&set(p)&set(t))
522n/a
523n/a def test_iand(self):
524n/a self.s &= set(self.otherword)
525n/a for c in (self.word + self.otherword):
526n/a if c in self.otherword and c in self.word:
527n/a self.assertIn(c, self.s)
528n/a else:
529n/a self.assertNotIn(c, self.s)
530n/a
531n/a def test_difference_update(self):
532n/a retval = self.s.difference_update(self.otherword)
533n/a self.assertEqual(retval, None)
534n/a for c in (self.word + self.otherword):
535n/a if c in self.word and c not in self.otherword:
536n/a self.assertIn(c, self.s)
537n/a else:
538n/a self.assertNotIn(c, self.s)
539n/a self.assertRaises(PassThru, self.s.difference_update, check_pass_thru())
540n/a self.assertRaises(TypeError, self.s.difference_update, [[]])
541n/a self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
542n/a for p, q in (('cdc', 'ab'), ('efgfe', 'abc'), ('ccb', 'a'), ('ef', 'abc')):
543n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
544n/a s = self.thetype('abcba')
545n/a self.assertEqual(s.difference_update(C(p)), None)
546n/a self.assertEqual(s, set(q))
547n/a
548n/a s = self.thetype('abcdefghih')
549n/a s.difference_update()
550n/a self.assertEqual(s, self.thetype('abcdefghih'))
551n/a
552n/a s = self.thetype('abcdefghih')
553n/a s.difference_update(C('aba'))
554n/a self.assertEqual(s, self.thetype('cdefghih'))
555n/a
556n/a s = self.thetype('abcdefghih')
557n/a s.difference_update(C('cdc'), C('aba'))
558n/a self.assertEqual(s, self.thetype('efghih'))
559n/a
560n/a def test_isub(self):
561n/a self.s -= set(self.otherword)
562n/a for c in (self.word + self.otherword):
563n/a if c in self.word and c not in self.otherword:
564n/a self.assertIn(c, self.s)
565n/a else:
566n/a self.assertNotIn(c, self.s)
567n/a
568n/a def test_symmetric_difference_update(self):
569n/a retval = self.s.symmetric_difference_update(self.otherword)
570n/a self.assertEqual(retval, None)
571n/a for c in (self.word + self.otherword):
572n/a if (c in self.word) ^ (c in self.otherword):
573n/a self.assertIn(c, self.s)
574n/a else:
575n/a self.assertNotIn(c, self.s)
576n/a self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru())
577n/a self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
578n/a for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')):
579n/a for C in set, frozenset, dict.fromkeys, str, list, tuple:
580n/a s = self.thetype('abcba')
581n/a self.assertEqual(s.symmetric_difference_update(C(p)), None)
582n/a self.assertEqual(s, set(q))
583n/a
584n/a def test_ixor(self):
585n/a self.s ^= set(self.otherword)
586n/a for c in (self.word + self.otherword):
587n/a if (c in self.word) ^ (c in self.otherword):
588n/a self.assertIn(c, self.s)
589n/a else:
590n/a self.assertNotIn(c, self.s)
591n/a
592n/a def test_inplace_on_self(self):
593n/a t = self.s.copy()
594n/a t |= t
595n/a self.assertEqual(t, self.s)
596n/a t &= t
597n/a self.assertEqual(t, self.s)
598n/a t -= t
599n/a self.assertEqual(t, self.thetype())
600n/a t = self.s.copy()
601n/a t ^= t
602n/a self.assertEqual(t, self.thetype())
603n/a
604n/a def test_weakref(self):
605n/a s = self.thetype('gallahad')
606n/a p = weakref.proxy(s)
607n/a self.assertEqual(str(p), str(s))
608n/a s = None
609n/a self.assertRaises(ReferenceError, str, p)
610n/a
611n/a def test_rich_compare(self):
612n/a class TestRichSetCompare:
613n/a def __gt__(self, some_set):
614n/a self.gt_called = True
615n/a return False
616n/a def __lt__(self, some_set):
617n/a self.lt_called = True
618n/a return False
619n/a def __ge__(self, some_set):
620n/a self.ge_called = True
621n/a return False
622n/a def __le__(self, some_set):
623n/a self.le_called = True
624n/a return False
625n/a
626n/a # This first tries the builtin rich set comparison, which doesn't know
627n/a # how to handle the custom object. Upon returning NotImplemented, the
628n/a # corresponding comparison on the right object is invoked.
629n/a myset = {1, 2, 3}
630n/a
631n/a myobj = TestRichSetCompare()
632n/a myset < myobj
633n/a self.assertTrue(myobj.gt_called)
634n/a
635n/a myobj = TestRichSetCompare()
636n/a myset > myobj
637n/a self.assertTrue(myobj.lt_called)
638n/a
639n/a myobj = TestRichSetCompare()
640n/a myset <= myobj
641n/a self.assertTrue(myobj.ge_called)
642n/a
643n/a myobj = TestRichSetCompare()
644n/a myset >= myobj
645n/a self.assertTrue(myobj.le_called)
646n/a
647n/a @unittest.skipUnless(hasattr(set, "test_c_api"),
648n/a 'C API test only available in a debug build')
649n/a def test_c_api(self):
650n/a self.assertEqual(set().test_c_api(), True)
651n/a
652n/aclass SetSubclass(set):
653n/a pass
654n/a
655n/aclass TestSetSubclass(TestSet):
656n/a thetype = SetSubclass
657n/a basetype = set
658n/a
659n/aclass SetSubclassWithKeywordArgs(set):
660n/a def __init__(self, iterable=[], newarg=None):
661n/a set.__init__(self, iterable)
662n/a
663n/aclass TestSetSubclassWithKeywordArgs(TestSet):
664n/a
665n/a def test_keywords_in_subclass(self):
666n/a 'SF bug #1486663 -- this used to erroneously raise a TypeError'
667n/a SetSubclassWithKeywordArgs(newarg=1)
668n/a
669n/aclass TestFrozenSet(TestJointOps, unittest.TestCase):
670n/a thetype = frozenset
671n/a basetype = frozenset
672n/a
673n/a def test_init(self):
674n/a s = self.thetype(self.word)
675n/a s.__init__(self.otherword)
676n/a self.assertEqual(s, set(self.word))
677n/a
678n/a def test_singleton_empty_frozenset(self):
679n/a f = frozenset()
680n/a efs = [frozenset(), frozenset([]), frozenset(()), frozenset(''),
681n/a frozenset(), frozenset([]), frozenset(()), frozenset(''),
682n/a frozenset(range(0)), frozenset(frozenset()),
683n/a frozenset(f), f]
684n/a # All of the empty frozensets should have just one id()
685n/a self.assertEqual(len(set(map(id, efs))), 1)
686n/a
687n/a def test_constructor_identity(self):
688n/a s = self.thetype(range(3))
689n/a t = self.thetype(s)
690n/a self.assertEqual(id(s), id(t))
691n/a
692n/a def test_hash(self):
693n/a self.assertEqual(hash(self.thetype('abcdeb')),
694n/a hash(self.thetype('ebecda')))
695n/a
696n/a # make sure that all permutations give the same hash value
697n/a n = 100
698n/a seq = [randrange(n) for i in range(n)]
699n/a results = set()
700n/a for i in range(200):
701n/a shuffle(seq)
702n/a results.add(hash(self.thetype(seq)))
703n/a self.assertEqual(len(results), 1)
704n/a
705n/a def test_copy(self):
706n/a dup = self.s.copy()
707n/a self.assertEqual(id(self.s), id(dup))
708n/a
709n/a def test_frozen_as_dictkey(self):
710n/a seq = list(range(10)) + list('abcdefg') + ['apple']
711n/a key1 = self.thetype(seq)
712n/a key2 = self.thetype(reversed(seq))
713n/a self.assertEqual(key1, key2)
714n/a self.assertNotEqual(id(key1), id(key2))
715n/a d = {}
716n/a d[key1] = 42
717n/a self.assertEqual(d[key2], 42)
718n/a
719n/a def test_hash_caching(self):
720n/a f = self.thetype('abcdcda')
721n/a self.assertEqual(hash(f), hash(f))
722n/a
723n/a def test_hash_effectiveness(self):
724n/a n = 13
725n/a hashvalues = set()
726n/a addhashvalue = hashvalues.add
727n/a elemmasks = [(i+1, 1<<i) for i in range(n)]
728n/a for i in range(2**n):
729n/a addhashvalue(hash(frozenset([e for e, m in elemmasks if m&i])))
730n/a self.assertEqual(len(hashvalues), 2**n)
731n/a
732n/a def zf_range(n):
733n/a # https://en.wikipedia.org/wiki/Set-theoretic_definition_of_natural_numbers
734n/a nums = [frozenset()]
735n/a for i in range(n-1):
736n/a num = frozenset(nums)
737n/a nums.append(num)
738n/a return nums[:n]
739n/a
740n/a def powerset(s):
741n/a for i in range(len(s)+1):
742n/a yield from map(frozenset, itertools.combinations(s, i))
743n/a
744n/a for n in range(18):
745n/a t = 2 ** n
746n/a mask = t - 1
747n/a for nums in (range, zf_range):
748n/a u = len({h & mask for h in map(hash, powerset(nums(n)))})
749n/a self.assertGreater(4*u, t)
750n/a
751n/aclass FrozenSetSubclass(frozenset):
752n/a pass
753n/a
754n/aclass TestFrozenSetSubclass(TestFrozenSet):
755n/a thetype = FrozenSetSubclass
756n/a basetype = frozenset
757n/a
758n/a def test_constructor_identity(self):
759n/a s = self.thetype(range(3))
760n/a t = self.thetype(s)
761n/a self.assertNotEqual(id(s), id(t))
762n/a
763n/a def test_copy(self):
764n/a dup = self.s.copy()
765n/a self.assertNotEqual(id(self.s), id(dup))
766n/a
767n/a def test_nested_empty_constructor(self):
768n/a s = self.thetype()
769n/a t = self.thetype(s)
770n/a self.assertEqual(s, t)
771n/a
772n/a def test_singleton_empty_frozenset(self):
773n/a Frozenset = self.thetype
774n/a f = frozenset()
775n/a F = Frozenset()
776n/a efs = [Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
777n/a Frozenset(), Frozenset([]), Frozenset(()), Frozenset(''),
778n/a Frozenset(range(0)), Frozenset(Frozenset()),
779n/a Frozenset(frozenset()), f, F, Frozenset(f), Frozenset(F)]
780n/a # All empty frozenset subclass instances should have different ids
781n/a self.assertEqual(len(set(map(id, efs))), len(efs))
782n/a
783n/a# Tests taken from test_sets.py =============================================
784n/a
785n/aempty_set = set()
786n/a
787n/a#==============================================================================
788n/a
789n/aclass TestBasicOps:
790n/a
791n/a def test_repr(self):
792n/a if self.repr is not None:
793n/a self.assertEqual(repr(self.set), self.repr)
794n/a
795n/a def check_repr_against_values(self):
796n/a text = repr(self.set)
797n/a self.assertTrue(text.startswith('{'))
798n/a self.assertTrue(text.endswith('}'))
799n/a
800n/a result = text[1:-1].split(', ')
801n/a result.sort()
802n/a sorted_repr_values = [repr(value) for value in self.values]
803n/a sorted_repr_values.sort()
804n/a self.assertEqual(result, sorted_repr_values)
805n/a
806n/a def test_print(self):
807n/a try:
808n/a fo = open(support.TESTFN, "w")
809n/a fo.write(str(self.set))
810n/a fo.close()
811n/a fo = open(support.TESTFN, "r")
812n/a self.assertEqual(fo.read(), repr(self.set))
813n/a finally:
814n/a fo.close()
815n/a support.unlink(support.TESTFN)
816n/a
817n/a def test_length(self):
818n/a self.assertEqual(len(self.set), self.length)
819n/a
820n/a def test_self_equality(self):
821n/a self.assertEqual(self.set, self.set)
822n/a
823n/a def test_equivalent_equality(self):
824n/a self.assertEqual(self.set, self.dup)
825n/a
826n/a def test_copy(self):
827n/a self.assertEqual(self.set.copy(), self.dup)
828n/a
829n/a def test_self_union(self):
830n/a result = self.set | self.set
831n/a self.assertEqual(result, self.dup)
832n/a
833n/a def test_empty_union(self):
834n/a result = self.set | empty_set
835n/a self.assertEqual(result, self.dup)
836n/a
837n/a def test_union_empty(self):
838n/a result = empty_set | self.set
839n/a self.assertEqual(result, self.dup)
840n/a
841n/a def test_self_intersection(self):
842n/a result = self.set & self.set
843n/a self.assertEqual(result, self.dup)
844n/a
845n/a def test_empty_intersection(self):
846n/a result = self.set & empty_set
847n/a self.assertEqual(result, empty_set)
848n/a
849n/a def test_intersection_empty(self):
850n/a result = empty_set & self.set
851n/a self.assertEqual(result, empty_set)
852n/a
853n/a def test_self_isdisjoint(self):
854n/a result = self.set.isdisjoint(self.set)
855n/a self.assertEqual(result, not self.set)
856n/a
857n/a def test_empty_isdisjoint(self):
858n/a result = self.set.isdisjoint(empty_set)
859n/a self.assertEqual(result, True)
860n/a
861n/a def test_isdisjoint_empty(self):
862n/a result = empty_set.isdisjoint(self.set)
863n/a self.assertEqual(result, True)
864n/a
865n/a def test_self_symmetric_difference(self):
866n/a result = self.set ^ self.set
867n/a self.assertEqual(result, empty_set)
868n/a
869n/a def test_empty_symmetric_difference(self):
870n/a result = self.set ^ empty_set
871n/a self.assertEqual(result, self.set)
872n/a
873n/a def test_self_difference(self):
874n/a result = self.set - self.set
875n/a self.assertEqual(result, empty_set)
876n/a
877n/a def test_empty_difference(self):
878n/a result = self.set - empty_set
879n/a self.assertEqual(result, self.dup)
880n/a
881n/a def test_empty_difference_rev(self):
882n/a result = empty_set - self.set
883n/a self.assertEqual(result, empty_set)
884n/a
885n/a def test_iteration(self):
886n/a for v in self.set:
887n/a self.assertIn(v, self.values)
888n/a setiter = iter(self.set)
889n/a self.assertEqual(setiter.__length_hint__(), len(self.set))
890n/a
891n/a def test_pickling(self):
892n/a for proto in range(pickle.HIGHEST_PROTOCOL + 1):
893n/a p = pickle.dumps(self.set, proto)
894n/a copy = pickle.loads(p)
895n/a self.assertEqual(self.set, copy,
896n/a "%s != %s" % (self.set, copy))
897n/a
898n/a#------------------------------------------------------------------------------
899n/a
900n/aclass TestBasicOpsEmpty(TestBasicOps, unittest.TestCase):
901n/a def setUp(self):
902n/a self.case = "empty set"
903n/a self.values = []
904n/a self.set = set(self.values)
905n/a self.dup = set(self.values)
906n/a self.length = 0
907n/a self.repr = "set()"
908n/a
909n/a#------------------------------------------------------------------------------
910n/a
911n/aclass TestBasicOpsSingleton(TestBasicOps, unittest.TestCase):
912n/a def setUp(self):
913n/a self.case = "unit set (number)"
914n/a self.values = [3]
915n/a self.set = set(self.values)
916n/a self.dup = set(self.values)
917n/a self.length = 1
918n/a self.repr = "{3}"
919n/a
920n/a def test_in(self):
921n/a self.assertIn(3, self.set)
922n/a
923n/a def test_not_in(self):
924n/a self.assertNotIn(2, self.set)
925n/a
926n/a#------------------------------------------------------------------------------
927n/a
928n/aclass TestBasicOpsTuple(TestBasicOps, unittest.TestCase):
929n/a def setUp(self):
930n/a self.case = "unit set (tuple)"
931n/a self.values = [(0, "zero")]
932n/a self.set = set(self.values)
933n/a self.dup = set(self.values)
934n/a self.length = 1
935n/a self.repr = "{(0, 'zero')}"
936n/a
937n/a def test_in(self):
938n/a self.assertIn((0, "zero"), self.set)
939n/a
940n/a def test_not_in(self):
941n/a self.assertNotIn(9, self.set)
942n/a
943n/a#------------------------------------------------------------------------------
944n/a
945n/aclass TestBasicOpsTriple(TestBasicOps, unittest.TestCase):
946n/a def setUp(self):
947n/a self.case = "triple set"
948n/a self.values = [0, "zero", operator.add]
949n/a self.set = set(self.values)
950n/a self.dup = set(self.values)
951n/a self.length = 3
952n/a self.repr = None
953n/a
954n/a#------------------------------------------------------------------------------
955n/a
956n/aclass TestBasicOpsString(TestBasicOps, unittest.TestCase):
957n/a def setUp(self):
958n/a self.case = "string set"
959n/a self.values = ["a", "b", "c"]
960n/a self.set = set(self.values)
961n/a self.dup = set(self.values)
962n/a self.length = 3
963n/a
964n/a def test_repr(self):
965n/a self.check_repr_against_values()
966n/a
967n/a#------------------------------------------------------------------------------
968n/a
969n/aclass TestBasicOpsBytes(TestBasicOps, unittest.TestCase):
970n/a def setUp(self):
971n/a self.case = "bytes set"
972n/a self.values = [b"a", b"b", b"c"]
973n/a self.set = set(self.values)
974n/a self.dup = set(self.values)
975n/a self.length = 3
976n/a
977n/a def test_repr(self):
978n/a self.check_repr_against_values()
979n/a
980n/a#------------------------------------------------------------------------------
981n/a
982n/aclass TestBasicOpsMixedStringBytes(TestBasicOps, unittest.TestCase):
983n/a def setUp(self):
984n/a self._warning_filters = support.check_warnings()
985n/a self._warning_filters.__enter__()
986n/a warnings.simplefilter('ignore', BytesWarning)
987n/a self.case = "string and bytes set"
988n/a self.values = ["a", "b", b"a", b"b"]
989n/a self.set = set(self.values)
990n/a self.dup = set(self.values)
991n/a self.length = 4
992n/a
993n/a def tearDown(self):
994n/a self._warning_filters.__exit__(None, None, None)
995n/a
996n/a def test_repr(self):
997n/a self.check_repr_against_values()
998n/a
999n/a#==============================================================================
1000n/a
1001n/adef baditer():
1002n/a raise TypeError
1003n/a yield True
1004n/a
1005n/adef gooditer():
1006n/a yield True
1007n/a
1008n/aclass TestExceptionPropagation(unittest.TestCase):
1009n/a """SF 628246: Set constructor should not trap iterator TypeErrors"""
1010n/a
1011n/a def test_instanceWithException(self):
1012n/a self.assertRaises(TypeError, set, baditer())
1013n/a
1014n/a def test_instancesWithoutException(self):
1015n/a # All of these iterables should load without exception.
1016n/a set([1,2,3])
1017n/a set((1,2,3))
1018n/a set({'one':1, 'two':2, 'three':3})
1019n/a set(range(3))
1020n/a set('abc')
1021n/a set(gooditer())
1022n/a
1023n/a def test_changingSizeWhileIterating(self):
1024n/a s = set([1,2,3])
1025n/a try:
1026n/a for i in s:
1027n/a s.update([4])
1028n/a except RuntimeError:
1029n/a pass
1030n/a else:
1031n/a self.fail("no exception when changing size during iteration")
1032n/a
1033n/a#==============================================================================
1034n/a
1035n/aclass TestSetOfSets(unittest.TestCase):
1036n/a def test_constructor(self):
1037n/a inner = frozenset([1])
1038n/a outer = set([inner])
1039n/a element = outer.pop()
1040n/a self.assertEqual(type(element), frozenset)
1041n/a outer.add(inner) # Rebuild set of sets with .add method
1042n/a outer.remove(inner)
1043n/a self.assertEqual(outer, set()) # Verify that remove worked
1044n/a outer.discard(inner) # Absence of KeyError indicates working fine
1045n/a
1046n/a#==============================================================================
1047n/a
1048n/aclass TestBinaryOps(unittest.TestCase):
1049n/a def setUp(self):
1050n/a self.set = set((2, 4, 6))
1051n/a
1052n/a def test_eq(self): # SF bug 643115
1053n/a self.assertEqual(self.set, set({2:1,4:3,6:5}))
1054n/a
1055n/a def test_union_subset(self):
1056n/a result = self.set | set([2])
1057n/a self.assertEqual(result, set((2, 4, 6)))
1058n/a
1059n/a def test_union_superset(self):
1060n/a result = self.set | set([2, 4, 6, 8])
1061n/a self.assertEqual(result, set([2, 4, 6, 8]))
1062n/a
1063n/a def test_union_overlap(self):
1064n/a result = self.set | set([3, 4, 5])
1065n/a self.assertEqual(result, set([2, 3, 4, 5, 6]))
1066n/a
1067n/a def test_union_non_overlap(self):
1068n/a result = self.set | set([8])
1069n/a self.assertEqual(result, set([2, 4, 6, 8]))
1070n/a
1071n/a def test_intersection_subset(self):
1072n/a result = self.set & set((2, 4))
1073n/a self.assertEqual(result, set((2, 4)))
1074n/a
1075n/a def test_intersection_superset(self):
1076n/a result = self.set & set([2, 4, 6, 8])
1077n/a self.assertEqual(result, set([2, 4, 6]))
1078n/a
1079n/a def test_intersection_overlap(self):
1080n/a result = self.set & set([3, 4, 5])
1081n/a self.assertEqual(result, set([4]))
1082n/a
1083n/a def test_intersection_non_overlap(self):
1084n/a result = self.set & set([8])
1085n/a self.assertEqual(result, empty_set)
1086n/a
1087n/a def test_isdisjoint_subset(self):
1088n/a result = self.set.isdisjoint(set((2, 4)))
1089n/a self.assertEqual(result, False)
1090n/a
1091n/a def test_isdisjoint_superset(self):
1092n/a result = self.set.isdisjoint(set([2, 4, 6, 8]))
1093n/a self.assertEqual(result, False)
1094n/a
1095n/a def test_isdisjoint_overlap(self):
1096n/a result = self.set.isdisjoint(set([3, 4, 5]))
1097n/a self.assertEqual(result, False)
1098n/a
1099n/a def test_isdisjoint_non_overlap(self):
1100n/a result = self.set.isdisjoint(set([8]))
1101n/a self.assertEqual(result, True)
1102n/a
1103n/a def test_sym_difference_subset(self):
1104n/a result = self.set ^ set((2, 4))
1105n/a self.assertEqual(result, set([6]))
1106n/a
1107n/a def test_sym_difference_superset(self):
1108n/a result = self.set ^ set((2, 4, 6, 8))
1109n/a self.assertEqual(result, set([8]))
1110n/a
1111n/a def test_sym_difference_overlap(self):
1112n/a result = self.set ^ set((3, 4, 5))
1113n/a self.assertEqual(result, set([2, 3, 5, 6]))
1114n/a
1115n/a def test_sym_difference_non_overlap(self):
1116n/a result = self.set ^ set([8])
1117n/a self.assertEqual(result, set([2, 4, 6, 8]))
1118n/a
1119n/a#==============================================================================
1120n/a
1121n/aclass TestUpdateOps(unittest.TestCase):
1122n/a def setUp(self):
1123n/a self.set = set((2, 4, 6))
1124n/a
1125n/a def test_union_subset(self):
1126n/a self.set |= set([2])
1127n/a self.assertEqual(self.set, set((2, 4, 6)))
1128n/a
1129n/a def test_union_superset(self):
1130n/a self.set |= set([2, 4, 6, 8])
1131n/a self.assertEqual(self.set, set([2, 4, 6, 8]))
1132n/a
1133n/a def test_union_overlap(self):
1134n/a self.set |= set([3, 4, 5])
1135n/a self.assertEqual(self.set, set([2, 3, 4, 5, 6]))
1136n/a
1137n/a def test_union_non_overlap(self):
1138n/a self.set |= set([8])
1139n/a self.assertEqual(self.set, set([2, 4, 6, 8]))
1140n/a
1141n/a def test_union_method_call(self):
1142n/a self.set.update(set([3, 4, 5]))
1143n/a self.assertEqual(self.set, set([2, 3, 4, 5, 6]))
1144n/a
1145n/a def test_intersection_subset(self):
1146n/a self.set &= set((2, 4))
1147n/a self.assertEqual(self.set, set((2, 4)))
1148n/a
1149n/a def test_intersection_superset(self):
1150n/a self.set &= set([2, 4, 6, 8])
1151n/a self.assertEqual(self.set, set([2, 4, 6]))
1152n/a
1153n/a def test_intersection_overlap(self):
1154n/a self.set &= set([3, 4, 5])
1155n/a self.assertEqual(self.set, set([4]))
1156n/a
1157n/a def test_intersection_non_overlap(self):
1158n/a self.set &= set([8])
1159n/a self.assertEqual(self.set, empty_set)
1160n/a
1161n/a def test_intersection_method_call(self):
1162n/a self.set.intersection_update(set([3, 4, 5]))
1163n/a self.assertEqual(self.set, set([4]))
1164n/a
1165n/a def test_sym_difference_subset(self):
1166n/a self.set ^= set((2, 4))
1167n/a self.assertEqual(self.set, set([6]))
1168n/a
1169n/a def test_sym_difference_superset(self):
1170n/a self.set ^= set((2, 4, 6, 8))
1171n/a self.assertEqual(self.set, set([8]))
1172n/a
1173n/a def test_sym_difference_overlap(self):
1174n/a self.set ^= set((3, 4, 5))
1175n/a self.assertEqual(self.set, set([2, 3, 5, 6]))
1176n/a
1177n/a def test_sym_difference_non_overlap(self):
1178n/a self.set ^= set([8])
1179n/a self.assertEqual(self.set, set([2, 4, 6, 8]))
1180n/a
1181n/a def test_sym_difference_method_call(self):
1182n/a self.set.symmetric_difference_update(set([3, 4, 5]))
1183n/a self.assertEqual(self.set, set([2, 3, 5, 6]))
1184n/a
1185n/a def test_difference_subset(self):
1186n/a self.set -= set((2, 4))
1187n/a self.assertEqual(self.set, set([6]))
1188n/a
1189n/a def test_difference_superset(self):
1190n/a self.set -= set((2, 4, 6, 8))
1191n/a self.assertEqual(self.set, set([]))
1192n/a
1193n/a def test_difference_overlap(self):
1194n/a self.set -= set((3, 4, 5))
1195n/a self.assertEqual(self.set, set([2, 6]))
1196n/a
1197n/a def test_difference_non_overlap(self):
1198n/a self.set -= set([8])
1199n/a self.assertEqual(self.set, set([2, 4, 6]))
1200n/a
1201n/a def test_difference_method_call(self):
1202n/a self.set.difference_update(set([3, 4, 5]))
1203n/a self.assertEqual(self.set, set([2, 6]))
1204n/a
1205n/a#==============================================================================
1206n/a
1207n/aclass TestMutate(unittest.TestCase):
1208n/a def setUp(self):
1209n/a self.values = ["a", "b", "c"]
1210n/a self.set = set(self.values)
1211n/a
1212n/a def test_add_present(self):
1213n/a self.set.add("c")
1214n/a self.assertEqual(self.set, set("abc"))
1215n/a
1216n/a def test_add_absent(self):
1217n/a self.set.add("d")
1218n/a self.assertEqual(self.set, set("abcd"))
1219n/a
1220n/a def test_add_until_full(self):
1221n/a tmp = set()
1222n/a expected_len = 0
1223n/a for v in self.values:
1224n/a tmp.add(v)
1225n/a expected_len += 1
1226n/a self.assertEqual(len(tmp), expected_len)
1227n/a self.assertEqual(tmp, self.set)
1228n/a
1229n/a def test_remove_present(self):
1230n/a self.set.remove("b")
1231n/a self.assertEqual(self.set, set("ac"))
1232n/a
1233n/a def test_remove_absent(self):
1234n/a try:
1235n/a self.set.remove("d")
1236n/a self.fail("Removing missing element should have raised LookupError")
1237n/a except LookupError:
1238n/a pass
1239n/a
1240n/a def test_remove_until_empty(self):
1241n/a expected_len = len(self.set)
1242n/a for v in self.values:
1243n/a self.set.remove(v)
1244n/a expected_len -= 1
1245n/a self.assertEqual(len(self.set), expected_len)
1246n/a
1247n/a def test_discard_present(self):
1248n/a self.set.discard("c")
1249n/a self.assertEqual(self.set, set("ab"))
1250n/a
1251n/a def test_discard_absent(self):
1252n/a self.set.discard("d")
1253n/a self.assertEqual(self.set, set("abc"))
1254n/a
1255n/a def test_clear(self):
1256n/a self.set.clear()
1257n/a self.assertEqual(len(self.set), 0)
1258n/a
1259n/a def test_pop(self):
1260n/a popped = {}
1261n/a while self.set:
1262n/a popped[self.set.pop()] = None
1263n/a self.assertEqual(len(popped), len(self.values))
1264n/a for v in self.values:
1265n/a self.assertIn(v, popped)
1266n/a
1267n/a def test_update_empty_tuple(self):
1268n/a self.set.update(())
1269n/a self.assertEqual(self.set, set(self.values))
1270n/a
1271n/a def test_update_unit_tuple_overlap(self):
1272n/a self.set.update(("a",))
1273n/a self.assertEqual(self.set, set(self.values))
1274n/a
1275n/a def test_update_unit_tuple_non_overlap(self):
1276n/a self.set.update(("a", "z"))
1277n/a self.assertEqual(self.set, set(self.values + ["z"]))
1278n/a
1279n/a#==============================================================================
1280n/a
1281n/aclass TestSubsets:
1282n/a
1283n/a case2method = {"<=": "issubset",
1284n/a ">=": "issuperset",
1285n/a }
1286n/a
1287n/a reverse = {"==": "==",
1288n/a "!=": "!=",
1289n/a "<": ">",
1290n/a ">": "<",
1291n/a "<=": ">=",
1292n/a ">=": "<=",
1293n/a }
1294n/a
1295n/a def test_issubset(self):
1296n/a x = self.left
1297n/a y = self.right
1298n/a for case in "!=", "==", "<", "<=", ">", ">=":
1299n/a expected = case in self.cases
1300n/a # Test the binary infix spelling.
1301n/a result = eval("x" + case + "y", locals())
1302n/a self.assertEqual(result, expected)
1303n/a # Test the "friendly" method-name spelling, if one exists.
1304n/a if case in TestSubsets.case2method:
1305n/a method = getattr(x, TestSubsets.case2method[case])
1306n/a result = method(y)
1307n/a self.assertEqual(result, expected)
1308n/a
1309n/a # Now do the same for the operands reversed.
1310n/a rcase = TestSubsets.reverse[case]
1311n/a result = eval("y" + rcase + "x", locals())
1312n/a self.assertEqual(result, expected)
1313n/a if rcase in TestSubsets.case2method:
1314n/a method = getattr(y, TestSubsets.case2method[rcase])
1315n/a result = method(x)
1316n/a self.assertEqual(result, expected)
1317n/a#------------------------------------------------------------------------------
1318n/a
1319n/aclass TestSubsetEqualEmpty(TestSubsets, unittest.TestCase):
1320n/a left = set()
1321n/a right = set()
1322n/a name = "both empty"
1323n/a cases = "==", "<=", ">="
1324n/a
1325n/a#------------------------------------------------------------------------------
1326n/a
1327n/aclass TestSubsetEqualNonEmpty(TestSubsets, unittest.TestCase):
1328n/a left = set([1, 2])
1329n/a right = set([1, 2])
1330n/a name = "equal pair"
1331n/a cases = "==", "<=", ">="
1332n/a
1333n/a#------------------------------------------------------------------------------
1334n/a
1335n/aclass TestSubsetEmptyNonEmpty(TestSubsets, unittest.TestCase):
1336n/a left = set()
1337n/a right = set([1, 2])
1338n/a name = "one empty, one non-empty"
1339n/a cases = "!=", "<", "<="
1340n/a
1341n/a#------------------------------------------------------------------------------
1342n/a
1343n/aclass TestSubsetPartial(TestSubsets, unittest.TestCase):
1344n/a left = set([1])
1345n/a right = set([1, 2])
1346n/a name = "one a non-empty proper subset of other"
1347n/a cases = "!=", "<", "<="
1348n/a
1349n/a#------------------------------------------------------------------------------
1350n/a
1351n/aclass TestSubsetNonOverlap(TestSubsets, unittest.TestCase):
1352n/a left = set([1])
1353n/a right = set([2])
1354n/a name = "neither empty, neither contains"
1355n/a cases = "!="
1356n/a
1357n/a#==============================================================================
1358n/a
1359n/aclass TestOnlySetsInBinaryOps:
1360n/a
1361n/a def test_eq_ne(self):
1362n/a # Unlike the others, this is testing that == and != *are* allowed.
1363n/a self.assertEqual(self.other == self.set, False)
1364n/a self.assertEqual(self.set == self.other, False)
1365n/a self.assertEqual(self.other != self.set, True)
1366n/a self.assertEqual(self.set != self.other, True)
1367n/a
1368n/a def test_ge_gt_le_lt(self):
1369n/a self.assertRaises(TypeError, lambda: self.set < self.other)
1370n/a self.assertRaises(TypeError, lambda: self.set <= self.other)
1371n/a self.assertRaises(TypeError, lambda: self.set > self.other)
1372n/a self.assertRaises(TypeError, lambda: self.set >= self.other)
1373n/a
1374n/a self.assertRaises(TypeError, lambda: self.other < self.set)
1375n/a self.assertRaises(TypeError, lambda: self.other <= self.set)
1376n/a self.assertRaises(TypeError, lambda: self.other > self.set)
1377n/a self.assertRaises(TypeError, lambda: self.other >= self.set)
1378n/a
1379n/a def test_update_operator(self):
1380n/a try:
1381n/a self.set |= self.other
1382n/a except TypeError:
1383n/a pass
1384n/a else:
1385n/a self.fail("expected TypeError")
1386n/a
1387n/a def test_update(self):
1388n/a if self.otherIsIterable:
1389n/a self.set.update(self.other)
1390n/a else:
1391n/a self.assertRaises(TypeError, self.set.update, self.other)
1392n/a
1393n/a def test_union(self):
1394n/a self.assertRaises(TypeError, lambda: self.set | self.other)
1395n/a self.assertRaises(TypeError, lambda: self.other | self.set)
1396n/a if self.otherIsIterable:
1397n/a self.set.union(self.other)
1398n/a else:
1399n/a self.assertRaises(TypeError, self.set.union, self.other)
1400n/a
1401n/a def test_intersection_update_operator(self):
1402n/a try:
1403n/a self.set &= self.other
1404n/a except TypeError:
1405n/a pass
1406n/a else:
1407n/a self.fail("expected TypeError")
1408n/a
1409n/a def test_intersection_update(self):
1410n/a if self.otherIsIterable:
1411n/a self.set.intersection_update(self.other)
1412n/a else:
1413n/a self.assertRaises(TypeError,
1414n/a self.set.intersection_update,
1415n/a self.other)
1416n/a
1417n/a def test_intersection(self):
1418n/a self.assertRaises(TypeError, lambda: self.set & self.other)
1419n/a self.assertRaises(TypeError, lambda: self.other & self.set)
1420n/a if self.otherIsIterable:
1421n/a self.set.intersection(self.other)
1422n/a else:
1423n/a self.assertRaises(TypeError, self.set.intersection, self.other)
1424n/a
1425n/a def test_sym_difference_update_operator(self):
1426n/a try:
1427n/a self.set ^= self.other
1428n/a except TypeError:
1429n/a pass
1430n/a else:
1431n/a self.fail("expected TypeError")
1432n/a
1433n/a def test_sym_difference_update(self):
1434n/a if self.otherIsIterable:
1435n/a self.set.symmetric_difference_update(self.other)
1436n/a else:
1437n/a self.assertRaises(TypeError,
1438n/a self.set.symmetric_difference_update,
1439n/a self.other)
1440n/a
1441n/a def test_sym_difference(self):
1442n/a self.assertRaises(TypeError, lambda: self.set ^ self.other)
1443n/a self.assertRaises(TypeError, lambda: self.other ^ self.set)
1444n/a if self.otherIsIterable:
1445n/a self.set.symmetric_difference(self.other)
1446n/a else:
1447n/a self.assertRaises(TypeError, self.set.symmetric_difference, self.other)
1448n/a
1449n/a def test_difference_update_operator(self):
1450n/a try:
1451n/a self.set -= self.other
1452n/a except TypeError:
1453n/a pass
1454n/a else:
1455n/a self.fail("expected TypeError")
1456n/a
1457n/a def test_difference_update(self):
1458n/a if self.otherIsIterable:
1459n/a self.set.difference_update(self.other)
1460n/a else:
1461n/a self.assertRaises(TypeError,
1462n/a self.set.difference_update,
1463n/a self.other)
1464n/a
1465n/a def test_difference(self):
1466n/a self.assertRaises(TypeError, lambda: self.set - self.other)
1467n/a self.assertRaises(TypeError, lambda: self.other - self.set)
1468n/a if self.otherIsIterable:
1469n/a self.set.difference(self.other)
1470n/a else:
1471n/a self.assertRaises(TypeError, self.set.difference, self.other)
1472n/a
1473n/a#------------------------------------------------------------------------------
1474n/a
1475n/aclass TestOnlySetsNumeric(TestOnlySetsInBinaryOps, unittest.TestCase):
1476n/a def setUp(self):
1477n/a self.set = set((1, 2, 3))
1478n/a self.other = 19
1479n/a self.otherIsIterable = False
1480n/a
1481n/a#------------------------------------------------------------------------------
1482n/a
1483n/aclass TestOnlySetsDict(TestOnlySetsInBinaryOps, unittest.TestCase):
1484n/a def setUp(self):
1485n/a self.set = set((1, 2, 3))
1486n/a self.other = {1:2, 3:4}
1487n/a self.otherIsIterable = True
1488n/a
1489n/a#------------------------------------------------------------------------------
1490n/a
1491n/aclass TestOnlySetsOperator(TestOnlySetsInBinaryOps, unittest.TestCase):
1492n/a def setUp(self):
1493n/a self.set = set((1, 2, 3))
1494n/a self.other = operator.add
1495n/a self.otherIsIterable = False
1496n/a
1497n/a#------------------------------------------------------------------------------
1498n/a
1499n/aclass TestOnlySetsTuple(TestOnlySetsInBinaryOps, unittest.TestCase):
1500n/a def setUp(self):
1501n/a self.set = set((1, 2, 3))
1502n/a self.other = (2, 4, 6)
1503n/a self.otherIsIterable = True
1504n/a
1505n/a#------------------------------------------------------------------------------
1506n/a
1507n/aclass TestOnlySetsString(TestOnlySetsInBinaryOps, unittest.TestCase):
1508n/a def setUp(self):
1509n/a self.set = set((1, 2, 3))
1510n/a self.other = 'abc'
1511n/a self.otherIsIterable = True
1512n/a
1513n/a#------------------------------------------------------------------------------
1514n/a
1515n/aclass TestOnlySetsGenerator(TestOnlySetsInBinaryOps, unittest.TestCase):
1516n/a def setUp(self):
1517n/a def gen():
1518n/a for i in range(0, 10, 2):
1519n/a yield i
1520n/a self.set = set((1, 2, 3))
1521n/a self.other = gen()
1522n/a self.otherIsIterable = True
1523n/a
1524n/a#==============================================================================
1525n/a
1526n/aclass TestCopying:
1527n/a
1528n/a def test_copy(self):
1529n/a dup = self.set.copy()
1530n/a dup_list = sorted(dup, key=repr)
1531n/a set_list = sorted(self.set, key=repr)
1532n/a self.assertEqual(len(dup_list), len(set_list))
1533n/a for i in range(len(dup_list)):
1534n/a self.assertTrue(dup_list[i] is set_list[i])
1535n/a
1536n/a def test_deep_copy(self):
1537n/a dup = copy.deepcopy(self.set)
1538n/a ##print type(dup), repr(dup)
1539n/a dup_list = sorted(dup, key=repr)
1540n/a set_list = sorted(self.set, key=repr)
1541n/a self.assertEqual(len(dup_list), len(set_list))
1542n/a for i in range(len(dup_list)):
1543n/a self.assertEqual(dup_list[i], set_list[i])
1544n/a
1545n/a#------------------------------------------------------------------------------
1546n/a
1547n/aclass TestCopyingEmpty(TestCopying, unittest.TestCase):
1548n/a def setUp(self):
1549n/a self.set = set()
1550n/a
1551n/a#------------------------------------------------------------------------------
1552n/a
1553n/aclass TestCopyingSingleton(TestCopying, unittest.TestCase):
1554n/a def setUp(self):
1555n/a self.set = set(["hello"])
1556n/a
1557n/a#------------------------------------------------------------------------------
1558n/a
1559n/aclass TestCopyingTriple(TestCopying, unittest.TestCase):
1560n/a def setUp(self):
1561n/a self.set = set(["zero", 0, None])
1562n/a
1563n/a#------------------------------------------------------------------------------
1564n/a
1565n/aclass TestCopyingTuple(TestCopying, unittest.TestCase):
1566n/a def setUp(self):
1567n/a self.set = set([(1, 2)])
1568n/a
1569n/a#------------------------------------------------------------------------------
1570n/a
1571n/aclass TestCopyingNested(TestCopying, unittest.TestCase):
1572n/a def setUp(self):
1573n/a self.set = set([((1, 2), (3, 4))])
1574n/a
1575n/a#==============================================================================
1576n/a
1577n/aclass TestIdentities(unittest.TestCase):
1578n/a def setUp(self):
1579n/a self.a = set('abracadabra')
1580n/a self.b = set('alacazam')
1581n/a
1582n/a def test_binopsVsSubsets(self):
1583n/a a, b = self.a, self.b
1584n/a self.assertTrue(a - b < a)
1585n/a self.assertTrue(b - a < b)
1586n/a self.assertTrue(a & b < a)
1587n/a self.assertTrue(a & b < b)
1588n/a self.assertTrue(a | b > a)
1589n/a self.assertTrue(a | b > b)
1590n/a self.assertTrue(a ^ b < a | b)
1591n/a
1592n/a def test_commutativity(self):
1593n/a a, b = self.a, self.b
1594n/a self.assertEqual(a&b, b&a)
1595n/a self.assertEqual(a|b, b|a)
1596n/a self.assertEqual(a^b, b^a)
1597n/a if a != b:
1598n/a self.assertNotEqual(a-b, b-a)
1599n/a
1600n/a def test_summations(self):
1601n/a # check that sums of parts equal the whole
1602n/a a, b = self.a, self.b
1603n/a self.assertEqual((a-b)|(a&b)|(b-a), a|b)
1604n/a self.assertEqual((a&b)|(a^b), a|b)
1605n/a self.assertEqual(a|(b-a), a|b)
1606n/a self.assertEqual((a-b)|b, a|b)
1607n/a self.assertEqual((a-b)|(a&b), a)
1608n/a self.assertEqual((b-a)|(a&b), b)
1609n/a self.assertEqual((a-b)|(b-a), a^b)
1610n/a
1611n/a def test_exclusion(self):
1612n/a # check that inverse operations show non-overlap
1613n/a a, b, zero = self.a, self.b, set()
1614n/a self.assertEqual((a-b)&b, zero)
1615n/a self.assertEqual((b-a)&a, zero)
1616n/a self.assertEqual((a&b)&(a^b), zero)
1617n/a
1618n/a# Tests derived from test_itertools.py =======================================
1619n/a
1620n/adef R(seqn):
1621n/a 'Regular generator'
1622n/a for i in seqn:
1623n/a yield i
1624n/a
1625n/aclass G:
1626n/a 'Sequence using __getitem__'
1627n/a def __init__(self, seqn):
1628n/a self.seqn = seqn
1629n/a def __getitem__(self, i):
1630n/a return self.seqn[i]
1631n/a
1632n/aclass I:
1633n/a 'Sequence using iterator protocol'
1634n/a def __init__(self, seqn):
1635n/a self.seqn = seqn
1636n/a self.i = 0
1637n/a def __iter__(self):
1638n/a return self
1639n/a def __next__(self):
1640n/a if self.i >= len(self.seqn): raise StopIteration
1641n/a v = self.seqn[self.i]
1642n/a self.i += 1
1643n/a return v
1644n/a
1645n/aclass Ig:
1646n/a 'Sequence using iterator protocol defined with a generator'
1647n/a def __init__(self, seqn):
1648n/a self.seqn = seqn
1649n/a self.i = 0
1650n/a def __iter__(self):
1651n/a for val in self.seqn:
1652n/a yield val
1653n/a
1654n/aclass X:
1655n/a 'Missing __getitem__ and __iter__'
1656n/a def __init__(self, seqn):
1657n/a self.seqn = seqn
1658n/a self.i = 0
1659n/a def __next__(self):
1660n/a if self.i >= len(self.seqn): raise StopIteration
1661n/a v = self.seqn[self.i]
1662n/a self.i += 1
1663n/a return v
1664n/a
1665n/aclass N:
1666n/a 'Iterator missing __next__()'
1667n/a def __init__(self, seqn):
1668n/a self.seqn = seqn
1669n/a self.i = 0
1670n/a def __iter__(self):
1671n/a return self
1672n/a
1673n/aclass E:
1674n/a 'Test propagation of exceptions'
1675n/a def __init__(self, seqn):
1676n/a self.seqn = seqn
1677n/a self.i = 0
1678n/a def __iter__(self):
1679n/a return self
1680n/a def __next__(self):
1681n/a 3 // 0
1682n/a
1683n/aclass S:
1684n/a 'Test immediate stop'
1685n/a def __init__(self, seqn):
1686n/a pass
1687n/a def __iter__(self):
1688n/a return self
1689n/a def __next__(self):
1690n/a raise StopIteration
1691n/a
1692n/afrom itertools import chain
1693n/adef L(seqn):
1694n/a 'Test multiple tiers of iterators'
1695n/a return chain(map(lambda x:x, R(Ig(G(seqn)))))
1696n/a
1697n/aclass TestVariousIteratorArgs(unittest.TestCase):
1698n/a
1699n/a def test_constructor(self):
1700n/a for cons in (set, frozenset):
1701n/a for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
1702n/a for g in (G, I, Ig, S, L, R):
1703n/a self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr))
1704n/a self.assertRaises(TypeError, cons , X(s))
1705n/a self.assertRaises(TypeError, cons , N(s))
1706n/a self.assertRaises(ZeroDivisionError, cons , E(s))
1707n/a
1708n/a def test_inline_methods(self):
1709n/a s = set('november')
1710n/a for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
1711n/a for meth in (s.union, s.intersection, s.difference, s.symmetric_difference, s.isdisjoint):
1712n/a for g in (G, I, Ig, L, R):
1713n/a expected = meth(data)
1714n/a actual = meth(g(data))
1715n/a if isinstance(expected, bool):
1716n/a self.assertEqual(actual, expected)
1717n/a else:
1718n/a self.assertEqual(sorted(actual, key=repr), sorted(expected, key=repr))
1719n/a self.assertRaises(TypeError, meth, X(s))
1720n/a self.assertRaises(TypeError, meth, N(s))
1721n/a self.assertRaises(ZeroDivisionError, meth, E(s))
1722n/a
1723n/a def test_inplace_methods(self):
1724n/a for data in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5), 'december'):
1725n/a for methname in ('update', 'intersection_update',
1726n/a 'difference_update', 'symmetric_difference_update'):
1727n/a for g in (G, I, Ig, S, L, R):
1728n/a s = set('january')
1729n/a t = s.copy()
1730n/a getattr(s, methname)(list(g(data)))
1731n/a getattr(t, methname)(g(data))
1732n/a self.assertEqual(sorted(s, key=repr), sorted(t, key=repr))
1733n/a
1734n/a self.assertRaises(TypeError, getattr(set('january'), methname), X(data))
1735n/a self.assertRaises(TypeError, getattr(set('january'), methname), N(data))
1736n/a self.assertRaises(ZeroDivisionError, getattr(set('january'), methname), E(data))
1737n/a
1738n/aclass bad_eq:
1739n/a def __eq__(self, other):
1740n/a if be_bad:
1741n/a set2.clear()
1742n/a raise ZeroDivisionError
1743n/a return self is other
1744n/a def __hash__(self):
1745n/a return 0
1746n/a
1747n/aclass bad_dict_clear:
1748n/a def __eq__(self, other):
1749n/a if be_bad:
1750n/a dict2.clear()
1751n/a return self is other
1752n/a def __hash__(self):
1753n/a return 0
1754n/a
1755n/aclass TestWeirdBugs(unittest.TestCase):
1756n/a def test_8420_set_merge(self):
1757n/a # This used to segfault
1758n/a global be_bad, set2, dict2
1759n/a be_bad = False
1760n/a set1 = {bad_eq()}
1761n/a set2 = {bad_eq() for i in range(75)}
1762n/a be_bad = True
1763n/a self.assertRaises(ZeroDivisionError, set1.update, set2)
1764n/a
1765n/a be_bad = False
1766n/a set1 = {bad_dict_clear()}
1767n/a dict2 = {bad_dict_clear(): None}
1768n/a be_bad = True
1769n/a set1.symmetric_difference_update(dict2)
1770n/a
1771n/a def test_iter_and_mutate(self):
1772n/a # Issue #24581
1773n/a s = set(range(100))
1774n/a s.clear()
1775n/a s.update(range(100))
1776n/a si = iter(s)
1777n/a s.clear()
1778n/a a = list(range(100))
1779n/a s.update(range(100))
1780n/a list(si)
1781n/a
1782n/a def test_merge_and_mutate(self):
1783n/a class X:
1784n/a def __hash__(self):
1785n/a return hash(0)
1786n/a def __eq__(self, o):
1787n/a other.clear()
1788n/a return False
1789n/a
1790n/a other = set()
1791n/a other = {X() for i in range(10)}
1792n/a s = {0}
1793n/a s.update(other)
1794n/a
1795n/a# Application tests (based on David Eppstein's graph recipes ====================================
1796n/a
1797n/adef powerset(U):
1798n/a """Generates all subsets of a set or sequence U."""
1799n/a U = iter(U)
1800n/a try:
1801n/a x = frozenset([next(U)])
1802n/a for S in powerset(U):
1803n/a yield S
1804n/a yield S | x
1805n/a except StopIteration:
1806n/a yield frozenset()
1807n/a
1808n/adef cube(n):
1809n/a """Graph of n-dimensional hypercube."""
1810n/a singletons = [frozenset([x]) for x in range(n)]
1811n/a return dict([(x, frozenset([x^s for s in singletons]))
1812n/a for x in powerset(range(n))])
1813n/a
1814n/adef linegraph(G):
1815n/a """Graph, the vertices of which are edges of G,
1816n/a with two vertices being adjacent iff the corresponding
1817n/a edges share a vertex."""
1818n/a L = {}
1819n/a for x in G:
1820n/a for y in G[x]:
1821n/a nx = [frozenset([x,z]) for z in G[x] if z != y]
1822n/a ny = [frozenset([y,z]) for z in G[y] if z != x]
1823n/a L[frozenset([x,y])] = frozenset(nx+ny)
1824n/a return L
1825n/a
1826n/adef faces(G):
1827n/a 'Return a set of faces in G. Where a face is a set of vertices on that face'
1828n/a # currently limited to triangles,squares, and pentagons
1829n/a f = set()
1830n/a for v1, edges in G.items():
1831n/a for v2 in edges:
1832n/a for v3 in G[v2]:
1833n/a if v1 == v3:
1834n/a continue
1835n/a if v1 in G[v3]:
1836n/a f.add(frozenset([v1, v2, v3]))
1837n/a else:
1838n/a for v4 in G[v3]:
1839n/a if v4 == v2:
1840n/a continue
1841n/a if v1 in G[v4]:
1842n/a f.add(frozenset([v1, v2, v3, v4]))
1843n/a else:
1844n/a for v5 in G[v4]:
1845n/a if v5 == v3 or v5 == v2:
1846n/a continue
1847n/a if v1 in G[v5]:
1848n/a f.add(frozenset([v1, v2, v3, v4, v5]))
1849n/a return f
1850n/a
1851n/a
1852n/aclass TestGraphs(unittest.TestCase):
1853n/a
1854n/a def test_cube(self):
1855n/a
1856n/a g = cube(3) # vert --> {v1, v2, v3}
1857n/a vertices1 = set(g)
1858n/a self.assertEqual(len(vertices1), 8) # eight vertices
1859n/a for edge in g.values():
1860n/a self.assertEqual(len(edge), 3) # each vertex connects to three edges
1861n/a vertices2 = set(v for edges in g.values() for v in edges)
1862n/a self.assertEqual(vertices1, vertices2) # edge vertices in original set
1863n/a
1864n/a cubefaces = faces(g)
1865n/a self.assertEqual(len(cubefaces), 6) # six faces
1866n/a for face in cubefaces:
1867n/a self.assertEqual(len(face), 4) # each face is a square
1868n/a
1869n/a def test_cuboctahedron(self):
1870n/a
1871n/a # http://en.wikipedia.org/wiki/Cuboctahedron
1872n/a # 8 triangular faces and 6 square faces
1873n/a # 12 identical vertices each connecting a triangle and square
1874n/a
1875n/a g = cube(3)
1876n/a cuboctahedron = linegraph(g) # V( --> {V1, V2, V3, V4}
1877n/a self.assertEqual(len(cuboctahedron), 12)# twelve vertices
1878n/a
1879n/a vertices = set(cuboctahedron)
1880n/a for edges in cuboctahedron.values():
1881n/a self.assertEqual(len(edges), 4) # each vertex connects to four other vertices
1882n/a othervertices = set(edge for edges in cuboctahedron.values() for edge in edges)
1883n/a self.assertEqual(vertices, othervertices) # edge vertices in original set
1884n/a
1885n/a cubofaces = faces(cuboctahedron)
1886n/a facesizes = collections.defaultdict(int)
1887n/a for face in cubofaces:
1888n/a facesizes[len(face)] += 1
1889n/a self.assertEqual(facesizes[3], 8) # eight triangular faces
1890n/a self.assertEqual(facesizes[4], 6) # six square faces
1891n/a
1892n/a for vertex in cuboctahedron:
1893n/a edge = vertex # Cuboctahedron vertices are edges in Cube
1894n/a self.assertEqual(len(edge), 2) # Two cube vertices define an edge
1895n/a for cubevert in edge:
1896n/a self.assertIn(cubevert, g)
1897n/a
1898n/a
1899n/a#==============================================================================
1900n/a
1901n/aif __name__ == "__main__":
1902n/a unittest.main()