PageRenderTime 47ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

http://github.com/pypy/pypy
Python | 295 lines | 258 code | 22 blank | 15 comment | 23 complexity | d793eff31d9094d9a7e67c0c33ca720f MD5 | raw file
  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.module import ll_os #has side effect of registering functions
  7. from pypy.rpython import extregistry
  8. import errno
  9. import sys
  10. import py
  11. def getllimpl(fn):
  12. return extregistry.lookup(fn).lltypeimpl
  13. def test_access():
  14. filename = str(udir.join('test_access.txt'))
  15. fd = file(filename, 'w')
  16. fd.close()
  17. for mode in os.R_OK, os.W_OK, os.X_OK, os.R_OK | os.W_OK | os.X_OK:
  18. result = getllimpl(os.access)(filename, mode)
  19. assert result == os.access(filename, mode)
  20. def test_times():
  21. """
  22. posix.times should compile as an RPython function and should return a
  23. five-tuple giving float-representations (seconds, effectively) of the four
  24. fields from the underlying struct tms and the return value.
  25. """
  26. times = compile(lambda: os.times(), ())()
  27. assert isinstance(times, tuple)
  28. assert len(times) == 5
  29. for value in times:
  30. assert isinstance(value, float)
  31. def test_getlogin():
  32. if not hasattr(os, 'getlogin'):
  33. py.test.skip('posix specific function')
  34. try:
  35. expected = os.getlogin()
  36. except OSError, e:
  37. py.test.skip("the underlying os.getlogin() failed: %s" % e)
  38. data = getllimpl(os.getlogin)()
  39. assert data == expected
  40. def test_utimes():
  41. if os.name != 'nt':
  42. py.test.skip('Windows specific feature')
  43. # Windows support centiseconds
  44. def f(fname, t1):
  45. os.utime(fname, (t1, t1))
  46. fname = udir.join('test_utimes.txt')
  47. fname.ensure()
  48. t1 = 1159195039.25
  49. compile(f, (str, float))(str(fname), t1)
  50. assert t1 == os.stat(str(fname)).st_mtime
  51. def test__getfullpathname():
  52. if os.name != 'nt':
  53. py.test.skip('nt specific function')
  54. posix = __import__(os.name)
  55. sysdrv = os.getenv('SystemDrive', 'C:')
  56. stuff = sysdrv + 'stuff'
  57. data = getllimpl(posix._getfullpathname)(stuff)
  58. assert data == posix._getfullpathname(stuff)
  59. # the most intriguing failure of ntpath.py should not repeat, here:
  60. assert not data.endswith(stuff)
  61. def test_getcwd():
  62. data = getllimpl(os.getcwd)()
  63. assert data == os.getcwd()
  64. def test_chdir():
  65. def check_special_envvar():
  66. if sys.platform != 'win32':
  67. return
  68. pwd = os.getcwd()
  69. import ctypes
  70. buf = ctypes.create_string_buffer(1000)
  71. len = ctypes.windll.kernel32.GetEnvironmentVariableA('=%c:' % pwd[0], buf, 1000)
  72. if (len == 0) and "WINGDB_PYTHON" in os.environ:
  73. # the ctypes call seems not to work in the Wing debugger
  74. return
  75. assert str(buf.value).lower() == pwd.lower()
  76. # ctypes returns the drive letter in uppercase,
  77. # os.getcwd does not,
  78. # but there may be uppercase in os.getcwd path
  79. pwd = os.getcwd()
  80. try:
  81. check_special_envvar()
  82. getllimpl(os.chdir)('..')
  83. assert os.getcwd() == os.path.dirname(pwd)
  84. check_special_envvar()
  85. finally:
  86. os.chdir(pwd)
  87. def test_mkdir():
  88. filename = str(udir.join('test_mkdir.dir'))
  89. getllimpl(os.mkdir)(filename, 0)
  90. exc = raises(OSError, getllimpl(os.mkdir), filename, 0)
  91. assert exc.value.errno == errno.EEXIST
  92. if sys.platform == 'win32':
  93. assert exc.type is WindowsError
  94. def test_strerror():
  95. data = getllimpl(os.strerror)(2)
  96. assert data == os.strerror(2)
  97. def test_system():
  98. filename = str(udir.join('test_system.txt'))
  99. arg = '%s -c "print 1+1" > %s' % (sys.executable, filename)
  100. data = getllimpl(os.system)(arg)
  101. assert data == 0
  102. assert file(filename).read().strip() == '2'
  103. os.unlink(filename)
  104. EXECVE_ENV = {"foo": "bar", "baz": "quux"}
  105. def test_execve():
  106. if os.name != 'posix':
  107. py.test.skip('posix specific function')
  108. ll_execve = getllimpl(os.execve)
  109. def run_execve(program, args=None, env=None, do_path_lookup=False):
  110. if args is None:
  111. args = [program]
  112. else:
  113. args = [program] + args
  114. if env is None:
  115. env = {}
  116. # we cannot directly call ll_execve() because it replaces the
  117. # current process.
  118. fd_read, fd_write = os.pipe()
  119. childpid = os.fork()
  120. if childpid == 0:
  121. # in the child
  122. os.close(fd_read)
  123. os.dup2(fd_write, 1) # stdout
  124. os.close(fd_write)
  125. if do_path_lookup:
  126. os.execvp(program, args)
  127. else:
  128. ll_execve(program, args, env)
  129. assert 0, "should not arrive here"
  130. else:
  131. # in the parent
  132. os.close(fd_write)
  133. child_stdout = []
  134. while True:
  135. data = os.read(fd_read, 4096)
  136. if not data: break # closed
  137. child_stdout.append(data)
  138. pid, status = os.waitpid(childpid, 0)
  139. os.close(fd_read)
  140. return status, ''.join(child_stdout)
  141. # Test exit status and code
  142. result, child_stdout = run_execve("/usr/bin/which", ["true"], do_path_lookup=True)
  143. result, child_stdout = run_execve(child_stdout.strip()) # /bin/true or /usr/bin/true
  144. assert os.WIFEXITED(result)
  145. assert os.WEXITSTATUS(result) == 0
  146. result, child_stdout = run_execve("/usr/bin/which", ["false"], do_path_lookup=True)
  147. result, child_stdout = run_execve(child_stdout.strip()) # /bin/false or /usr/bin/false
  148. assert os.WIFEXITED(result)
  149. assert os.WEXITSTATUS(result) == 1
  150. # Test environment
  151. result, child_stdout = run_execve("/usr/bin/env", env=EXECVE_ENV)
  152. assert os.WIFEXITED(result)
  153. assert os.WEXITSTATUS(result) == 0
  154. assert dict([line.split('=') for line in child_stdout.splitlines()]) == EXECVE_ENV
  155. # The following won't actually execute anything, so they don't need
  156. # a child process helper.
  157. # If the target does not exist, an OSError should result
  158. info = py.test.raises(
  159. OSError, ll_execve, "this/file/is/non/existent", [], {})
  160. assert info.value.errno == errno.ENOENT
  161. # If the target is not executable, an OSError should result
  162. info = py.test.raises(
  163. OSError, ll_execve, "/etc/passwd", [], {})
  164. assert info.value.errno == errno.EACCES
  165. def test_os_write():
  166. #Same as test in rpython/test/test_rbuiltin
  167. fname = str(udir.join('os_test.txt'))
  168. fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
  169. assert fd >= 0
  170. f = getllimpl(os.write)
  171. f(fd, 'Hello world')
  172. os.close(fd)
  173. with open(fname) as fid:
  174. assert fid.read() == "Hello world"
  175. fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
  176. os.close(fd)
  177. raises(OSError, f, fd, 'Hello world')
  178. def test_os_close():
  179. fname = str(udir.join('os_test.txt'))
  180. fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
  181. assert fd >= 0
  182. os.write(fd, 'Hello world')
  183. f = getllimpl(os.close)
  184. f(fd)
  185. raises(OSError, f, fd)
  186. def test_os_lseek():
  187. fname = str(udir.join('os_test.txt'))
  188. fd = os.open(fname, os.O_RDWR|os.O_CREAT, 0777)
  189. assert fd >= 0
  190. os.write(fd, 'Hello world')
  191. f = getllimpl(os.lseek)
  192. f(fd,0,0)
  193. assert os.read(fd, 11) == 'Hello world'
  194. os.close(fd)
  195. raises(OSError, f, fd, 0, 0)
  196. def test_os_fsync():
  197. fname = str(udir.join('os_test.txt'))
  198. fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
  199. assert fd >= 0
  200. os.write(fd, 'Hello world')
  201. f = getllimpl(os.fsync)
  202. f(fd)
  203. os.close(fd)
  204. fid = open(fname)
  205. assert fid.read() == 'Hello world'
  206. fid.close()
  207. raises(OSError, f, fd)
  208. def test_os_fdatasync():
  209. try:
  210. f = getllimpl(os.fdatasync)
  211. except:
  212. skip('No fdatasync in os')
  213. fname = str(udir.join('os_test.txt'))
  214. fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777)
  215. assert fd >= 0
  216. os.write(fd, 'Hello world')
  217. f(fd)
  218. fid = open(fname)
  219. assert fid.read() == 'Hello world'
  220. os.close(fd)
  221. raises(OSError, f, fd)
  222. def test_os_kill():
  223. try:
  224. f = getllimpl(os.kill)
  225. except:
  226. skip('No kill in os')
  227. import subprocess
  228. import signal
  229. proc = subprocess.Popen([sys.executable, "-c",
  230. "import time;"
  231. "time.sleep(10)",
  232. ],
  233. )
  234. f(proc.pid, signal.SIGTERM)
  235. expected = -signal.SIGTERM
  236. if sys.platform.startswith('win'):
  237. expected = -expected
  238. assert proc.wait() == expected
  239. class ExpectTestOs:
  240. def setup_class(cls):
  241. if not hasattr(os, 'ttyname'):
  242. py.test.skip("no ttyname")
  243. def test_ttyname(self):
  244. import os
  245. import py
  246. from pypy.rpython.test.test_llinterp import interpret
  247. def ll_to_string(s):
  248. return ''.join(s.chars)
  249. def f(num):
  250. try:
  251. return os.ttyname(num)
  252. except OSError:
  253. return ''
  254. assert ll_to_string(interpret(f, [0])) == f(0)
  255. assert ll_to_string(interpret(f, [338])) == ''