Debian Codegraph @

rpython/rlib/test/test_rposix.py

raw symbols SCIP
1 from hypothesis import given, strategies as st, assume
2 import pytest
3
4 from rpython.rtyper.test.test_llinterp import interpret
5 from rpython.translator.c.test.test_genc import compile
6 from rpython.tool.pytest.expecttest import ExpectTest
7 from rpython.tool.udir import udir
8 from rpython.rlib import rposix, rposix_stat, rstring
9 import os, sys
10 import errno
11 import py
12
13 def rposix_requires(funcname):
14 return pytest.mark.skipif(not hasattr(rposix, funcname),
15 reason="Requires rposix.%s()" % funcname)
16
17 win_only = pytest.mark.skipif("os.name != 'nt'")
18
19 class TestPosixFunction:
20 def test_access(self):
21 filename = str(udir.join('test_access.txt'))
22 fd = file(filename, 'w')
23 fd.close()
24
25 for mode in os.R_OK, os.W_OK, os.X_OK, os.R_OK | os.W_OK | os.X_OK:
26 result = rposix.access(filename, mode)
27 assert result == os.access(filename, mode)
28
29 def test_times(self):
30 """
31 posix.times should compile as an RPython function and should return a
32 five-tuple giving float-representations (seconds, effectively) of the four
33 fields from the underlying struct tms and the return value.
34 """
35 times = eval(compile(lambda: str(os.times()), ())())
36 assert isinstance(times, tuple)
37 assert len(times) == 5
38 for value in times:
39 assert isinstance(value, float)
40
41 @py.test.mark.skipif("not hasattr(os, 'getlogin')")
42 def test_getlogin(self):
43 try:
44 expected = os.getlogin()
45 except OSError as e:
46 py.test.skip("the underlying os.getlogin() failed: %s" % e)
47 data = rposix.getlogin()
48 assert data == expected
49
50 @win_only
51 def test_utimes(self):
52 # Windows support centiseconds
53 def f(fname, t1):
54 os.utime(fname, (t1, t1))
55
56 fname = udir.join('test_utimes.txt')
57 fname.ensure()
58 t1 = 1159195039.25
59 compile(f, (str, float))(str(fname), t1)
60 assert t1 == os.stat(str(fname)).st_mtime
61 t1 = 5000000000.0
62 compile(f, (str, float))(str(fname), t1)
63 assert t1 == os.stat(str(fname)).st_mtime
64
65 @py.test.mark.skipif("sys.platform == 'darwin'")
66 def test_utime_negative_fraction(self):
67 def f(fname, t1):
68 os.utime(fname, (t1, t1))
69
70 fname = udir.join('test_utime_negative_fraction.txt')
71 fname.ensure()
72 t1 = -123.75
73 compile(f, (str, float))(str(fname), t1)
74 got = os.stat(str(fname)).st_mtime
75 assert got == -123 or got == -123.75
76
77 @win_only
78 def test__getfullpathname(self):
79 posix = __import__(os.name)
80 sysdrv = os.getenv('SystemDrive', 'C:')
81 stuff = sysdrv + 'stuff'
82 data = rposix.getfullpathname(stuff)
83 assert data == posix._getfullpathname(stuff)
84 # the most intriguing failure of ntpath.py should not repeat, here:
85 assert not data.endswith(stuff)
86
87 @win_only
88 def test__getfullpathname_long(self):
89 ustuff = u"C:" + u"\\abcd" * 100
90 res = rposix.getfullpathname(ustuff)
91 assert res == ustuff
92
93 @win_only
94 def test__getfullpathname_unicode(self):
95 res = rposix.getfullpathname(u"foo\xf2\xf2")
96 assert res
97
98 def test_getcwd(self):
99 assert rposix.getcwd() == os.getcwd()
100
101 def test_chdir(self):
102 def check_special_envvar():
103 if sys.platform != 'win32':
104 return
105 pwd = os.getcwd()
106 import ctypes
107 buf = ctypes.create_string_buffer(1000)
108 len = ctypes.windll.kernel32.GetEnvironmentVariableA('=%c:' % pwd[0], buf, 1000)
109 if (len == 0) and "WINGDB_PYTHON" in os.environ:
110 # the ctypes call seems not to work in the Wing debugger
111 return
112 assert str(buf.value).lower() == pwd.lower()
113 # ctypes returns the drive letter in uppercase,
114 # os.getcwd does not,
115 # but there may be uppercase in os.getcwd path
116
117 pwd = os.getcwd()
118 try:
119 check_special_envvar()
120 rposix.chdir('..')
121 assert os.getcwd() == os.path.dirname(pwd)
122 check_special_envvar()
123 finally:
124 os.chdir(pwd)
125
126 def test_mkdir(self):
127 filename = str(udir.join('test_mkdir.dir'))
128 rposix.mkdir(filename, 0777)
129 with py.test.raises(OSError) as excinfo:
130 rposix.mkdir(filename, 0777)
131 assert excinfo.value.errno == errno.EEXIST
132 if sys.platform == 'win32':
133 assert excinfo.type is WindowsError
134
135 @rposix_requires('mkdirat')
136 def test_mkdirat(self):
137 relpath = 'test_mkdirat.dir'
138 filename = str(udir.join(relpath))
139 dirfd = os.open(os.path.dirname(filename), os.O_RDONLY)
140 try:
141 rposix.mkdirat(relpath, 0777, dir_fd=dirfd)
142 with py.test.raises(OSError) as excinfo:
143 rposix.mkdirat(relpath, 0777, dir_fd=dirfd)
144 assert excinfo.value.errno == errno.EEXIST
145 finally:
146 os.close(dirfd)
147
148 def test_strerror(self):
149 assert rposix.strerror(2) == os.strerror(2)
150
151 def test_system(self):
152 filename = str(udir.join('test_system.txt'))
153 arg = '%s -c "print 1+1" > %s' % (sys.executable, filename)
154 data = rposix.system(arg)
155 assert data == 0
156 with file(filename) as f:
157 assert f.read().strip() == '2'
158 os.unlink(filename)
159
160
161 @py.test.mark.skipif("os.name != 'posix'")
162 def test_execve(self):
163 EXECVE_ENV = {"foo": "bar", "baz": "quux"}
164
165 def run_execve(program, args=None, env=None, do_path_lookup=False):
166 if args is None:
167 args = [program]
168 else:
169 args = [program] + args
170 if env is None:
171 env = {}
172 # we cannot directly call execve() because it replaces the
173 # current process.
174 fd_read, fd_write = os.pipe()
175 childpid = os.fork()
176 if childpid == 0:
177 # in the child
178 os.close(fd_read)
179 os.dup2(fd_write, 1) # stdout
180 os.close(fd_write)
181 if do_path_lookup:
182 os.execvp(program, args)
183 else:
184 rposix.execve(program, args, env)
185 assert 0, "should not arrive here"
186 else:
187 # in the parent
188 os.close(fd_write)
189 child_stdout = []
190 while True:
191 data = os.read(fd_read, 4096)
192 if not data: break # closed
193 child_stdout.append(data)
194 pid, status = os.waitpid(childpid, 0)
195 os.close(fd_read)
196 return status, ''.join(child_stdout)
197
198 # Test exit status and code
199 result, child_stdout = run_execve("/usr/bin/which", ["true"], do_path_lookup=True)
200 result, child_stdout = run_execve(child_stdout.strip()) # /bin/true or /usr/bin/true
201 assert os.WIFEXITED(result)
202 assert os.WEXITSTATUS(result) == 0
203 result, child_stdout = run_execve("/usr/bin/which", ["false"], do_path_lookup=True)
204 result, child_stdout = run_execve(child_stdout.strip()) # /bin/false or /usr/bin/false
205 assert os.WIFEXITED(result)
206 assert os.WEXITSTATUS(result) == 1
207
208 # Test environment
209 result, child_stdout = run_execve("/usr/bin/env", env=EXECVE_ENV)
210 assert os.WIFEXITED(result)
211 assert os.WEXITSTATUS(result) == 0
212 assert dict([line.split('=') for line in child_stdout.splitlines()]) == EXECVE_ENV
213
214 # The following won't actually execute anything, so they don't need
215 # a child process helper.
216
217 # If the target does not exist, an OSError should result
218 info = py.test.raises(
219 OSError, rposix.execve, "this/file/is/non/existent", [], {})
220 assert info.value.errno == errno.ENOENT
221
222 # If the target is not executable, an OSError should result
223 info = py.test.raises(
224 OSError, rposix.execve, "/etc/passwd", [], {})
225 assert info.value.errno == errno.EACCES
226
227 def test_os_write(self):
228 #Same as test in rpython/test/test_rbuiltin
229 fname = str(udir.join('os_test.txt'))
230 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
231 assert fd >= 0
232 rposix.write(fd, 'Hello world')
233 os.close(fd)
234 with open(fname) as fid:
235 assert fid.read() == "Hello world"
236 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
237 os.close(fd)
238 py.test.raises(OSError, rposix.write, fd, 'Hello world')
239
240 def test_os_close(self):
241 fname = str(udir.join('os_test.txt'))
242 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
243 assert fd >= 0
244 os.write(fd, 'Hello world')
245 rposix.close(fd)
246 py.test.raises(OSError, rposix.close, fd)
247
248 def test_os_lseek(self):
249 fname = str(udir.join('os_test.txt'))
250 fd = os.open(fname, os.O_RDWR|os.O_CREAT, 0777)
251 assert fd >= 0
252 os.write(fd, 'Hello world')
253 rposix.lseek(fd,0,0)
254 assert os.read(fd, 11) == 'Hello world'
255 os.close(fd)
256 py.test.raises(OSError, rposix.lseek, fd, 0, 0)
257
258 def test_os_fsync(self):
259 fname = str(udir.join('os_test.txt'))
260 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
261 assert fd >= 0
262 os.write(fd, 'Hello world')
263 rposix.fsync(fd)
264 os.close(fd)
265 fid = open(fname)
266 assert fid.read() == 'Hello world'
267 fid.close()
268 py.test.raises(OSError, rposix.fsync, fd)
269
270 @py.test.mark.skipif("not hasattr(os, 'fdatasync')")
271 def test_os_fdatasync(self):
272 fname = str(udir.join('os_test.txt'))
273 fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
274 assert fd >= 0
275 os.write(fd, 'Hello world')
276 rposix.fdatasync(fd)
277 fid = open(fname)
278 assert fid.read() == 'Hello world'
279 os.close(fd)
280 py.test.raises(OSError, rposix.fdatasync, fd)
281
282 def test_os_kill(self):
283 import subprocess
284 import signal
285 proc = subprocess.Popen([sys.executable, "-c",
286 "import time;"
287 "time.sleep(10)",
288 ],
289 )
290 rposix.kill(proc.pid, signal.SIGTERM)
291 if os.name == 'nt':
292 expected = signal.SIGTERM
293 else:
294 expected = -signal.SIGTERM
295 assert proc.wait() == expected
296
297 def test_isatty(self):
298 assert rposix.isatty(-1) is False
299
300 @py.test.mark.skipif("not hasattr(rposix, 'makedev')")
301 def test_makedev(self):
302 dev = rposix.makedev(24, 7)
303 assert rposix.major(dev) == 24
304 assert rposix.minor(dev) == 7
305
306 @py.test.mark.skipif("not hasattr(rposix, 'memfd_create')")
307 def test_memfd_create(self):
308 fd = rposix.memfd_create("abc", rposix.MFD_CLOEXEC)
309 try:
310 s = "defghi?"
311 os.write(fd, s)
312 finally:
313 os.close(fd)
314
315 @py.test.mark.skipif("not hasattr(os, 'ttyname')")
316 class TestOsExpect(ExpectTest):
317 def test_ttyname(self):
318 def f():
319 import os
320 from rpython.rtyper.test.test_llinterp import interpret
321
322 def ll_to_string(s):
323 return ''.join(s.chars)
324
325 def f(num):
326 try:
327 return os.ttyname(num)
328 except OSError:
329 return ''
330
331 assert ll_to_string(interpret(f, [0])) == f(0)
332 assert ll_to_string(interpret(f, [338])) == ''
333
334 self.run_test(f)
335
336
337 def ll_to_string(s):
338 return ''.join(s.chars)
339
340 class UnicodeWithEncoding:
341 is_unicode = True
342
343 def __init__(self, unistr):
344 self.unistr = unistr
345
346 def as_utf8(self):
347 from rpython.rlib.runicode import unicode_encode_utf_8
348 res = unicode_encode_utf_8(self.unistr, len(self.unistr), "strict")
349 return rstring.assert_str0(res)
350
351 def as_bytes(self):
352 from rpython.rlib.runicode import unicode_encode_utf_8
353 res = unicode_encode_utf_8(self.unistr, len(self.unistr),
354 "strict")
355 return rstring.assert_str0(res)
356
357 class BasePosixUnicodeOrAscii:
358 def setup_method(self, method):
359 self.ufilename = self._get_filename()
360 try:
361 f = file(self.ufilename, 'w')
362 except UnicodeEncodeError:
363 py.test.skip("encoding not good enough")
364 f.write("test")
365 f.close()
366 if sys.platform == 'win32' and isinstance(self.ufilename, str):
367 self.path = self.ufilename
368 self.path2 = self.ufilename + ".new"
369 else:
370 self.path = UnicodeWithEncoding(self.ufilename)
371 self.path2 = UnicodeWithEncoding(self.ufilename + ".new")
372
373 def _teardown_method(self, method):
374 for path in [self.ufilename + ".new", self.ufilename]:
375 if os.path.exists(path):
376 os.unlink(path)
377
378 def test_open(self):
379 def f():
380 try:
381 fd = os.open(self.path, os.O_RDONLY, 0777)
382 try:
383 text = os.read(fd, 50)
384 return text
385 finally:
386 os.close(fd)
387 except OSError:
388 return ''
389
390 assert ll_to_string(interpret(f, [])) == "test"
391
392 def test_stat(self):
393 def f():
394 return rposix_stat.stat(self.path).st_mtime
395 if sys.platform == 'win32':
396 # double vs. float, be satisfied with sub-millisec resolution
397 assert abs(interpret(f, []) - os.stat(self.ufilename).st_mtime) < 1e-4
398 else:
399 assert interpret(f, []) == os.stat(self.ufilename).st_mtime
400
401 def test_access(self):
402 def f():
403 return rposix.access(self.path, os.R_OK)
404
405 assert interpret(f, []) == 1
406
407 def test_utime(self):
408 def f():
409 return rposix.utime(self.path, None)
410
411 interpret(f, []) # does not crash
412
413 def test_chmod(self):
414 def f():
415 return rposix.chmod(self.path, 0777)
416 f()
417 interpret(f, []) # does not crash
418
419 def test_unlink(self):
420 def f():
421 return rposix.unlink(self.path)
422
423 interpret(f, [])
424 assert not os.path.exists(self.ufilename)
425
426 def test_rename(self):
427 def f():
428 return rposix.rename(self.path, self.path2)
429
430 interpret(f, [])
431 assert not os.path.exists(self.ufilename)
432 assert os.path.exists(self.ufilename + '.new')
433
434 def test_replace(self):
435 def f():
436 return rposix.replace(self.path, self.path2)
437
438 interpret(f, [])
439 assert not os.path.exists(self.ufilename)
440 assert os.path.exists(self.ufilename + '.new')
441
442 def test_listdir(self):
443 udir = UnicodeWithEncoding(os.path.dirname(self.ufilename))
444
445 if sys.platform == 'win32':
446 def f():
447 contents = ', '.join(rposix.listdir(udir))
448 return contents.decode('utf8')
449 f() # sanity check
450 result = interpret(f, [])
451 assert os.path.basename(self.ufilename) in ll_to_string(result)
452 else:
453 def f():
454 return ', '.join(rposix.listdir(udir))
455 result = interpret(f, [])
456 assert (os.path.basename(self.ufilename).encode('utf-8') in
457 ll_to_string(result))
458
459 def test_chdir(self):
460 os.unlink(self.ufilename)
461
462 def f():
463 rposix.mkdir(self.path, 0777)
464 rposix.chdir(self.path)
465
466 curdir = os.getcwd()
467 try:
468 interpret(f, [])
469 assert os.getcwdu() == os.path.realpath(self.ufilename)
470 finally:
471 os.chdir(curdir)
472
473 def g():
474 rposix.rmdir(self.path)
475
476 try:
477 interpret(g, [])
478 finally:
479 try:
480 os.rmdir(self.ufilename)
481 except Exception:
482 pass
483
484 def test_putenv(self):
485 from rpython.rlib import rposix_environ
486
487 def f():
488 rposix.putenv(self.path, self.path)
489 rposix.unsetenv(self.path)
490
491 interpret(f, [], # does not crash
492 malloc_check=rposix_environ.REAL_UNSETENV)
493 # If we have a real unsetenv(), check that it frees the string
494 # kept alive by putenv(). Otherwise, we can't check that,
495 # because unsetenv() will keep another string alive itself.
496 test_putenv.dont_track_allocations = True
497
498
499 class TestPosixAscii(BasePosixUnicodeOrAscii):
500 def _get_filename(self):
501 return unicode(udir.join('test_open_ascii'))
502
503 @rposix_requires('openat')
504 def test_openat(self):
505 def f(dirfd):
506 try:
507 fd = rposix.openat('test_open_ascii', os.O_RDONLY, 0777, dirfd)
508 try:
509 text = os.read(fd, 50)
510 return text
511 finally:
512 os.close(fd)
513 except OSError:
514 return ''
515
516 dirfd = os.open(os.path.dirname(self.ufilename), os.O_RDONLY)
517 try:
518 assert ll_to_string(interpret(f, [dirfd])) == "test"
519 finally:
520 os.close(dirfd)
521
522 @rposix_requires('unlinkat')
523 def test_unlinkat(self):
524 def f(dirfd):
525 return rposix.unlinkat('test_open_ascii', dir_fd=dirfd)
526
527 dirfd = os.open(os.path.dirname(self.ufilename), os.O_RDONLY)
528 try:
529 interpret(f, [dirfd])
530 finally:
531 os.close(dirfd)
532 assert not os.path.exists(self.ufilename)
533
534 @rposix_requires('utimensat')
535 def test_utimensat(self):
536 def f(dirfd):
537 return rposix.utimensat('test_open_ascii',
538 0, rposix.UTIME_NOW, 0, rposix.UTIME_NOW, dir_fd=dirfd)
539
540 dirfd = os.open(os.path.dirname(self.ufilename), os.O_RDONLY)
541 try:
542 interpret(f, [dirfd]) # does not crash
543 finally:
544 os.close(dirfd)
545
546 @rposix_requires('fchmodat')
547 def test_fchmodat(self):
548 def f(dirfd):
549 return rposix.fchmodat('test_open_ascii', 0777, dirfd)
550
551 dirfd = os.open(os.path.dirname(self.ufilename), os.O_RDONLY)
552 try:
553 interpret(f, [dirfd]) # does not crash
554 finally:
555 os.close(dirfd)
556
557
558 class TestPosixUnicode(BasePosixUnicodeOrAscii):
559 def _get_filename(self):
560 return (unicode(udir.join('test_open')) +
561 u'\u65e5\u672c.txt') # "Japan"
562
563 class TestRegisteredFunctions:
564 def test_dup(self):
565 def f():
566 os.dup(4)
567 os.dup2(5, 6)
568 compile(f, ())
569
570 def test_open(self):
571 def f():
572 os.open('/tmp/t', 0, 0)
573 os.open(u'/tmp/t', 0, 0)
574 compile(f, ())
575
576
577 @rposix_requires('fdlistdir')
578 def test_fdlistdir(tmpdir):
579 tmpdir.join('file').write('text')
580 dirfd = os.open(str(tmpdir), os.O_RDONLY)
581 result = rposix.fdlistdir(dirfd)
582 # Note: fdlistdir() always closes dirfd
583 assert result == ['file']
584
585 @rposix_requires('fdlistdir')
586 def test_fdlistdir_rewinddir(tmpdir):
587 tmpdir.join('file').write('text')
588 dirfd = os.open(str(tmpdir), os.O_RDONLY)
589 result1 = rposix.fdlistdir(os.dup(dirfd))
590 result2 = rposix.fdlistdir(dirfd)
591 assert result1 == result2 == ['file']
592
593 @rposix_requires('symlinkat')
594 def test_symlinkat(tmpdir):
595 tmpdir.join('file').write('text')
596 dirfd = os.open(str(tmpdir), os.O_RDONLY)
597 try:
598 rposix.symlinkat('file', 'link', dir_fd=dirfd)
599 assert os.readlink(str(tmpdir.join('link'))) == 'file'
600 finally:
601 os.close(dirfd)
602
603 @rposix_requires('renameat')
604 def test_renameat(tmpdir):
605 tmpdir.join('file').write('text')
606 dirfd = os.open(str(tmpdir), os.O_RDONLY)
607 try:
608 rposix.renameat('file', 'file2', src_dir_fd=dirfd, dst_dir_fd=dirfd)
609 finally:
610 os.close(dirfd)
611 assert tmpdir.join('file').check(exists=False)
612 assert tmpdir.join('file2').check(exists=True)
613
614 def test_set_inheritable():
615 fd1, fd2 = os.pipe()
616 rposix.set_inheritable(fd1, True)
617 assert rposix.get_inheritable(fd1) == True
618 rposix.set_inheritable(fd1, False)
619 assert rposix.get_inheritable(fd1) == False
620 os.close(fd1)
621 os.close(fd2)
622
623 def test_SetNonInheritableCache():
624 cache = rposix.SetNonInheritableCache()
625 fd1, fd2 = os.pipe()
626 if sys.platform == 'win32':
627 rposix.set_inheritable(fd1, True)
628 rposix.set_inheritable(fd2, True)
629 assert rposix.get_inheritable(fd1) == True
630 assert rposix.get_inheritable(fd1) == True
631 assert cache.cached_inheritable == -1
632 cache.set_non_inheritable(fd1)
633 assert cache.cached_inheritable == 1
634 cache.set_non_inheritable(fd2)
635 assert cache.cached_inheritable == 1
636 assert rposix.get_inheritable(fd1) == False
637 assert rposix.get_inheritable(fd1) == False
638 os.close(fd1)
639 os.close(fd2)
640
641 def test_dup_dup2_non_inheritable():
642 for preset in [False, True]:
643 fd1, fd2 = os.pipe()
644 rposix.set_inheritable(fd1, preset)
645 rposix.set_inheritable(fd2, preset)
646 fd3 = rposix.dup(fd1, True)
647 assert rposix.get_inheritable(fd3) == True
648 fd4 = rposix.dup(fd1, False)
649 assert rposix.get_inheritable(fd4) == False
650 rposix.dup2(fd2, fd4, False)
651 assert rposix.get_inheritable(fd4) == False
652 rposix.dup2(fd2, fd3, True)
653 assert rposix.get_inheritable(fd3) == True
654 os.close(fd1)
655 os.close(fd2)
656 os.close(fd3)
657 os.close(fd4)
658
659 def test_sync():
660 if sys.platform != 'win32':
661 rposix.sync()
662
663 def test_cpu_count():
664 cc = rposix.cpu_count()
665 assert cc >= 1
666
667 @rposix_requires('set_status_flags')
668 def test_set_status_flags():
669 fd1, fd2 = os.pipe()
670 try:
671 flags = rposix.get_status_flags(fd1)
672 assert flags & rposix.O_NONBLOCK == 0
673 rposix.set_status_flags(fd1, flags | rposix.O_NONBLOCK)
674 assert rposix.get_status_flags(fd1) & rposix.O_NONBLOCK != 0
675 finally:
676 os.close(fd1)
677 os.close(fd2)
678
679 @rposix_requires('getpriority')
680 def test_getpriority():
681 # a "don't crash" kind of test only
682 prio = rposix.getpriority(rposix.PRIO_PROCESS, 0)
683 rposix.setpriority(rposix.PRIO_PROCESS, 0, prio)
684 py.test.raises(OSError, rposix.getpriority, rposix.PRIO_PGRP, 123456789)
685
686 if sys.platform != 'win32':
687 def test_sendfile():
688 from rpython.rlib import rsocket
689 s1, s2 = rsocket.socketpair()
690 relpath = 'test_sendfile'
691 filename = str(udir.join(relpath))
692 fd = os.open(filename, os.O_RDWR|os.O_CREAT, 0777)
693 os.write(fd, 'abcdefghij')
694 res = rposix.sendfile(s1.fd, fd, 3, 5)
695 assert res == 5
696 data = os.read(s2.fd, 10)
697 assert data == 'defgh'
698 os.close(fd)
699 s2.close()
700 s1.close()
701
702 def test_sendfile_invalid_offset():
703 from rpython.rlib import rsocket
704 s1, s2 = rsocket.socketpair()
705 relpath = 'test_sendfile_invalid_offset'
706 filename = str(udir.join(relpath))
707 fd = os.open(filename, os.O_RDWR|os.O_CREAT, 0777)
708 os.write(fd, 'abcdefghij')
709 with py.test.raises(OSError) as excinfo:
710 rposix.sendfile(s1.fd, fd, -1, 5)
711 assert excinfo.value.errno == errno.EINVAL
712 os.close(fd)
713 s2.close()
714 s1.close()
715
716 if sys.platform.startswith('linux'):
717 def test_sendfile_no_offset():
718 from rpython.rlib import rsocket
719 s1, s2 = rsocket.socketpair()
720 relpath = 'test_sendfile'
721 filename = str(udir.join(relpath))
722 fd = os.open(filename, os.O_RDWR|os.O_CREAT, 0777)
723 os.write(fd, 'abcdefghij')
724 os.lseek(fd, 3, 0)
725 res = rposix.sendfile_no_offset(s1.fd, fd, 5)
726 assert res == 5
727 data = os.read(s2.fd, 10)
728 assert data == 'defgh'
729 os.close(fd)
730 s2.close()
731 s1.close()
732
733 if sys.platform == "darwin":
734 def test_sendfile_partial(tmpdir):
735 # issue 3964
736 from rpython.rlib.rsocket import socketpair
737 wsock, rsock = socketpair()
738 wsock.setblocking(False)
739 rsock.setblocking(False)
740
741 recvd = 0
742 with open(str(tmpdir / "sendfile.txt"), "wb+") as file:
743 file.write(b"x" * 131072)
744 file.flush()
745 file.seek(0)
746
747 sent = rposix.sendfile(wsock.fd, file.fileno(),
748 offset=0, count=131072)
749 assert sent > 0
750 try:
751 chunk = rsock.recv(1024)
752 while chunk:
753 recvd += len(chunk)
754 chunk = rsock.recv(1024)
755 except Exception as e:
756 pass
757 assert recvd == sent
758
759
760 @rposix_requires('pread')
761 def test_pread():
762 fname = str(udir.join('os_test.txt'))
763 fd = os.open(fname, os.O_RDWR | os.O_CREAT)
764 try:
765 assert fd >= 0
766 os.write(fd, b'Hello world')
767 os.lseek(fd, 0, 0)
768 assert rposix.pread(fd, 2, 1) == b'el'
769 finally:
770 os.close(fd)
771 py.test.raises(OSError, rposix.pread, fd, 2, 1)
772
773 @rposix_requires('pwrite')
774 def test_pwrite():
775 fname = str(udir.join('os_test.txt'))
776 fd = os.open(fname, os.O_RDWR | os.O_CREAT, 0777)
777 try:
778 assert fd >= 0
779 os.write(fd, b'Hello world')
780 os.lseek(fd, 0, 0)
781 rposix.pwrite(fd, b'ea', 1)
782 assert os.read(fd, 4) == b'Heal'
783 finally:
784 os.close(fd)
785 py.test.raises(OSError, rposix.pwrite, fd, b'ea', 1)
786
787 @rposix_requires('posix_fadvise')
788 def test_posix_fadvise():
789 if sys.maxint <= 2**32:
790 py.test.skip("ll2ctypes run of posix_fadvise() on 32-bit "
791 "gets confused by the size of OFF_T")
792 fname = str(udir.join('test_os_posix_fadvise'))
793 fd = os.open(fname, os.O_CREAT | os.O_RDWR)
794 try:
795 os.write(fd, b"foobar")
796 assert rposix.posix_fadvise(fd, 0, 1, rposix.POSIX_FADV_WILLNEED) is None
797 assert rposix.posix_fadvise(fd, 1, 1, rposix.POSIX_FADV_NORMAL) is None
798 assert rposix.posix_fadvise(fd, 2, 1, rposix.POSIX_FADV_SEQUENTIAL) is None
799 assert rposix.posix_fadvise(fd, 3, 1, rposix.POSIX_FADV_RANDOM) is None
800 assert rposix.posix_fadvise(fd, 4, 1, rposix.POSIX_FADV_NOREUSE) is None
801 assert rposix.posix_fadvise(fd, 5, 1, rposix.POSIX_FADV_DONTNEED) is None
802 py.test.raises(OSError, rposix.posix_fadvise, fd, 6, 1, 1234567)
803 finally:
804 os.close(fd)
805
806 @rposix_requires('posix_fallocate')
807 def test_posix_fallocate():
808 if sys.maxint <= 2**32:
809 py.test.skip("ll2ctypes run of posix_fallocate() on 32-bit "
810 "gets confused by the size of OFF_T")
811 fname = str(udir.join('os_test.txt'))
812 fd = os.open(fname, os.O_WRONLY | os.O_CREAT, 0777)
813 try:
814 assert rposix.posix_fallocate(fd, 0, 10) == 0
815 except OSError as inst:
816 """ ZFS seems not to support fallocate.
817 so skipping solaris-based since it is likely to come with ZFS
818 """
819 if inst.errno != errno.EINVAL or not sys.platform.startswith("sunos"):
820 raise
821 finally:
822 os.close(fd)
823
824 @rposix_requires('sched_get_priority_max')
825 def test_sched_get_priority_max():
826 assert rposix.sched_get_priority_max(rposix.SCHED_FIFO) != -1
827 assert rposix.sched_get_priority_max(rposix.SCHED_RR) != -1
828 assert rposix.sched_get_priority_max(rposix.SCHED_OTHER) != -1
829 if sys.platform != 'darwin':
830 assert rposix.sched_get_priority_max(rposix.SCHED_BATCH) != -1
831
832 @rposix_requires('sched_get_priority_min')
833 def test_sched_get_priority_min():
834 assert rposix.sched_get_priority_min(rposix.SCHED_FIFO) != -1
835 assert rposix.sched_get_priority_min(rposix.SCHED_RR) != -1
836 assert rposix.sched_get_priority_min(rposix.SCHED_OTHER) != -1
837 if sys.platform != 'darwin':
838 assert rposix.sched_get_priority_min(rposix.SCHED_BATCH) != -1
839
840 @rposix_requires('sched_get_priority_min')
841 def test_os_sched_priority_max_greater_than_min():
842 policy = rposix.SCHED_RR
843 low = rposix.sched_get_priority_min(policy)
844 high = rposix.sched_get_priority_max(policy)
845 assert isinstance(low, int) == True
846 assert isinstance(high, int) == True
847 assert high > low
848
849 @rposix_requires('sched_yield')
850 def test_sched_yield():
851 if sys.platform != 'win32':
852 rposix.sched_yield()
853
854 @rposix_requires('lockf')
855 def test_os_lockf():
856 fname = str(udir.join('os_test.txt'))
857 fd = os.open(fname, os.O_WRONLY | os.O_CREAT, 0777)
858 try:
859 os.write(fd, b'test')
860 os.lseek(fd, 0, 0)
861 rposix.lockf(fd, rposix.F_LOCK, 4)
862 rposix.lockf(fd, rposix.F_ULOCK, 4)
863 finally:
864 os.close(fd)
865
866 def check_working_xattr():
867 fname = str(udir.join('xattr_test0.txt'))
868 with open(fname, 'wb'):
869 pass
870 try:
871 rposix.setxattr(fname, 'user.foo', '')
872 except OSError:
873 return False
874 else:
875 return True
876
877 @pytest.mark.skipif(not (hasattr(rposix, 'getxattr') and check_working_xattr()),
878 reason="Requires working rposix.getxattr()")
879 @given(
880 name=st.text(
881 alphabet=st.characters(min_codepoint=1), min_size=1, max_size=10),
882 value=st.binary(max_size=10),
883 follow_symlinks=st.booleans(), use_fd=st.booleans())
884 def test_xattr(name, value, follow_symlinks, use_fd):
885 assume(follow_symlinks or not use_fd)
886 name = 'user.' + name.encode('utf-8')
887 fname = str(udir.join('xattr_test.txt'))
888 try:
889 os.unlink(fname)
890 except OSError:
891 pass
892 with open(fname, 'wb'):
893 pass
894 if use_fd:
895 file_id = os.open(fname, os.O_CREAT, 0777)
896 read, write, delete = rposix.fgetxattr, rposix.fsetxattr, rposix.fremovexattr
897 all_names = rposix.flistxattr
898 else:
899 file_id = fname
900 if follow_symlinks:
901 read, write, delete = rposix.getxattr, rposix.setxattr, rposix.removexattr
902 all_names = rposix.listxattr
903 else:
904 read = lambda *args, **kwargs: rposix.getxattr(*args, follow_symlinks=False, **kwargs)
905 write = lambda *args, **kwargs: rposix.setxattr(*args, follow_symlinks=False, **kwargs)
906 delete = lambda *args, **kwargs: rposix.removexattr(*args, follow_symlinks=False, **kwargs)
907 all_names = lambda *args, **kwargs: rposix.listxattr(*args, follow_symlinks=False, **kwargs)
908 try:
909 init_names = all_names(file_id)
910 with pytest.raises(OSError):
911 read(file_id, name)
912 write(file_id, name, value)
913 assert read(file_id, name) == value
914 assert set(all_names(file_id)) == set(init_names + [name])
915 assert '' not in all_names(file_id)
916 delete(file_id, name)
917 with pytest.raises(OSError):
918 read(file_id, name)
919 assert set(all_names(file_id)) == set(init_names)
920 finally:
921 if use_fd:
922 os.close(file_id)
923
924 @pytest.mark.skipif(not hasattr(rposix, 'getgrouplist'),
925 reason="Requires working rposix.getgrouplist()")
926 @rposix_requires('getgrouplist')
927 def test_getgrouplist():
928 import pwd
929 user = pwd.getpwuid(os.getuid())[0]
930 group = pwd.getpwuid(os.getuid())[3]
931 assert group in rposix.getgrouplist(user, group)
932
933 @pytest.mark.skipif(not hasattr(rposix, 'sched_rr_get_interval'),
934 reason="Requires working rposix.sched_rr_get_interval()")
935 def test_sched_rr_get_interval():
936 try:
937 interval = rposix.sched_rr_get_interval(0)
938 except OSError as e:
939 # This likely means that sched_rr_get_interval is only valid for
940 # processes with the SCHED_RR scheduler in effect.
941 if e.errno != errno.EINVAL:
942 raise
943 pytest.mark.skip("only works on SCHED_RR processes")
944 assert isinstance(interval, float)
945 # Reasonable constraints, I think.
946 assert interval > 0
947 assert interval < 1.
948
949 @pytest.mark.skipif(not hasattr(rposix, 'sched_getscheduler'),
950 reason="Requires working rposix.sched_getscheduler()")
951 def test_get_and_set_scheduler_and_param():
952 possible_schedulers = [sched for name, sched in rposix.__dict__.items()
953 if name.startswith("SCHED_")]
954 mine = rposix.sched_getscheduler(0)
955 assert mine in possible_schedulers
956 try:
957 parent = rposix.sched_getscheduler(os.getppid())
958 except OSError as e:
959 if e.errno != errno.EPERM:
960 raise
961 else:
962 assert parent in possible_schedulers
963 with pytest.raises(OSError):
964 rposix.sched_getscheduler(-1)
965 with pytest.raises(OSError):
966 rposix.sched_getparam(-1)
967 param = rposix.sched_getparam(0)
968 assert param == 0
969
970 # POSIX states that calling sched_setparam() or sched_setscheduler() on
971 # a process with a scheduling policy other than SCHED_FIFO or SCHED_RR
972 # is implementation-defined: NetBSD and FreeBSD can return EINVAL.
973 if not sys.platform.startswith(('freebsd', 'netbsd')):
974 try:
975 rposix.sched_setscheduler(0, mine, param)
976 rposix.sched_setparam(0, param)
977 except OSError as e:
978 if e.errno != errno.EPERM:
979 raise
980 with pytest.raises(OSError):
981 rposix.sched_setparam(-1, param)
982 with pytest.raises(OSError):
983 rposix.sched_setscheduler(-1, mine, param)
984
985 large = 214748364700
986 if large < sys.maxint:
987 param = large # rposix.sched_param(large)
988 with pytest.raises(OSError):
989 rposix.sched_setparam(0, param)
990 # param = rposix.sched_param(sched_priority=-large)
991 # with pytest.raises(OverflowError):
992 # rposix.sched_setparam(0, param)