PageRenderTime 33ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/rpython/module/test/test_ll_os.py

https://bitbucket.org/pypy/pypy/
Python | 208 lines | 175 code | 22 blank | 11 comment | 21 complexity | c8b4c7db22346b70763c07e787cbcf6a MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. import os
  2. from py.path import local
  3. import pypy
  4. from pypy.tool.udir import udir
  5. from pypy.translator.c.test.test_genc import compile
  6. from pypy.rpython import extregistry
  7. import errno
  8. import sys
  9. import py
  10. def getllimpl(fn):
  11. return extregistry.lookup(fn).lltypeimpl
  12. def test_access():
  13. filename = str(udir.join('test_access.txt'))
  14. fd = file(filename, 'w')
  15. fd.close()
  16. for mode in os.R_OK, os.W_OK, os.X_OK, os.R_OK | os.W_OK | os.X_OK:
  17. result = getllimpl(os.access)(filename, mode)
  18. assert result == os.access(filename, mode)
  19. def test_times():
  20. """
  21. posix.times should compile as an RPython function and should return a
  22. five-tuple giving float-representations (seconds, effectively) of the four
  23. fields from the underlying struct tms and the return value.
  24. """
  25. times = compile(lambda: os.times(), ())()
  26. assert isinstance(times, tuple)
  27. assert len(times) == 5
  28. for value in times:
  29. assert isinstance(value, float)
  30. def test_getlogin():
  31. if not hasattr(os, 'getlogin'):
  32. py.test.skip('posix specific function')
  33. try:
  34. expected = os.getlogin()
  35. except OSError, e:
  36. py.test.skip("the underlying os.getlogin() failed: %s" % e)
  37. data = getllimpl(os.getlogin)()
  38. assert data == expected
  39. def test_utimes():
  40. if os.name != 'nt':
  41. py.test.skip('Windows specific feature')
  42. # Windows support centiseconds
  43. def f(fname, t1):
  44. os.utime(fname, (t1, t1))
  45. fname = udir.join('test_utimes.txt')
  46. fname.ensure()
  47. t1 = 1159195039.25
  48. compile(f, (str, float))(str(fname), t1)
  49. assert t1 == os.stat(str(fname)).st_mtime
  50. def test__getfullpathname():
  51. if os.name != 'nt':
  52. py.test.skip('nt specific function')
  53. posix = __import__(os.name)
  54. sysdrv = os.getenv('SystemDrive', 'C:')
  55. stuff = sysdrv + 'stuff'
  56. data = getllimpl(posix._getfullpathname)(stuff)
  57. assert data == posix._getfullpathname(stuff)
  58. # the most intriguing failure of ntpath.py should not repeat, here:
  59. assert not data.endswith(stuff)
  60. def test_getcwd():
  61. data = getllimpl(os.getcwd)()
  62. assert data == os.getcwd()
  63. def test_chdir():
  64. def check_special_envvar():
  65. if sys.platform != 'win32':
  66. return
  67. pwd = os.getcwd()
  68. import ctypes
  69. buf = ctypes.create_string_buffer(1000)
  70. ctypes.windll.kernel32.GetEnvironmentVariableA('=%c:' % pwd[0], buf, 1000)
  71. assert str(buf.value) == pwd
  72. pwd = os.getcwd()
  73. try:
  74. check_special_envvar()
  75. getllimpl(os.chdir)('..')
  76. assert os.getcwd() == os.path.dirname(pwd)
  77. check_special_envvar()
  78. finally:
  79. os.chdir(pwd)
  80. def test_mkdir():
  81. filename = str(udir.join('test_mkdir.dir'))
  82. getllimpl(os.mkdir)(filename, 0)
  83. exc = raises(OSError, getllimpl(os.mkdir), filename, 0)
  84. assert exc.value.errno == errno.EEXIST
  85. if sys.platform == 'win32':
  86. assert exc.type is WindowsError
  87. def test_strerror():
  88. data = getllimpl(os.strerror)(2)
  89. assert data == os.strerror(2)
  90. def test_system():
  91. filename = str(udir.join('test_system.txt'))
  92. arg = '%s -c "print 1+1" > %s' % (sys.executable, filename)
  93. data = getllimpl(os.system)(arg)
  94. assert data == 0
  95. assert file(filename).read().strip() == '2'
  96. os.unlink(filename)
  97. EXECVE_ENV = {"foo": "bar", "baz": "quux"}
  98. def test_execve():
  99. if os.name != 'posix':
  100. py.test.skip('posix specific function')
  101. ll_execve = getllimpl(os.execve)
  102. def run_execve(program, args=None, env=None, do_path_lookup=False):
  103. if args is None:
  104. args = [program]
  105. else:
  106. args = [program] + args
  107. if env is None:
  108. env = {}
  109. # we cannot directly call ll_execve() because it replaces the
  110. # current process.
  111. fd_read, fd_write = os.pipe()
  112. childpid = os.fork()
  113. if childpid == 0:
  114. # in the child
  115. os.close(fd_read)
  116. os.dup2(fd_write, 1) # stdout
  117. os.close(fd_write)
  118. if do_path_lookup:
  119. os.execvp(program, args)
  120. else:
  121. ll_execve(program, args, env)
  122. assert 0, "should not arrive here"
  123. else:
  124. # in the parent
  125. os.close(fd_write)
  126. child_stdout = []
  127. while True:
  128. data = os.read(fd_read, 4096)
  129. if not data: break # closed
  130. child_stdout.append(data)
  131. pid, status = os.waitpid(childpid, 0)
  132. os.close(fd_read)
  133. return status, ''.join(child_stdout)
  134. # Test exit status and code
  135. result, child_stdout = run_execve("/usr/bin/which", ["true"], do_path_lookup=True)
  136. result, child_stdout = run_execve(child_stdout.strip()) # /bin/true or /usr/bin/true
  137. assert os.WIFEXITED(result)
  138. assert os.WEXITSTATUS(result) == 0
  139. result, child_stdout = run_execve("/usr/bin/which", ["false"], do_path_lookup=True)
  140. result, child_stdout = run_execve(child_stdout.strip()) # /bin/false or /usr/bin/false
  141. assert os.WIFEXITED(result)
  142. assert os.WEXITSTATUS(result) == 1
  143. # Test environment
  144. result, child_stdout = run_execve("/usr/bin/env", env=EXECVE_ENV)
  145. assert os.WIFEXITED(result)
  146. assert os.WEXITSTATUS(result) == 0
  147. assert dict([line.split('=') for line in child_stdout.splitlines()]) == EXECVE_ENV
  148. # The following won't actually execute anything, so they don't need
  149. # a child process helper.
  150. # If the target does not exist, an OSError should result
  151. info = py.test.raises(
  152. OSError, ll_execve, "this/file/is/non/existent", [], {})
  153. assert info.value.errno == errno.ENOENT
  154. # If the target is not executable, an OSError should result
  155. info = py.test.raises(
  156. OSError, ll_execve, "/etc/passwd", [], {})
  157. assert info.value.errno == errno.EACCES
  158. class ExpectTestOs:
  159. def setup_class(cls):
  160. if not hasattr(os, 'ttyname'):
  161. py.test.skip("no ttyname")
  162. def test_ttyname(self):
  163. import os
  164. import py
  165. from pypy.rpython.test.test_llinterp import interpret
  166. def ll_to_string(s):
  167. return ''.join(s.chars)
  168. def f(num):
  169. try:
  170. return os.ttyname(num)
  171. except OSError:
  172. return ''
  173. assert ll_to_string(interpret(f, [0])) == f(0)
  174. assert ll_to_string(interpret(f, [338])) == ''