File: test_defaultdict_jy.py

package info (click to toggle)
jython 2.5.3-16%2Bdeb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 43,772 kB
  • ctags: 106,434
  • sloc: python: 351,322; java: 216,349; xml: 1,584; sh: 330; perl: 114; ansic: 102; makefile: 45
file content (83 lines) | stat: -rw-r--r-- 2,255 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
"""Misc defaultdict tests.

Made for Jython.
"""
import pickle
import time
import threading
import unittest
from collections import defaultdict
from test import test_support
from random import randint

from java.util.concurrent.atomic import AtomicInteger

class PickleTestCase(unittest.TestCase):

    def test_pickle(self):
        d = defaultdict(str, a='foo', b='bar')
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            self.assertEqual(pickle.loads(pickle.dumps(d, proto)), d)


# TODO push into test_support or some other common module - run_threads
# is originally from test_list_jy.py

class ThreadSafetyTestCase(unittest.TestCase):

    def run_threads(self, f, num=10):
        threads = []
        for i in xrange(num):
            t = threading.Thread(target=f)
            t.start()
            threads.append(t)
        timeout = 10. # be especially generous
        for t in threads:
            t.join(timeout)
            timeout = 0.
        for t in threads:
            self.assertFalse(t.isAlive())

    def test_inc_dec(self):

        class Counter(object):
            def __init__(self):
                self.atomic = AtomicInteger()
                 # waiting is important here to ensure that
                 # defaultdict factories can step on each other
                time.sleep(0.001)

            def decrementAndGet(self):
                return self.atomic.decrementAndGet()

            def incrementAndGet(self):
                return self.atomic.incrementAndGet()

            def get(self):
                return self.atomic.get()

            def __repr__(self):
                return "Counter<%s>" % (self.atomic.get())

        counters = defaultdict(Counter)
        size = 17
        
        def tester():
            for i in xrange(1000):
                j = (i + randint(0, size)) % size
                counters[j].decrementAndGet()
                time.sleep(0.0001)
                counters[j].incrementAndGet()

        self.run_threads(tester, 20)
        
        for i in xrange(size):
            self.assertEqual(counters[i].get(), 0, counters)


def test_main():
    test_support.run_unittest(PickleTestCase, ThreadSafetyTestCase)


if __name__ == '__main__':
    test_main()