| 1 | import unittest, os, errno |
| 2 | import threading |
| 3 | |
| 4 | from ctypes import * |
| 5 | from ctypes.util import find_library |
| 6 | |
| 7 | class Test(unittest.TestCase): |
| 8 | def test_open(self): |
| 9 | libc_name = find_library("c") |
| 10 | if libc_name is None: |
| 11 | raise unittest.SkipTest("Unable to find C library") |
| 12 | libc = CDLL(libc_name, use_errno=True) |
| 13 | if os.name == "nt": |
| 14 | libc_open = libc._open |
| 15 | else: |
| 16 | libc_open = libc.open |
| 17 | |
| 18 | libc_open.argtypes = c_char_p, c_int |
| 19 | |
| 20 | self.assertEqual(libc_open(b"", 0), -1) |
| 21 | self.assertEqual(get_errno(), errno.ENOENT) |
| 22 | |
| 23 | self.assertEqual(set_errno(32), errno.ENOENT) |
| 24 | self.assertEqual(get_errno(), 32) |
| 25 | |
| 26 | def _worker(): |
| 27 | set_errno(0) |
| 28 | |
| 29 | libc = CDLL(libc_name, use_errno=False) |
| 30 | if os.name == "nt": |
| 31 | libc_open = libc._open |
| 32 | else: |
| 33 | libc_open = libc.open |
| 34 | libc_open.argtypes = c_char_p, c_int |
| 35 | self.assertEqual(libc_open(b"", 0), -1) |
| 36 | self.assertEqual(get_errno(), 0) |
| 37 | |
| 38 | t = threading.Thread(target=_worker) |
| 39 | t.start() |
| 40 | t.join() |
| 41 | |
| 42 | self.assertEqual(get_errno(), 32) |
| 43 | set_errno(0) |
| 44 | |
| 45 | @unittest.skipUnless(os.name == "nt", 'Test specific to Windows') |
| 46 | def test_GetLastError(self): |
| 47 | dll = WinDLL("kernel32", use_last_error=True) |
| 48 | GetModuleHandle = dll.GetModuleHandleA |
| 49 | GetModuleHandle.argtypes = [c_wchar_p] |
| 50 | |
| 51 | self.assertEqual(0, GetModuleHandle("foo")) |
| 52 | self.assertEqual(get_last_error(), 126) |
| 53 | |
| 54 | self.assertEqual(set_last_error(32), 126) |
| 55 | self.assertEqual(get_last_error(), 32) |
| 56 | |
| 57 | def _worker(): |
| 58 | set_last_error(0) |
| 59 | |
| 60 | dll = WinDLL("kernel32", use_last_error=False) |
| 61 | GetModuleHandle = dll.GetModuleHandleW |
| 62 | GetModuleHandle.argtypes = [c_wchar_p] |
| 63 | GetModuleHandle("bar") |
| 64 | |
| 65 | self.assertEqual(get_last_error(), 0) |
| 66 | |
| 67 | t = threading.Thread(target=_worker) |
| 68 | t.start() |
| 69 | t.join() |
| 70 | |
| 71 | self.assertEqual(get_last_error(), 32) |
| 72 | |
| 73 | set_last_error(0) |
| 74 | |
| 75 | if __name__ == "__main__": |
| 76 | unittest.main() |