1import imp
2import unittest
3from test import test_support
4
5try:
6    import thread
7except ImportError:
8    thread = None
9
10@unittest.skipUnless(thread, 'threading not available')
11class LockTests(unittest.TestCase):
12
13    """Very basic test of import lock functions."""
14
15    def verify_lock_state(self, expected):
16        self.assertEqual(imp.lock_held(), expected,
17                             "expected imp.lock_held() to be %r" % expected)
18    def testLock(self):
19        LOOPS = 50
20
21        # The import lock may already be held, e.g. if the test suite is run
22        # via "import test.autotest".
23        lock_held_at_start = imp.lock_held()
24        self.verify_lock_state(lock_held_at_start)
25
26        for i in range(LOOPS):
27            imp.acquire_lock()
28            self.verify_lock_state(True)
29
30        for i in range(LOOPS):
31            imp.release_lock()
32
33        # The original state should be restored now.
34        self.verify_lock_state(lock_held_at_start)
35
36        if not lock_held_at_start:
37            try:
38                imp.release_lock()
39            except RuntimeError:
40                pass
41            else:
42                self.fail("release_lock() without lock should raise "
43                            "RuntimeError")
44
45class ReloadTests(unittest.TestCase):
46
47    """Very basic tests to make sure that imp.reload() operates just like
48    reload()."""
49
50    def test_source(self):
51        # XXX (ncoghlan): It would be nice to use test_support.CleanImport
52        # here, but that breaks because the os module registers some
53        # handlers in copy_reg on import. Since CleanImport doesn't
54        # revert that registration, the module is left in a broken
55        # state after reversion. Reinitialising the module contents
56        # and just reverting os.environ to its previous state is an OK
57        # workaround
58        with test_support.EnvironmentVarGuard():
59            import os
60            imp.reload(os)
61
62    def test_extension(self):
63        with test_support.CleanImport('time'):
64            import time
65            imp.reload(time)
66
67    def test_builtin(self):
68        with test_support.CleanImport('marshal'):
69            import marshal
70            imp.reload(marshal)
71
72
73def test_main():
74    tests = [
75        ReloadTests,
76        LockTests,
77    ]
78    test_support.run_unittest(*tests)
79
80if __name__ == "__main__":
81    test_main()
82