Back to index

python3.2  3.2.2
Public Member Functions
test.test_collections.TestCounter Class Reference

List of all members.

Public Member Functions

def test_basics
def test_copying
def test_copy_subclass
def test_conversions
def test_invariant_for_the_in_operator
def test_multiset_operations
def test_subtract
def test_helper_function

Detailed Description

Definition at line 737 of file test_collections.py.


Member Function Documentation

Definition at line 739 of file test_collections.py.

00739 
00740     def test_basics(self):
00741         c = Counter('abcaba')
00742         self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1}))
00743         self.assertEqual(c, Counter(a=3, b=2, c=1))
00744         self.assertIsInstance(c, dict)
00745         self.assertIsInstance(c, Mapping)
00746         self.assertTrue(issubclass(Counter, dict))
00747         self.assertTrue(issubclass(Counter, Mapping))
00748         self.assertEqual(len(c), 3)
00749         self.assertEqual(sum(c.values()), 6)
00750         self.assertEqual(sorted(c.values()), [1, 2, 3])
00751         self.assertEqual(sorted(c.keys()), ['a', 'b', 'c'])
00752         self.assertEqual(sorted(c), ['a', 'b', 'c'])
00753         self.assertEqual(sorted(c.items()),
00754                          [('a', 3), ('b', 2), ('c', 1)])
00755         self.assertEqual(c['b'], 2)
00756         self.assertEqual(c['z'], 0)
00757         self.assertEqual(c.__contains__('c'), True)
00758         self.assertEqual(c.__contains__('z'), False)
00759         self.assertEqual(c.get('b', 10), 2)
00760         self.assertEqual(c.get('z', 10), 10)
00761         self.assertEqual(c, dict(a=3, b=2, c=1))
00762         self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})")
00763         self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)])
00764         for i in range(5):
00765             self.assertEqual(c.most_common(i),
00766                              [('a', 3), ('b', 2), ('c', 1)][:i])
00767         self.assertEqual(''.join(sorted(c.elements())), 'aaabbc')
00768         c['a'] += 1         # increment an existing value
00769         c['b'] -= 2         # sub existing value to zero
00770         del c['c']          # remove an entry
00771         del c['c']          # make sure that del doesn't raise KeyError
00772         c['d'] -= 2         # sub from a missing value
00773         c['e'] = -5         # directly assign a missing value
00774         c['f'] += 4         # add to a missing value
00775         self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4))
00776         self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff')
00777         self.assertEqual(c.pop('f'), 4)
00778         self.assertNotIn('f', c)
00779         for i in range(3):
00780             elem, cnt = c.popitem()
00781             self.assertNotIn(elem, c)
00782         c.clear()
00783         self.assertEqual(c, {})
00784         self.assertEqual(repr(c), 'Counter()')
00785         self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc')
00786         self.assertRaises(TypeError, hash, c)
00787         c.update(dict(a=5, b=3))
00788         c.update(c=1)
00789         c.update(Counter('a' * 50 + 'b' * 30))
00790         c.update()          # test case with no args
00791         c.__init__('a' * 500 + 'b' * 300)
00792         c.__init__('cdc')
00793         c.__init__()
00794         self.assertEqual(c, dict(a=555, b=333, c=3, d=1))
00795         self.assertEqual(c.setdefault('d', 5), 1)
00796         self.assertEqual(c['d'], 1)
00797         self.assertEqual(c.setdefault('e', 5), 5)
00798         self.assertEqual(c['e'], 5)

Here is the call graph for this function:

Definition at line 832 of file test_collections.py.

00832 
00833     def test_conversions(self):
00834         # Convert to: set, list, dict
00835         s = 'she sells sea shells by the sea shore'
00836         self.assertEqual(sorted(Counter(s).elements()), sorted(s))
00837         self.assertEqual(sorted(Counter(s)), sorted(set(s)))
00838         self.assertEqual(dict(Counter(s)), dict(Counter(s).items()))
00839         self.assertEqual(set(Counter(s)), set(s))

Here is the call graph for this function:

Definition at line 823 of file test_collections.py.

00823 
00824     def test_copy_subclass(self):
00825         class MyCounter(Counter):
00826             pass
00827         c = MyCounter('slartibartfast')
00828         d = c.copy()
00829         self.assertEqual(d, c)
00830         self.assertEqual(len(d), len(c))
00831         self.assertEqual(type(d), type(c))

Definition at line 799 of file test_collections.py.

