Back to index

python3.2  3.2.2
test_errno.py
Go to the documentation of this file.
00001 import unittest, os, errno
00002 from ctypes import *
00003 from ctypes.util import find_library
00004 try:
00005     import threading
00006 except ImportError:
00007     threading = None
00008 
00009 class Test(unittest.TestCase):
00010     def test_open(self):
00011         libc_name = find_library("c")
00012         if libc_name is None:
00013             raise unittest.SkipTest("Unable to find C library")
00014         libc = CDLL(libc_name, use_errno=True)
00015         if os.name == "nt":
00016             libc_open = libc._open
00017         else:
00018             libc_open = libc.open
00019 
00020         libc_open.argtypes = c_char_p, c_int
00021 
00022         self.assertEqual(libc_open(b"", 0), -1)
00023         self.assertEqual(get_errno(), errno.ENOENT)
00024 
00025         self.assertEqual(set_errno(32), errno.ENOENT)
00026         self.assertEqual(get_errno(), 32)
00027 
00028         if threading:
00029             def _worker():
00030                 set_errno(0)
00031 
00032                 libc = CDLL(libc_name, use_errno=False)
00033                 if os.name == "nt":
00034                     libc_open = libc._open
00035                 else:
00036                     libc_open = libc.open
00037                 libc_open.argtypes = c_char_p, c_int
00038                 self.assertEqual(libc_open(b"", 0), -1)
00039                 self.assertEqual(get_errno(), 0)
00040 
00041             t = threading.Thread(target=_worker)
00042             t.start()
00043             t.join()
00044 
00045             self.assertEqual(get_errno(), 32)
00046             set_errno(0)
00047 
00048     @unittest.skipUnless(os.name == "nt", 'Test specific to Windows')
00049     def test_GetLastError(self):
00050         dll = WinDLL("kernel32", use_last_error=True)
00051         GetModuleHandle = dll.GetModuleHandleA
00052         GetModuleHandle.argtypes = [c_wchar_p]
00053 
00054         self.assertEqual(0, GetModuleHandle("foo"))
00055         self.assertEqual(get_last_error(), 126)
00056 
00057         self.assertEqual(set_last_error(32), 126)
00058         self.assertEqual(get_last_error(), 32)
00059 
00060         def _worker():
00061             set_last_error(0)
00062 
00063             dll = WinDLL("kernel32", use_last_error=False)
00064             GetModuleHandle = dll.GetModuleHandleW
00065             GetModuleHandle.argtypes = [c_wchar_p]
00066             GetModuleHandle("bar")
00067 
00068             self.assertEqual(get_last_error(), 0)
00069 
00070         t = threading.Thread(target=_worker)
00071         t.start()
00072         t.join()
00073 
00074         self.assertEqual(get_last_error(), 32)
00075 
00076         set_last_error(0)
00077 
00078 if __name__ == "__main__":
00079     unittest.main()