def test_32bit_makefile(self): if not is_x86(): py.test.skip("i386 only") plat32 = Darwin_i386() plat64 = Darwin_x86_64() eci = ExternalCompilationInfo() cfile_content =r''' #include <stdio.h> #include <limits.h> int main() { printf("%d\n", INT_MAX < LONG_MAX); return 0; } ''' tmpdir = udir.join('32_makefile' + self.__class__.__name__).ensure(dir=1) cfile = tmpdir.join('test_int_size.c') cfile.write(cfile_content) mk = plat32.gen_makefile([cfile], ExternalCompilationInfo(), path=tmpdir) mk.write() plat32.execute_makefile(mk) res = plat32.execute(tmpdir.join('test_int_size')) self.check_res(res, '0\n') if host_factory == Darwin_x86_64: tmpdir = udir.join('64_makefile' + self.__class__.__name__).ensure(dir=1) cfile = tmpdir.join('test_int_size.c') cfile.write(cfile_content) mk = plat64.gen_makefile([cfile], ExternalCompilationInfo(), path=tmpdir) mk.write() plat64.execute_makefile(mk) res = plat64.execute(tmpdir.join('test_int_size')) self.check_res(res, '1\n')
def test_dont_inherit_across_import(self): # see the comment for test_dont_inherit_flag py.test.skip("we cannot actually check the result of this test (see comment)") from rpython.tool.udir import udir udir.join("test_dont_inherit_across_import.py").write("x = 1/2\n") space = self.space s1 = str( py.code.Source( """ from __future__ import division from test_dont_inherit_across_import import x """ ) ) w_result = space.appexec( [space.wrap(str(udir)), space.wrap(s1)], """(udir, s1): import sys copy = sys.path[:] sys.path.insert(0, udir) try: exec s1 finally: sys.path[:] = copy return x """, ) assert space.float_w(w_result) == 0
def setup_class(cls): space = cls.space class X(object): def __eq__(self, other): raise OverflowError def __hash__(self): return 42 d = {X(): 5} try: d[X()] except OverflowError: cls.w_sane_lookup = space.wrap(True) except KeyError: cls.w_sane_lookup = space.wrap(False) # starting with CPython 2.6, when the stack is almost out, we # can get a random error, instead of just a RuntimeError. # For example if an object x has a __getattr__, we can get # AttributeError if attempting to call x.__getattr__ runs out # of stack. That's annoying, so we just work around it. if cls.runappdirect: cls.w_safe_runtimerror = space.wrap(True) else: cls.w_safe_runtimerror = space.wrap(sys.version_info < (2, 6)) emptyfile = udir.join('emptyfile.py') emptyfile.write('') nullbytes = udir.join('nullbytes.py') nullbytes.write('#abc\x00def\n') nonexistent = udir.join('builtins-nonexistent') cls.w_emptyfile = space.wrap(str(emptyfile)) cls.w_nullbytes = space.wrap(str(nullbytes)) cls.w_nonexistent = space.wrap(str(nonexistent))
def test_900_files(self): txt = '#include <stdio.h>\n' for i in range(900): txt += 'int func%03d();\n' % i txt += 'int main() {\n int j=0;' for i in range(900): txt += ' j += func%03d();\n' % i txt += ' printf("%d\\n", j);\n' txt += ' return 0;};\n' cfile = udir.join('test_900_files.c') cfile.write(txt) cfiles = [cfile] for i in range(900): cfile2 = udir.join('implement%03d.c' %i) cfile2.write(''' int func%03d() { return %d; } ''' % (i, i)) cfiles.append(cfile2) mk = self.platform.gen_makefile(cfiles, ExternalCompilationInfo(), path=udir) mk.write() self.platform.execute_makefile(mk) res = self.platform.execute(udir.join('test_900_files')) self.check_res(res, '%d\n' %sum(range(900)))
def test_links(): import stat tmpfile1 = str(udir.join('test_links_1.txt')) tmpfile2 = str(udir.join('test_links_2.txt')) tmpfile3 = str(udir.join('test_links_3.txt')) f = open(tmpfile1, 'w') f.close() def does_stuff(): os.symlink(tmpfile1, tmpfile2) os.link(tmpfile1, tmpfile3) assert os.readlink(tmpfile2) == tmpfile1 flag= 0 st = os.lstat(tmpfile1) flag = flag*10 + stat.S_ISREG(st[0]) flag = flag*10 + stat.S_ISLNK(st[0]) st = os.lstat(tmpfile2) flag = flag*10 + stat.S_ISREG(st[0]) flag = flag*10 + stat.S_ISLNK(st[0]) st = os.lstat(tmpfile3) flag = flag*10 + stat.S_ISREG(st[0]) flag = flag*10 + stat.S_ISLNK(st[0]) return flag f1 = compile(does_stuff, []) res = f1() assert res == 100110 assert os.path.islink(tmpfile2) assert not os.path.islink(tmpfile3)
def setup_class(self): # ---------------------------------------- # setup code for test_setup_bootstrap_path # ---------------------------------------- from pypy.module.sys.version import CPYTHON_VERSION, PYPY_VERSION cpy_ver = '%d.%d' % CPYTHON_VERSION[:2] from lib_pypy._pypy_interact import irc_header goal_dir = os.path.dirname(app_main) # build a directory hierarchy like which contains both bin/pypy-c and # lib/pypy1.2/* prefix = udir.join('pathtest').ensure(dir=1) fake_exe = 'bin/pypy-c' if sys.platform == 'win32': fake_exe += '.exe' fake_exe = prefix.join(fake_exe).ensure(file=1) expected_path = [str(prefix.join(subdir).ensure(dir=1)) for subdir in ('lib_pypy', 'lib-python/%s' % cpy_ver)] # an empty directory from where we can't find the stdlib tmp_dir = str(udir.join('tmp').ensure(dir=1)) self.w_goal_dir = self.space.wrap(goal_dir) self.w_fake_exe = self.space.wrap(str(fake_exe)) self.w_expected_path = self.space.wrap(expected_path) self.w_trunkdir = self.space.wrap(os.path.dirname(pypydir)) self.w_is_release = self.space.wrap(PYPY_VERSION[3] == "final") self.w_tmp_dir = self.space.wrap(tmp_dir) foo_py = prefix.join('foo.py') foo_py.write("pass") self.w_foo_py = self.space.wrap(str(foo_py))
def setup_module(mod): usemodules = ["binascii", "posix", "signal", "struct", "time"] # py3k os.open uses subprocess, requiring the following per platform if os.name != "nt": usemodules += ["fcntl", "select"] else: usemodules += ["_rawffi", "thread"] mod.space = gettestobjspace(usemodules=usemodules) mod.path = udir.join("posixtestfile.txt") mod.path.write("this is a test") mod.path2 = udir.join("test_posix2-") pdir = udir.ensure("posixtestdir", dir=True) pdir.join("file1").write("test1") os.chmod(str(pdir.join("file1")), 0o600) pdir.join("file2").write("test2") pdir.join("another_longer_file_name").write("test3") mod.pdir = pdir bytes_dir = udir.ensure("fi\xc5\x9fier.txt", dir=True) bytes_dir.join("somefile").write("who cares?") bytes_dir.join("caf\xe9").write("who knows?") mod.bytes_dir = bytes_dir # an escaped surrogate mod.esurrogate_dir = udir.ensure("foo\x80", dir=True) # in applevel tests, os.stat uses the CPython os.stat. # Be sure to return times with full precision # even when running on top of CPython 2.4. os.stat_float_times(True)
def setup_module(mod): usemodules = ['binascii', 'posix', 'struct', 'time'] if os.name != 'nt': usemodules += ['fcntl'] else: # On windows, os.popen uses the subprocess module usemodules += ['_rawffi', 'thread', 'signal'] mod.space = gettestobjspace(usemodules=usemodules) mod.path = udir.join('posixtestfile.txt') mod.path.write("this is a test") mod.path2 = udir.join('test_posix2-') pdir = udir.ensure('posixtestdir', dir=True) pdir.join('file1').write("test1") os.chmod(str(pdir.join('file1')), 0600) pdir.join('file2').write("test2") pdir.join('another_longer_file_name').write("test3") mod.pdir = pdir unicode_dir = udir.ensure('fi\xc5\x9fier.txt', dir=True) unicode_dir.join('somefile').write('who cares?') unicode_dir.join('caf\xe9').write('who knows?') mod.unicode_dir = unicode_dir # in applevel tests, os.stat uses the CPython os.stat. # Be sure to return times with full precision # even when running on top of CPython 2.4. os.stat_float_times(True)
def test_estimate_nursery_s390x(): filepath = udir.join('estimate_best_nursery_size_linux2') filepath.write("""\ vendor_id : IBM/S390 # processors : 2 bogomips per cpu: 20325.00 ... cache2 : level=2 type=Data scope=Private size=2048K line_size=256 associativity=8 cache3 : level=2 type=Instruction scope=Private size=2048K line_size=256 associativity=8 ... """) result = env.get_L2cache_linux2_cpuinfo_s390x(str(filepath)) assert result == 2048 * 1024 filepath = udir.join('estimate_best_nursery_size_linux3') filepath.write("""\ vendor_id : IBM/S390 # processors : 2 bogomips per cpu: 9398.00 ... cache2 : level=2 type=Unified scope=Private size=1536K line_size=256 associativity=12 cache3 : level=3 type=Unified scope=Shared size=24576K line_size=256 associativity=12 ... """) result = env.get_L2cache_linux2_cpuinfo_s390x(str(filepath), label='cache3') assert result == 24576 * 1024 result = env.get_L2cache_linux2_cpuinfo_s390x(str(filepath), label='cache2') assert result == 1536 * 1024
def start(self): # start of a dump file if not self.TRACE: return from rpython.tool.udir import udir n = Tracer.Counter Tracer.Counter += 1 filename = 'llinterp_trace_%d.html' % n self.file = udir.join(filename).open('w') print >> self.file, self.HEADER linkname = str(udir.join('llinterp_trace.html')) try: os.unlink(linkname) except OSError: pass try: os.symlink(filename, linkname) except (AttributeError, OSError): pass self.count = 0 self.indentation = '' self.depth = 0 self.latest_call_chain = []
def test_create_exe(): if not os.name == 'nt': py.test.skip('Windows only test') dst_name = udir.join('dst/pypy.exe') src_name = udir.join('src/dydy2.exe') dll_name = udir.join('src/pypy.dll') lib_name = udir.join('src/pypy.lib') pdb_name = udir.join('src/pypy.pdb') src_name.ensure() src_name.write('exe') dll_name.ensure() dll_name.write('dll') lib_name.ensure() lib_name.write('lib') pdb_name.ensure() pdb_name.write('pdb') dst_name.ensure() class CBuilder(object): shared_library_name = dll_name td = TranslationDriver(exe_name=str(dst_name)) td.c_entryp = str(src_name) td.cbuilder = CBuilder() td.create_exe() assert dst_name.read() == 'exe' assert dst_name.new(ext='dll').read() == 'dll' assert dst_name.new(purebasename='python27',ext='lib').read() == 'lib'
def test_shutil_copy(): if os.name == 'nt': py.test.skip('Windows cannot copy or rename to an in-use file') a = udir.join('file_a') b = udir.join('file_a') a.write('hello') shutil_copy(str(a), str(b)) assert b.read() == 'hello'
def setup_class(cls): cls.space = gettestobjspace(usemodules=['_vmprof', 'struct']) cls.tmpfile = udir.join('test__vmprof.1').open('wb') cls.w_tmpfileno = cls.space.wrap(cls.tmpfile.fileno()) cls.w_tmpfilename = cls.space.wrap(cls.tmpfile.name) cls.tmpfile2 = udir.join('test__vmprof.2').open('wb') cls.w_tmpfileno2 = cls.space.wrap(cls.tmpfile2.fileno()) cls.w_tmpfilename2 = cls.space.wrap(cls.tmpfile2.name)
def setup_class(cls): cls.w_imp = cls.space.getbuiltinmodule('imp') cls.w_file_module = cls.space.wrap(__file__) latin1 = udir.join('latin1.py') latin1.write("# -*- coding: iso-8859-1 -*\n") fake_latin1 = udir.join('fake_latin1.py') fake_latin1.write("print('-*- coding: iso-8859-1 -*')") cls.w_udir = cls.space.wrap(str(udir))
def test_os_rename(): tmpfile1 = str(udir.join('test_os_rename_1.txt')) tmpfile2 = str(udir.join('test_os_rename_2.txt')) f = open(tmpfile1, 'w') f.close() def does_stuff(): os.rename(tmpfile1, tmpfile2) f1 = compile(does_stuff, []) f1() assert os.path.exists(tmpfile2) assert not os.path.exists(tmpfile1)
def setup_class(cls): testfn.write(testcode, 'w') udir.join(testmodule + '.py').write(testmodulecode, 'w') udir.ensure(testpackage, '__init__.py') udir.join(testpackage, testmodule + '.py').write(testmodulecode, 'w') space = cls.space cls.w_oldsyspath = space.appexec([space.wrap(str(udir))], """(udir): import sys old = sys.path[:] sys.path.insert(0, udir) return old """)
def eating_callback(self): h_source = py.code.Source(""" #ifndef _CALLBACK_H #define _CALLBACK_H extern Signed eating_callback(Signed arg, Signed(*call)(Signed)); #endif /* _CALLBACK_H */ """) h_include = udir.join('callback.h') h_include.write(h_source) c_source = py.code.Source(""" Signed eating_callback(Signed arg, Signed(*call)(Signed)) { Signed res = call(arg); if (res == -1) return -1; return res; } """) eci = ExternalCompilationInfo(includes=['callback.h'], include_dirs=[str(udir)], separate_module_sources=[c_source], export_symbols=['eating_callback']) args = [SIGNED, CCallback([SIGNED], SIGNED)] eating_callback = llexternal('eating_callback', args, SIGNED, compilation_info=eci) return eating_callback
def test_largefile(): if not hasattr(os, 'ftruncate'): py.test.skip("this os has no ftruncate :-(") need_sparse_files() filename = str(udir.join('test_largefile')) r4800000000 = r_longlong(4800000000L) r4900000000 = r_longlong(4900000000L) r5000000000 = r_longlong(5000000000L) r5200000000 = r_longlong(5200000000L) r9900000000 = r_longlong(9900000000L) r10000000000 = r_longlong(10000000000L) def does_stuff(): fd = os.open(filename, os.O_RDWR | os.O_CREAT, 0666) os.ftruncate(fd, r10000000000) res = os.lseek(fd, r9900000000, 0) assert res == r9900000000 res = os.lseek(fd, -r5000000000, 1) assert res == r4900000000 res = os.lseek(fd, -r5200000000, 2) assert res == r4800000000 os.close(fd) try: os.lseek(fd, 0, 0) except OSError: pass else: print "DID NOT RAISE" raise AssertionError st = os.stat(filename) assert st.st_size == r10000000000 does_stuff() os.unlink(filename) f1 = compile(does_stuff, []) f1() os.unlink(filename)
def return_char(self, signed): ctype_pref = ["un", ""][signed] rffi_type = [UCHAR, SIGNEDCHAR][signed] h_source = py.code.Source(""" %ssigned char returnchar(void) { return 42; } """ % (ctype_pref, )) h_file = udir.join("opaque2%s.h" % (ctype_pref, )) h_file.write(h_source) from rpython.rtyper.tool import rffi_platform eci = ExternalCompilationInfo( includes=[h_file.basename], include_dirs=[str(udir)] ) ll_returnchar = llexternal('returnchar', [], rffi_type, compilation_info=eci) def f(): result = ll_returnchar() return result f1 = self.compile(f, []) assert f1() == chr(42)
def test_is_valid_fd(self): assert rposix.is_valid_fd(0) == 1 fid = open(str(udir.join('validate_test.txt')), 'w') fd = fid.fileno() assert rposix.is_valid_fd(fd) == 1 fid.close() assert rposix.is_valid_fd(fd) == 0
def test_prebuilt_constant(self): py.test.skip("Think how to do it sane") h_source = py.code.Source(""" int x = 3; char** z = NULL; #endif """) h_include = udir.join('constants.h') h_include.write(h_source) eci = ExternalCompilationInfo(includes=['stdio.h', str(h_include.basename)], include_dirs=[str(udir)]) get_x, set_x = CExternVariable(lltype.Signed, 'x', eci) get_z, set_z = CExternVariable(CCHARPP, 'z', eci) def f(): one = get_x() set_x(13) return one + get_x() def g(): l = liststr2charpp(["a", "b", "c"]) try: set_z(l) return charp2str(get_z()[2]) finally: free_charpp(l) fn = self.compile(f, []) assert fn() == 16 gn = self.compile(g, []) assert gn() == "c"
def run(self, name, n=2000): pypylog = udir.join('TestCompileFramework.log') env = {'PYPYLOG': ':%s' % pypylog, 'PYPY_NO_INLINE_MALLOC': '1'} self._run(name, n, env) env['PYPY_NO_INLINE_MALLOC'] = '' self._run(name, n, env)
def test_system(self): filename = str(udir.join('test_system.txt')) arg = '%s -c "print 1+1" > %s' % (sys.executable, filename) data = rposix.system(arg) assert data == 0 assert file(filename).read().strip() == '2' os.unlink(filename)
def test_unix_socket_connect(): if getattr(rsocket, 'AF_UNIX', None) is None: py.test.skip('AF_UNIX not supported.') from rpython.tool.udir import udir sockpath = str(udir.join('test_unix_socket_connect')) a = UNIXAddress(sockpath) serversock = RSocket(AF_UNIX) serversock.bind(a) serversock.listen(1) clientsock = RSocket(AF_UNIX) clientsock.connect(a) fd, addr = serversock.accept() s = RSocket(AF_UNIX, fd=fd) s.send('X') data = clientsock.recv(100) assert data == 'X' clientsock.send('Y') data = s.recv(100) assert data == 'Y' clientsock.close() s.close()
def test_os_close(self): fname = str(udir.join('os_test.txt')) fd = os.open(fname, os.O_WRONLY|os.O_CREAT, 0777) assert fd >= 0 os.write(fd, 'Hello world') rposix.close(fd) py.test.raises(OSError, rposix.close, fd)
def setup_class(cls): if '__pypy__' not in sys.builtin_module_names: py.test.skip("must run this test with pypy") if not sys.pypy_translation_info['translation.jit']: py.test.skip("must give a pypy-c with the jit enabled") cls.tmpdir = udir.join('test-pypy-jit') cls.tmpdir.ensure(dir=True)
def run(cbuilder, args=''): # pypylog = udir.join('test_zrpy_gc.log') env = os.environ.copy() env['PYPYLOG'] = ':%s' % pypylog data = cbuilder.cmdexec(args, env=env) return data.strip()
def test_spawnve(): filename = str(udir.join('test_spawnve.txt')) progname = str(sys.executable) scriptpath = udir.join('test_spawnve.py') scriptpath.write('import os\n' + 'f=open(%r,"w")\n' % filename + 'f.write(os.environ["FOOBAR"])\n' + 'f.close\n') scriptname = str(scriptpath) def does_stuff(): l = [progname, scriptname] pid = os.spawnve(os.P_NOWAIT, progname, l, {'FOOBAR': '42'}) os.waitpid(pid, 0) func = compile(does_stuff, []) func() assert open(filename).read() == "42"
def test_mkdir(): filename = str(udir.join('test_mkdir.dir')) getllimpl(os.mkdir)(filename, 0) exc = py.test.raises(OSError, getllimpl(os.mkdir), filename, 0) assert exc.value.errno == errno.EEXIST if sys.platform == 'win32': assert exc.type is WindowsError
def convert_sources_to_files(self, cache_dir=None): if not self.separate_module_sources: return self if cache_dir is None: cache_dir = udir.join('module_cache').ensure(dir=1) num = 0 files = [] for source in self.separate_module_sources: while 1: filename = cache_dir.join('module_%d.c' % num) num += 1 if not filename.check(): break f = filename.open("w") self.write_c_header(f) source = str(source) f.write(source) if not source.endswith('\n'): f.write('\n') f.close() files.append(str(filename)) d = self._copy_attributes() d['separate_module_sources'] = () d['separate_module_files'] += tuple(files) return ExternalCompilationInfo(**d)
def setup_class(cls): try: from cffi import FFI # <== the system one, which from cffi import recompiler # needs to be at least cffi 1.0.0 from cffi import ffiplatform except ImportError: py.test.skip("system cffi module not found or older than 1.0.0") space = cls.space SRC = """ #define FOOBAR (-42) static const int FOOBAZ = -43; #define BIGPOS 420000000000L #define BIGNEG -420000000000L int add42(int x) { return x + 42; } int globalvar42 = 1234; const int globalconst42 = 4321; const char *const globalconsthello = "hello"; struct foo_s; typedef struct bar_s { int x; signed char a[]; } bar_t; enum foo_e { AA, BB, CC }; void init_test_re_python(void) { } /* windows hack */ void PyInit__test_re_python(void) { } /* windows hack */ """ tmpdir = udir.join('test_re_python') tmpdir.ensure(dir=1) c_file = tmpdir.join('_test_re_python.c') c_file.write(SRC) ext = ffiplatform.get_extension(str(c_file), '_test_re_python', export_symbols=[ 'add42', 'globalvar42', 'globalconst42', 'globalconsthello' ]) outputfilename = ffiplatform.compile(str(tmpdir), ext) cls.w_extmod = space.wrap(outputfilename) #mod.tmpdir = tmpdir # ffi = FFI() ffi.cdef(""" #define FOOBAR -42 static const int FOOBAZ = -43; #define BIGPOS 420000000000L #define BIGNEG -420000000000L int add42(int); int globalvar42; const int globalconst42; const char *const globalconsthello = "hello"; int no_such_function(int); int no_such_globalvar; struct foo_s; typedef struct bar_s { int x; signed char a[]; } bar_t; enum foo_e { AA, BB, CC }; """) ffi.set_source('re_python_pysrc', None) ffi.emit_python_code(str(tmpdir.join('re_python_pysrc.py'))) # sub_ffi = FFI() sub_ffi.cdef("static const int k2 = 121212;") sub_ffi.include(ffi) assert 'macro FOOBAR' in ffi._parser._declarations assert 'macro FOOBAZ' in ffi._parser._declarations sub_ffi.set_source('re_py_subsrc', None) sub_ffi.emit_python_code(str(tmpdir.join('re_py_subsrc.py'))) # space.appexec([space.wrap(str(tmpdir))], """(path): import _cffi_backend # force it to be initialized import sys sys.path.insert(0, path) """)
def test_random(code): filename = str(udir.join("test-rawrefcount-boehm.c")) with open(filename, "w") as f: print >> f, TEST_CODE print >> f, 'void run_test(void) {' print >> f, code print >> f, '}' err = compile_test("test-rawrefcount-boehm") if err != 0: raise OSError("gcc failed") p = subprocess.Popen("./test-rawrefcount-boehm", stdout=subprocess.PIPE, cwd=str(udir)) stdout, _ = p.communicate() assert p.wait() == 0 gcobjs = {} pyobjs = {} links_p2g = {} links_g2p = {} for line in stdout.splitlines(): if line.startswith('py obj: '): p = line[8:] assert not pyobjs.get(p) pyobjs[p] = True assert p not in links_p2g elif line.startswith('gc obj: '): g = line[8:] assert not gcobjs.get(g) gcobjs[g] = True if g in links_g2p: del links_g2p[g] elif line.startswith('-p'): p = line[2:] assert pyobjs[p] == True pyobjs[p] = False elif line.startswith('-g'): g = line[2:] assert gcobjs[g] == True gcobjs[g] = False elif line.startswith('decref to zero: '): p = line[16:] assert pyobjs[p] == False assert p not in links_p2g del pyobjs[p] elif line.startswith('create_link '): g, p = line[12:].split('-') assert g in gcobjs assert p in pyobjs assert g not in links_g2p assert p not in links_p2g links_g2p[g] = p links_p2g[p] = g elif line.startswith('link '): g, p = line[5:].split('-') assert g in gcobjs assert p in pyobjs assert links_g2p[g] == p assert links_p2g[p] == g elif line.startswith('plist['): pass elif line.startswith('next_dead: '): p = line[11:] assert pyobjs[p] == False del pyobjs[p] del links_p2g[p] else: assert False, repr(line)
_clean_cache(self.space) all_names = ', '.join(Module.interpleveldefs.keys()) backend_test_c = py.path.local(__file__).join('..', '_backend_test_c.py') lst = [] with backend_test_c.open('r') as f: for line in f: if line.startswith('def test_'): line = line[4:] line = line[:line.index('():')] lst.append(line) tmpdir = udir.join('test_c').ensure(dir=1) tmpname = tmpdir.join('_test_c.py') with tmpname.open('w') as f: for func in lst: print >> f, 'def %s(self):' % (func, ) print >> f, ' import _all_test_c' print >> f, ' _all_test_c.%s()' % (func, ) tmpname2 = tmpdir.join('_all_test_c.py') with tmpname2.open('w') as f: print >> f, 'import sys' print >> f, 'from _cffi_backend import %s' % all_names print >> f, 'class py:' print >> f, ' class test:' print >> f, ' raises = staticmethod(raises)'
def _get_next_path(ext='.py'): global _counter p = udir.join('demo_test_app_main_%d%s' % (_counter, ext)) _counter += 1 return p
class GraphPage(BaseGraphPage): save_tmp_file = str(udir.join('graph.dot'))
def setup_class(cls): path = udir.join('AppTestTypeDef.txt') path.write('hello world\n') cls.w_path = cls.space.wrap(str(path))
def setup_class(cls): tmpfile = udir.join('tmpfile') cls.w_tmpfile = cls.space.wrap(str(tmpfile))
def setup_class(cls): cls.w_tmpfilename = cls.space.wrap(str(udir.join('test__vmprof.1'))) cls.w_tmpfilename2 = cls.space.wrap(str(udir.join('test__vmprof.2')))
def write_cpuinfo(info): filepath = udir.join('get_arch_version') filepath.write(info) return str(filepath)
def __init__(self, instr): self.instr = instr self.file = udir.join(self.base_name % self.index) while self.file.check(): self.index += 1 self.file = udir.join(self.base_name % self.index)
rpython.tool.udir = mod if '--text' in sys.argv: sys.argv.remove('--text') showgraph = False else: showgraph = True if len(sys.argv) != 2: print >> sys.stderr, __doc__ sys.exit(2) # import cStringIO from rpython.tool import logparser log1 = logparser.parse_log_file(sys.argv[1]) text1 = logparser.extract_category(log1, catprefix='jit-backend-dump') f = cStringIO.StringIO() f.writelines(text1) f.seek(0) del log1, text1 # world = World() world.parse(f) if showgraph: world.find_cross_references() world.show(showtext=True) else: world.showtextonly() else: from rpython.tool.udir import udir tmpfile = str(udir.join('dump.tmp'))
def build_winerror_to_errno(): """Build a dictionary mapping windows error numbers to POSIX errno. The function returns the dict, and the default value for codes not in the dict.""" # Prior to Visual Studio 8, the MSVCRT dll doesn't export the # _dosmaperr() function, which is available only when compiled # against the static CRT library. from rpython.translator.platform import host_factory static_platform = host_factory() if static_platform.name == 'msvc': static_platform.cflags = ['/MT'] # static CRT static_platform.version = 0 # no manifest cfile = udir.join('dosmaperr.c') cfile.write(r''' #include <errno.h> #include <WinError.h> #include <stdio.h> #ifdef __GNUC__ #define _dosmaperr mingw_dosmaperr #endif int main() { int i; for(i=1; i < 65000; i++) { _dosmaperr(i); if (errno == EINVAL) { /* CPython issue #12802 */ if (i == ERROR_DIRECTORY) errno = ENOTDIR; else continue; } printf("%d\t%d\n", i, errno); } return 0; }''') try: exename = static_platform.compile([cfile], ExternalCompilationInfo(), outputfilename="dosmaperr", standalone=True) except (CompilationError, WindowsError): # Fallback for the mingw32 compiler assert static_platform.name == 'mingw32' errors = { 2: 2, 3: 2, 4: 24, 5: 13, 6: 9, 7: 12, 8: 12, 9: 12, 10: 7, 11: 8, 15: 2, 16: 13, 17: 18, 18: 2, 19: 13, 20: 13, 21: 13, 22: 13, 23: 13, 24: 13, 25: 13, 26: 13, 27: 13, 28: 13, 29: 13, 30: 13, 31: 13, 32: 13, 33: 13, 34: 13, 35: 13, 36: 13, 53: 2, 65: 13, 67: 2, 80: 17, 82: 13, 83: 13, 89: 11, 108: 13, 109: 32, 112: 28, 114: 9, 128: 10, 129: 10, 130: 9, 132: 13, 145: 41, 158: 13, 161: 2, 164: 11, 167: 13, 183: 17, 188: 8, 189: 8, 190: 8, 191: 8, 192: 8, 193: 8, 194: 8, 195: 8, 196: 8, 197: 8, 198: 8, 199: 8, 200: 8, 201: 8, 202: 8, 206: 2, 215: 11, 267: 20, 1816: 12, } else: output = os.popen(str(exename)) errors = dict(map(int, line.split()) for line in output) return errors, errno.EINVAL
def setup_module(mod): mod.space = gettestobjspace(usemodules=['_socket', 'array', 'struct']) mod.w_socket = space.appexec([], "(): import _socket as m; return m") mod.path = udir.join('fd') mod.path.write('fo')
def setup_class(cls): tmpfile = udir.join('AppTestMarshal.tmp') cls.w_tmpfile = cls.space.wrap(str(tmpfile))
def test_simple(self): self.run('simple') assert 'call_release_gil' in udir.join( 'TestCompileFramework.log').read()
def setup_class(cls): cls.tmpdir = udir.join('test_rfile') cls.tmpdir.ensure(dir=True)
def setup_module(module): testf = udir.join('test.txt') module.path = testf.strpath
def test_get_set_errno(self): self.run('get_set_errno') assert 'call_release_gil' in udir.join( 'TestCompileFramework.log').read()
def setup_class(cls): cls.w_tmpfilename = cls.space.wrap(str(udir.join('test__vmprof.1'))) cls.w_tmpfilename2 = cls.space.wrap(str(udir.join('test__vmprof.2'))) cls.w_plain = cls.space.wrap(not cls.runappdirect and '__pypy__' not in sys.builtin_module_names)
def setup_class(cls): cls.tmpname = str(udir.join('mmap-'))
def test_getauxval_no_neon(): path = udir.join('auxv') path.write(auxv, 'wb') AT_HWCAP = 16 assert getauxval(AT_HWCAP, filename=str(path)) == 2009303
def setup_class(cls): cls.w_tmpname = cls.space.wrap(str(udir.join('mmap-')))
def test_close_stack(self): self.run('close_stack') assert 'call_release_gil' in udir.join( 'TestCompileFramework.log').read()
def setup_class(cls): if not executable.check(): py.test.skip("missing pyrolog-c at %s" % (executable.dirpath(), )) cls.tmpdir = udir.join('test-pyrolog-jit') cls.tmpdir.ensure(dir=True)
w_oldout = space.sys.get('stdout') capturefn = udir.join('capturefile') w_capturefile = space.call_method(space.builtin, "open", space.wrap(str(capturefn)), space.wrap("w")) w_sys = space.sys.getmodule('sys') space.setattr(w_sys, space.wrap("stdout"), w_capturefile) try: f(*(args + (space, ))) finally: space.setattr(w_sys, space.wrap("stdout"), w_oldout) space.call_method(w_capturefile, "close") assert capturefn.read(mode='rU') == expected_output testfn = udir.join('tmp_hello_world.py') testmodule = 'tmp_hello_module' testpackage = 'tmp_package' class TestMain: def setup_class(cls): testfn.write(testcode, 'w') udir.join(testmodule + '.py').write(testmodulecode, 'w') udir.ensure(testpackage, '__init__.py') udir.join(testpackage, testmodule + '.py').write(testmodulecode, 'w') space = cls.space cls.w_oldsyspath = space.appexec([space.wrap(str(udir))], """(udir): import sys old = sys.path[:] sys.path.insert(0, udir)
def _get_filename(self): return unicode(udir.join('test_open_ascii'))
def test_loadlibrary_unicode(): import shutil test0u = unicode(udir.join(u'load\u03betest.dll')) shutil.copyfile(test0, test0u) hdll = rwin32.LoadLibraryW(test0u) assert hdll
def _get_filename(self): return (unicode(udir.join('test_open')) + u'\u65e5\u672c.txt' ) # "Japan"
@rvmprof.vmprof_execute_code("interp", lambda code: code) def interpret(code): n = code.count while n > 0: n = one_less(n) return 42 def one_less(n): return n - 1 one_less._dont_inline_ = True PROF_FILE = str(udir.join('test_ztranslation.prof')) def main(argv=[]): rthread.get_ident() # force TLOFS_thread_ident if NonConstant(False): # Hack to give os.open() the correct annotation os.open('foo', 1, 1) code1 = MyCode(6500) fd = os.open(PROF_FILE, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0666) rvmprof.enable(fd, 0.01) # code2 = MyCode(9100) stop = time.time() + 1 while time.time() < stop: interpret(code1)
def setup_class(cls): tmpfile = udir.join('tmpfile') tmpfile.write(b"a\nb\nc", mode='wb') cls.w_tmpfile = cls.space.wrap(str(tmpfile))