Debian Codegraph @

pypy/sandbox/test/test_pypy_interact.py

raw symbols SCIP
1 import os, stat, errno, py
2 from pypy.sandbox.pypy_interact import PyPySandboxedProc
3 from rpython.translator.interactive import Translation
4
5 from pypy.module.sys.version import CPYTHON_VERSION
6 from pypy.tool.lib_pypy import LIB_PYTHON
7
8 VERSION = '%d' % CPYTHON_VERSION[0]
9 SITE_PY_CONTENT = LIB_PYTHON.join('site.py').read()
10 ERROR_TEXT = os.strerror(errno.ENOENT)
11
12 if os.name == 'nt':
13 py.test.skip('sandbox not supported on windows')
14
15 def assert_(cond, text):
16 if not cond:
17 print "assert failed:", text
18 raise AssertionError
19
20 def mini_pypy_like_entry_point(argv):
21 """An RPython standalone executable that does the same kind of I/O as
22 PyPy when it starts up.
23 """
24 assert_(len(argv) == 3, "expected len(argv) == 3")
25 assert_(argv[1] == 'foo', "bad argv[1]")
26 assert_(argv[2] == 'bar', "bad argv[2]")
27 env = os.environ.items()
28 assert_(len(env) == 0, "empty environment expected")
29 assert_(argv[0] == '/bin/pypy3-c', "bad argv[0]")
30 st = os.lstat('/bin/pypy3-c')
31 assert_(stat.S_ISREG(st.st_mode), "bad st_mode for /bin/pypy3-c")
32 for dirname in ['/bin/lib-python/' + VERSION, '/bin/lib_pypy']:
33 st = os.stat(dirname)
34 assert_(stat.S_ISDIR(st.st_mode), "bad st_mode for " + dirname)
35 assert_(os.environ.get('PYTHONPATH') is None, "unexpected $PYTHONPATH")
36 try:
37 os.stat('site')
38 except OSError:
39 pass
40 else:
41 assert_(False, "os.stat('site') should have failed")
42
43 try:
44 os.stat('/bin/lib-python/%s/site.pyc' % VERSION)
45 except OSError:
46 pass
47 else:
48 assert_(False, "os.stat('....pyc') should have failed")
49 fd = os.open('/bin/lib-python/%s/site.py' % VERSION,
50 os.O_RDONLY, 0666)
51 length = 8192
52 ofs = 0
53 while True:
54 data = os.read(fd, length)
55 if not data: break
56 end = ofs+length
57 if end > len(SITE_PY_CONTENT):
58 end = len(SITE_PY_CONTENT)
59 assert_(data == SITE_PY_CONTENT[ofs:end], "bad data from site.py")
60 ofs = end
61 os.close(fd)
62 assert_(ofs == len(SITE_PY_CONTENT), "not enough data from site.py")
63 assert_(os.getcwd() == '/tmp', "bad cwd")
64 assert_(os.strerror(errno.ENOENT) == ERROR_TEXT, "bad strerror(ENOENT)")
65 assert_(os.isatty(0), "isatty(0) returned False")
66 # an obvious 'attack'
67 try:
68 os.open('/spam', os.O_RDWR | os.O_CREAT, 0666)
69 except OSError:
70 pass
71 else:
72 assert_(False, "os.open('/spam') should have failed")
73 return 0
74
75
76 def setup_module(mod):
77 t = Translation(mini_pypy_like_entry_point, backend='c', sandbox=True,
78 lldebug=True)
79 mod.executable = str(t.compile())
80
81
82 def test_run():
83 sandproc = PyPySandboxedProc(executable, ['foo', 'bar'])
84 returncode = sandproc.interact()
85 assert returncode == 0