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