00799 
00800     def test_copying(self):
00801         # Check that counters are copyable, deepcopyable, picklable, and
00802         #have a repr/eval round-trip
00803         words = Counter('which witch had which witches wrist watch'.split())
00804         update_test = Counter()
00805         update_test.update(words)
00806         for i, dup in enumerate([
00807                     words.copy(),
00808                     copy.copy(words),
00809                     copy.deepcopy(words),
00810                     pickle.loads(pickle.dumps(words, 0)),
00811                     pickle.loads(pickle.dumps(words, 1)),
00812                     pickle.loads(pickle.dumps(words, 2)),
00813                     pickle.loads(pickle.dumps(words, -1)),
00814                     eval(repr(words)),
00815                     update_test,
00816                     Counter(words),
00817                     ]):
00818             msg = (i, dup, words)
00819             self.assertTrue(dup is not words)
00820             self.assertEqual(dup, words)
00821             self.assertEqual(len(dup), len(words))
00822             self.assertEqual(type(dup), type(words))

Here is the call graph for this function:

Definition at line 896 of file test_collections.py.

00896 
00897     def test_helper_function(self):
00898         # two paths, one for real dicts and one for other mappings
00899         elems = list('abracadabra')
00900 
00901         d = dict()
00902         _count_elements(d, elems)
00903         self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
00904 
00905         m = OrderedDict()
00906         _count_elements(m, elems)
00907         self.assertEqual(m,
00908              OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]))
00909 

Here is the call graph for this function:

Definition at line 840 of file test_collections.py.

00840 
00841     def test_invariant_for_the_in_operator(self):
00842         c = Counter(a=10, b=-2, c=0)
00843         for elem in c:
00844             self.assertTrue(elem in c)
00845             self.assertIn(elem, c)

Here is the call graph for this function:

Definition at line 846 of file test_collections.py.

00846 
00847     def test_multiset_operations(self):
00848         # Verify that adding a zero counter will strip zeros and negatives
00849         c = Counter(a=10, b=-2, c=0) + Counter()
00850         self.assertEqual(dict(c), dict(a=10))
00851 
00852         elements = 'abcd'
00853         for i in range(1000):
00854             # test random pairs of multisets
00855             p = Counter(dict((elem, randrange(-2,4)) for elem in elements))
00856             p.update(e=1, f=-1, g=0)
00857             q = Counter(dict((elem, randrange(-2,4)) for elem in elements))
00858             q.update(h=1, i=-1, j=0)
00859             for counterop, numberop in [
00860                 (Counter.__add__, lambda x, y: max(0, x+y)),
00861                 (Counter.__sub__, lambda x, y: max(0, x-y)),
00862                 (Counter.__or__, lambda x, y: max(0,x,y)),
00863                 (Counter.__and__, lambda x, y: max(0, min(x,y))),
00864             ]:
00865                 result = counterop(p, q)
00866                 for x in elements:
00867                     self.assertEqual(numberop(p[x], q[x]), result[x],
00868                                      (counterop, x, p, q))
00869                 # verify that results exclude non-positive counts
00870                 self.assertTrue(x>0 for x in result.values())
00871 
00872         elements = 'abcdef'
00873         for i in range(100):
00874             # verify that random multisets with no repeats are exactly like sets
00875             p = Counter(dict((elem, randrange(0, 2)) for elem in elements))
00876             q = Counter(dict((elem, randrange(0, 2)) for elem in elements))
00877             for counterop, setop in [
00878                 (Counter.__sub__, set.__sub__),
00879                 (Counter.__or__, set.__or__),
00880                 (Counter.__and__, set.__and__),
00881             ]:
00882                 counter_result = counterop(p, q)
00883                 set_result = setop(set(p.elements()), set(q.elements()))
00884                 self.assertEqual(counter_result, dict.fromkeys(set_result, 1))

Here is the call graph for this function:

Definition at line 885 of file test_collections.py.

00885 
00886     def test_subtract(self):
00887         c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
00888         c.subtract(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50)
00889         self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50))
00890         c = Counter(a=-5, b=0, c=5, d=10, e=15,g=40)
00891         c.subtract(Counter(a=1, b=2, c=-3, d=10, e=20, f=30, h=-50))
00892         self.assertEqual(c, Counter(a=-6, b=-2, c=8, d=0, e=-5, f=-30, g=40, h=50))
00893         c = Counter('aaabbcd')
00894         c.subtract('aaaabbcce')
00895         self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))

Here is the call graph for this function:


The documentation for this class was generated from the following file: