Debian Codegraph @

Lib/test/test_fcntl.py

raw
1 """Test program for the fcntl C module.
2 """
3 import errno
4 import multiprocessing
5 import platform
6 import os
7 import struct
8 import sys
9 import unittest
10 from test.support import (
11 cpython_only, get_pagesize, is_apple, requires_subprocess, verbose, is_emscripten
12 )
13 from test.support.import_helper import import_module
14 from test.support.os_helper import TESTFN, unlink, make_bad_fd
15
16
17 # Skip test if no fcntl module.
18 fcntl = import_module('fcntl')
19
20
21
22 class BadFile:
23 def __init__(self, fn):
24 self.fn = fn
25 def fileno(self):
26 return self.fn
27
28 def try_lockf_on_other_process_fail(fname, cmd):
29 f = open(fname, 'wb+')
30 try:
31 fcntl.lockf(f, cmd)
32 except BlockingIOError:
33 pass
34 finally:
35 f.close()
36
37 def try_lockf_on_other_process(fname, cmd):
38 f = open(fname, 'wb+')
39 fcntl.lockf(f, cmd)
40 fcntl.lockf(f, fcntl.LOCK_UN)
41 f.close()
42
43 class TestFcntl(unittest.TestCase):
44
45 def setUp(self):
46 self.f = None
47
48 def tearDown(self):
49 if self.f and not self.f.closed:
50 self.f.close()
51 unlink(TESTFN)
52
53 @staticmethod
54 def get_lockdata():
55 try:
56 os.O_LARGEFILE
57 except AttributeError:
58 start_len = "ll"
59 else:
60 start_len = "qq"
61
62 if (
63 sys.platform.startswith(('netbsd', 'freebsd', 'openbsd'))
64 or is_apple
65 ):
66 if struct.calcsize('l') == 8:
67 off_t = 'l'
68 pid_t = 'i'
69 else:
70 off_t = 'lxxxx'
71 pid_t = 'l'
72 lockdata = struct.pack(off_t + off_t + pid_t + 'hh', 0, 0, 0,
73 fcntl.F_WRLCK, 0)
74 elif sys.platform.startswith('gnukfreebsd'):
75 lockdata = struct.pack('qqihhi', 0, 0, 0, fcntl.F_WRLCK, 0, 0)
76 elif sys.platform in ['hp-uxB', 'unixware7']:
77 lockdata = struct.pack('hhlllii', fcntl.F_WRLCK, 0, 0, 0, 0, 0, 0)
78 else:
79 lockdata = struct.pack('hh'+start_len+'hh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
80 if lockdata:
81 if verbose:
82 print('struct.pack: ', repr(lockdata))
83 return lockdata
84
85 def test_fcntl_fileno(self):
86 # the example from the library docs
87 self.f = open(TESTFN, 'wb')
88 rv = fcntl.fcntl(self.f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)
89 if verbose:
90 print('Status from fcntl with O_NONBLOCK: ', rv)
91 lockdata = self.get_lockdata()
92 rv = fcntl.fcntl(self.f.fileno(), fcntl.F_SETLKW, lockdata)
93 if verbose:
94 print('String from fcntl with F_SETLKW: ', repr(rv))
95 self.f.close()
96
97 def test_fcntl_file_descriptor(self):
98 # again, but pass the file rather than numeric descriptor
99 self.f = open(TESTFN, 'wb')
100 rv = fcntl.fcntl(self.f, fcntl.F_SETFL, os.O_NONBLOCK)
101 if verbose:
102 print('Status from fcntl with O_NONBLOCK: ', rv)
103 lockdata = self.get_lockdata()
104 rv = fcntl.fcntl(self.f, fcntl.F_SETLKW, lockdata)
105 if verbose:
106 print('String from fcntl with F_SETLKW: ', repr(rv))
107 self.f.close()
108
109 def test_fcntl_bad_file(self):
110 with self.assertRaises(ValueError):
111 fcntl.fcntl(-1, fcntl.F_SETFL, os.O_NONBLOCK)
112 with self.assertRaises(ValueError):
113 fcntl.fcntl(BadFile(-1), fcntl.F_SETFL, os.O_NONBLOCK)
114 with self.assertRaises(TypeError):
115 fcntl.fcntl('spam', fcntl.F_SETFL, os.O_NONBLOCK)
116 with self.assertRaises(TypeError):
117 fcntl.fcntl(BadFile('spam'), fcntl.F_SETFL, os.O_NONBLOCK)
118
119 @cpython_only
120 def test_fcntl_bad_file_overflow(self):
121 _testcapi = import_module("_testcapi")
122 INT_MAX = _testcapi.INT_MAX
123 INT_MIN = _testcapi.INT_MIN
124 # Issue 15989
125 with self.assertRaises(OverflowError):
126 fcntl.fcntl(INT_MAX + 1, fcntl.F_SETFL, os.O_NONBLOCK)
127 with self.assertRaises(OverflowError):
128 fcntl.fcntl(BadFile(INT_MAX + 1), fcntl.F_SETFL, os.O_NONBLOCK)
129 with self.assertRaises(OverflowError):
130 fcntl.fcntl(INT_MIN - 1, fcntl.F_SETFL, os.O_NONBLOCK)
131 with self.assertRaises(OverflowError):
132 fcntl.fcntl(BadFile(INT_MIN - 1), fcntl.F_SETFL, os.O_NONBLOCK)
133
134 @unittest.skipIf(
135 (platform.machine().startswith("arm") and platform.system() == "Linux")
136 or platform.system() == "Android",
137 "this platform returns EINVAL for F_NOTIFY DN_MULTISHOT")
138 def test_fcntl_64_bit(self):
139 # Issue GH-42434: fcntl shouldn't fail when the third arg fits in a
140 # C 'long' but not in a C 'int'.
141 try:
142 cmd = fcntl.F_NOTIFY
143 # DN_MULTISHOT is >= 2**31 in 64-bit builds
144 flags = fcntl.DN_MULTISHOT
145 except AttributeError:
146 self.skipTest("F_NOTIFY or DN_MULTISHOT unavailable")
147 fd = os.open(os.path.dirname(os.path.abspath(TESTFN)), os.O_RDONLY)
148 try:
149 try:
150 fcntl.fcntl(fd, cmd, fcntl.DN_DELETE)
151 except OSError as exc:
152 if exc.errno == errno.EINVAL:
153 self.skipTest("F_NOTIFY not available by this environment")
154 fcntl.fcntl(fd, cmd, flags)
155 finally:
156 os.close(fd)
157
158 def test_flock(self):
159 # Solaris needs readable file for shared lock
160 self.f = open(TESTFN, 'wb+')
161 fileno = self.f.fileno()
162 fcntl.flock(fileno, fcntl.LOCK_SH)
163 fcntl.flock(fileno, fcntl.LOCK_UN)
164 fcntl.flock(self.f, fcntl.LOCK_SH | fcntl.LOCK_NB)
165 fcntl.flock(self.f, fcntl.LOCK_UN)
166 fcntl.flock(fileno, fcntl.LOCK_EX)
167 fcntl.flock(fileno, fcntl.LOCK_UN)
168
169 self.assertRaises(ValueError, fcntl.flock, -1, fcntl.LOCK_SH)
170 self.assertRaises(TypeError, fcntl.flock, 'spam', fcntl.LOCK_SH)
171
172 @unittest.skipIf(platform.system() == "AIX", "AIX returns PermissionError")
173 @requires_subprocess()
174 def test_lockf_exclusive(self):
175 self.f = open(TESTFN, 'wb+')
176 cmd = fcntl.LOCK_EX | fcntl.LOCK_NB
177 fcntl.lockf(self.f, cmd)
178 mp = multiprocessing.get_context('spawn')
179 p = mp.Process(target=try_lockf_on_other_process_fail, args=(TESTFN, cmd))
180 p.start()
181 p.join()
182 fcntl.lockf(self.f, fcntl.LOCK_UN)
183 self.assertEqual(p.exitcode, 0)
184
185 @unittest.skipIf(platform.system() == "AIX", "AIX returns PermissionError")
186 @requires_subprocess()
187 def test_lockf_share(self):
188 self.f = open(TESTFN, 'wb+')
189 cmd = fcntl.LOCK_SH | fcntl.LOCK_NB
190 fcntl.lockf(self.f, cmd)
191 mp = multiprocessing.get_context('spawn')
192 p = mp.Process(target=try_lockf_on_other_process, args=(TESTFN, cmd))
193 p.start()
194 p.join()
195 fcntl.lockf(self.f, fcntl.LOCK_UN)
196 self.assertEqual(p.exitcode, 0)
197
198 @cpython_only
199 def test_flock_overflow(self):
200 _testcapi = import_module("_testcapi")
201 self.assertRaises(OverflowError, fcntl.flock, _testcapi.INT_MAX+1,
202 fcntl.LOCK_SH)
203
204 @unittest.skipIf(sys.platform != 'darwin', "F_GETPATH is only available on macos")
205 def test_fcntl_f_getpath(self):
206 self.f = open(TESTFN, 'wb')
207 expected = os.path.abspath(TESTFN).encode('utf-8')
208 res = fcntl.fcntl(self.f.fileno(), fcntl.F_GETPATH, bytes(len(expected)))
209 self.assertEqual(expected, res)
210
211 @unittest.skipUnless(
212 hasattr(fcntl, "F_SETPIPE_SZ") and hasattr(fcntl, "F_GETPIPE_SZ"),
213 "F_SETPIPE_SZ and F_GETPIPE_SZ are not available on all platforms.")
214 @unittest.skipIf(is_emscripten, "Emscripten pipefs doesn't support these")
215 def test_fcntl_f_pipesize(self):
216 test_pipe_r, test_pipe_w = os.pipe()
217 try:
218 # Get the default pipesize with F_GETPIPE_SZ
219 pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
220 pipesize = pipesize_default // 2 # A new value to detect change.
221 pagesize_default = get_pagesize()
222 if pipesize < pagesize_default: # the POSIX minimum
223 raise unittest.SkipTest(
224 'default pipesize too small to perform test.')
225 fcntl.fcntl(test_pipe_w, fcntl.F_SETPIPE_SZ, pipesize)
226 self.assertEqual(fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ),
227 pipesize)
228 finally:
229 os.close(test_pipe_r)
230 os.close(test_pipe_w)
231
232 @unittest.skipUnless(hasattr(fcntl, 'F_DUPFD'), 'need fcntl.F_DUPFD')
233 def test_bad_fd(self):
234 # gh-134744: Test error handling
235 fd = make_bad_fd()
236 with self.assertRaises(OSError):
237 fcntl.fcntl(fd, fcntl.F_DUPFD, 0)
238 with self.assertRaises(OSError):
239 fcntl.fcntl(fd, fcntl.F_DUPFD, b'\0' * 1024)
240
241
242 if __name__ == '__main__':
243 unittest.main()