Debian Codegraph @

Lib/test/test_ctypes/test_errno.py

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