| 1 | import imp |
| 2 | from test.test_support import TestFailed, TestSkipped |
| 3 | try: |
| 4 | import thread |
| 5 | except ImportError: |
| 6 | raise TestSkipped("test only valid when thread support is available") |
| 7 | |
| 8 | def verify_lock_state(expected): |
| 9 | if imp.lock_held() != expected: |
| 10 | raise TestFailed("expected imp.lock_held() to be %r" % expected) |
| 11 | |
| 12 | def testLock(): |
| 13 | LOOPS = 50 |
| 14 | |
| 15 | # The import lock may already be held, e.g. if the test suite is run |
| 16 | # via "import test.autotest". |
| 17 | lock_held_at_start = imp.lock_held() |
| 18 | verify_lock_state(lock_held_at_start) |
| 19 | |
| 20 | for i in range(LOOPS): |
| 21 | imp.acquire_lock() |
| 22 | verify_lock_state(True) |
| 23 | |
| 24 | for i in range(LOOPS): |
| 25 | imp.release_lock() |
| 26 | |
| 27 | # The original state should be restored now. |
| 28 | verify_lock_state(lock_held_at_start) |
| 29 | |
| 30 | if not lock_held_at_start: |
| 31 | try: |
| 32 | imp.release_lock() |
| 33 | except RuntimeError: |
| 34 | pass |
| 35 | else: |
| 36 | raise TestFailed("release_lock() without lock should raise " |
| 37 | "RuntimeError") |
| 38 | |
| 39 | def test_main(): |
| 40 | testLock() |
| 41 | |
| 42 | if __name__ == "__main__": |
| 43 | test_main() |