test_imp.py 2.3 KB

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