[pypy-svn] pypy commit 4f2096cecd1c: Merge from 'default'
Bitbucket
commits-noreply at bitbucket.org
Wed Dec 15 00:36:52 CET 2010
# HG changeset patch -- Bitbucket.org
# Project pypy
# URL http://bitbucket.org/pypy/pypy/overview
# User Amaury Forgeot d'Arc <amauryfa at gmail.com>
# Date 1292347965 -3600
# Node ID 4f2096cecd1c32529af9b221a90157066925abb7
# Parent 4ffed77c095c7a5cc0c38a72e489fb75340424ad
# Parent 11dd42c70507da9dc1ae3c2692f4ccaa4b3ade90
Merge from 'default'
--- a/pypy/jit/backend/cli/test/conftest.py
+++ b/pypy/jit/backend/cli/test/conftest.py
@@ -1,4 +1,4 @@
import py
-def pytest_collect_directory(path):
- py.test.skip("CLI backend tests skipped for now")
+def pytest_ignore_collect(path):
+ return True
--- a/pypy/rpython/llinterp.py
+++ b/pypy/rpython/llinterp.py
@@ -948,6 +948,9 @@ class LLFrame(object):
def op_set_stack_depth_limit(self):
raise NotImplementedError("set_stack_depth_limit")
+ def op_stack_current(self):
+ return 0
+
# operations on pyobjects!
for opname in lloperation.opimpls.keys():
exec py.code.Source("""
--- a/pypy/translator/benchmark/autopath.py
+++ /dev/null
@@ -1,134 +0,0 @@
-"""
-self cloning, automatic path configuration
-
-copy this into any subdirectory of pypy from which scripts need
-to be run, typically all of the test subdirs.
-The idea is that any such script simply issues
-
- import autopath
-
-and this will make sure that the parent directory containing "pypy"
-is in sys.path.
-
-If you modify the master "autopath.py" version (in pypy/tool/autopath.py)
-you can directly run it which will copy itself on all autopath.py files
-it finds under the pypy root directory.
-
-This module always provides these attributes:
-
- pypydir pypy root directory path
- this_dir directory where this autopath.py resides
-
-"""
-
-def __dirinfo(part):
- """ return (partdir, this_dir) and insert parent of partdir
- into sys.path. If the parent directories don't have the part
- an EnvironmentError is raised."""
-
- import sys, os
- try:
- head = this_dir = os.path.realpath(os.path.dirname(__file__))
- except NameError:
- head = this_dir = os.path.realpath(os.path.dirname(sys.argv[0]))
-
- error = None
- while head:
- partdir = head
- head, tail = os.path.split(head)
- if tail == part:
- checkfile = os.path.join(partdir, os.pardir, 'pypy', '__init__.py')
- if not os.path.exists(checkfile):
- error = "Cannot find %r" % (os.path.normpath(checkfile),)
- break
- else:
- error = "Cannot find the parent directory %r of the path %r" % (
- partdir, this_dir)
- if not error:
- # check for bogus end-of-line style (e.g. files checked out on
- # Windows and moved to Unix)
- f = open(__file__.replace('.pyc', '.py'), 'r')
- data = f.read()
- f.close()
- if data.endswith('\r\n') or data.endswith('\r'):
- error = ("Bad end-of-line style in the .py files. Typically "
- "caused by a zip file or a checkout done on Windows and "
- "moved to Unix or vice-versa.")
- if error:
- raise EnvironmentError("Invalid source tree - bogus checkout! " +
- error)
-
- pypy_root = os.path.join(head, '')
- try:
- sys.path.remove(head)
- except ValueError:
- pass
- sys.path.insert(0, head)
-
- munged = {}
- for name, mod in sys.modules.items():
- if '.' in name:
- continue
- fn = getattr(mod, '__file__', None)
- if not isinstance(fn, str):
- continue
- newname = os.path.splitext(os.path.basename(fn))[0]
- if not newname.startswith(part + '.'):
- continue
- path = os.path.join(os.path.dirname(os.path.realpath(fn)), '')
- if path.startswith(pypy_root) and newname != part:
- modpaths = os.path.normpath(path[len(pypy_root):]).split(os.sep)
- if newname != '__init__':
- modpaths.append(newname)
- modpath = '.'.join(modpaths)
- if modpath not in sys.modules:
- munged[modpath] = mod
-
- for name, mod in munged.iteritems():
- if name not in sys.modules:
- sys.modules[name] = mod
- if '.' in name:
- prename = name[:name.rfind('.')]
- postname = name[len(prename)+1:]
- if prename not in sys.modules:
- __import__(prename)
- if not hasattr(sys.modules[prename], postname):
- setattr(sys.modules[prename], postname, mod)
-
- return partdir, this_dir
-
-def __clone():
- """ clone master version of autopath.py into all subdirs """
- from os.path import join, walk
- if not this_dir.endswith(join('pypy','tool')):
- raise EnvironmentError("can only clone master version "
- "'%s'" % join(pypydir, 'tool',_myname))
-
-
- def sync_walker(arg, dirname, fnames):
- if _myname in fnames:
- fn = join(dirname, _myname)
- f = open(fn, 'rwb+')
- try:
- if f.read() == arg:
- print "checkok", fn
- else:
- print "syncing", fn
- f = open(fn, 'w')
- f.write(arg)
- finally:
- f.close()
- s = open(join(pypydir, 'tool', _myname), 'rb').read()
- walk(pypydir, sync_walker, s)
-
-_myname = 'autopath.py'
-
-# set guaranteed attributes
-
-pypydir, this_dir = __dirinfo('pypy')
-import py # note: py is imported only AFTER the path has been set
-libpythondir = str(py.path.local(pypydir).dirpath().join('lib-python', '2.5.2'))
-libpythonmodifieddir = str(py.path.local(libpythondir).dirpath().join('modified-2.5.2'))
-
-if __name__ == '__main__':
- __clone()
--- a/pypy/translator/benchmark/bench-custom.py
+++ /dev/null
@@ -1,127 +0,0 @@
-# benchmarks on a unix machine.
-
-import autopath
-from pypy.translator.benchmark.result import BenchmarkResultSet
-from pypy.translator.benchmark.benchmarks import BENCHMARKS
-import os, sys, time, pickle, re, py
-
-SPLIT_TABLE = True # useful when executable names are very long
-
-def get_executables(args): #sorted by revision number (highest first)
- exes = sorted(args, key=os.path.getmtime)
- r = []
- for exe in exes:
- if '/' not in exe:
- r.append('./' + exe)
- else:
- r.append(exe)
- return r
-
-def main(options, args):
- if os.path.exists(options.picklefile):
- benchmark_result = pickle.load(open(options.picklefile, 'rb'))
- else:
- benchmark_result = BenchmarkResultSet()
-
- benchmarks = []
- for b in BENCHMARKS:
- if b.name in options.benchmarks:
- if not b.check():
- print "can't run %s benchmark for some reason"%(b.name,)
- else:
- if int(options.sizefactor) > 1:
- b = b * int(options.sizefactor)
- benchmarks.append(b)
-
- exes = get_executables(args)
- pythons = 'python2.6 python2.5 python2.4'.split()
- full_pythons = []
- for python in pythons:
- full_python = py.path.local.sysfind(python)
- if full_python:
- full_pythons.append(str(full_python))
-
- sys.stdout.flush()
-
- refs = {}
- final_error_count = 0
-
- if not options.nocpython:
- exes = full_pythons + exes
-
- for i in range(int(options.runcount)) or [None]:
- if i is not None:
- for exe in exes:
- for b in benchmarks:
- br = benchmark_result.result(exe, allowcreate=True)
- result = br.run_benchmark(b, verbose=options.verbose)
- if not result:
- final_error_count += 1
-
- if options.relto:
- relto = options.relto
- else:
- relto = full_pythons[0]
- if relto not in benchmark_result.benchmarks:
- continue
-
- pickle.dump(benchmark_result, open(options.picklefile, 'wb'))
-
- exe_stats = ['stat:st_mtime', 'exe_name', 'pypy_rev']
- if not SPLIT_TABLE:
- stats = exe_stats[:]
- else:
- stats = ['exe']
- for b in benchmarks:
- stats.append('bench:'+b.name)
- kwds = {'relto': relto,
- 'filteron' :lambda r: r.exe_name in exes,
- }
- for row in benchmark_result.txt_summary(stats, **kwds):
- print row
- if SPLIT_TABLE:
- print
- print 'Reference:'
- for row in benchmark_result.txt_summary(['exe'] + exe_stats,
- **kwds):
- print row
- print
-
- if final_error_count:
- raise SystemExit("%d benchmark run(s) failed (see -FAILED- above)"
- % final_error_count)
-
-if __name__ == '__main__':
- from optparse import OptionParser
- parser = OptionParser()
- default_benches = ','.join([b.name for b in BENCHMARKS if b.check()])
- parser.add_option(
- '--benchmarks', dest='benchmarks',
- default=default_benches,
- )
- parser.add_option(
- '--pickle', dest='picklefile',
- default='bench-custom.benchmark_result'
- )
- parser.add_option(
- '--runcount', dest='runcount',
- default='1',
- )
- parser.add_option(
- '--relto', dest='relto',
- default=None,
- )
- parser.add_option(
- '-v', '--verbose', action='store_true', dest='verbose',
- default=None,
- )
- parser.add_option(
- '--no-cpython', action='store_true', dest='nocpython',
- default=None,
- )
- parser.add_option(
- '--size-factor', dest='sizefactor',
- default='1',
- )
- options, args = parser.parse_args(sys.argv[1:])
- main(options, args)
--- a/pypy/module/sys/__init__.py
+++ b/pypy/module/sys/__init__.py
@@ -64,7 +64,7 @@ class Module(MixedModule):
'pypy_version_info' : 'version.get_pypy_version_info(space)',
'pypy_svn_url' : 'version.get_svn_url(space)',
'subversion' : 'version.get_subversion_info(space)',
- '_mercurial' : 'version.get_mercurial_info(space)',
+ '_mercurial' : 'version.wrap_mercurial_info(space)',
'hexversion' : 'version.get_hexversion(space)',
'displayhook' : 'hook.displayhook',
--- a/pypy/module/cpyext/test/conftest.py
+++ /dev/null
@@ -1,16 +0,0 @@
-import py
-from pypy.conftest import option, gettestobjspace
-
-def pytest_collect_directory(parent):
- if parent.config.option.runappdirect:
- py.test.skip("cannot be run by py.test -A")
-
- # ensure additional functions are registered
- import pypy.module.cpyext.test.test_cpyext
-
-def pytest_funcarg__space(request):
- return gettestobjspace(usemodules=['cpyext', 'thread', '_rawffi'])
-
-def pytest_funcarg__api(request):
- return request.cls.api
-
--- a/pypy/jit/backend/llvm/test/conftest.py
+++ b/pypy/jit/backend/llvm/test/conftest.py
@@ -1,4 +1,4 @@
import py
-def pytest_collect_directory():
- py.test.skip("llvm backend tests skipped for now")
+def pytest_ignore_collect(path):
+ return True
--- a/pypy/translator/goal/test2/test_app_main.py
+++ b/pypy/translator/goal/test2/test_app_main.py
@@ -43,6 +43,93 @@ crashing_demo_script = getscript("""
""")
+class TestParseCommandLine:
+
+ def check_options(self, options, sys_argv, **expected):
+ assert sys.argv == sys_argv
+ for key, value in expected.items():
+ assert options[key] == value
+ for key, value in options.items():
+ if key not in expected:
+ assert not value, (
+ "option %r has unexpectedly the value %r" % (key, value))
+
+ def check(self, argv, **expected):
+ import StringIO
+ from pypy.translator.goal import app_main
+ saved_sys_argv = sys.argv[:]
+ saved_sys_stdout = sys.stdout
+ saved_sys_stderr = sys.stdout
+ app_main.os = os
+ try:
+ sys.stdout = sys.stderr = StringIO.StringIO()
+ try:
+ options = app_main.parse_command_line(argv)
+ except SystemExit:
+ output = expected['output_contains']
+ assert output in sys.stdout.getvalue()
+ else:
+ self.check_options(options, **expected)
+ finally:
+ sys.argv[:] = saved_sys_argv
+ sys.stdout = saved_sys_stdout
+ sys.stderr = saved_sys_stderr
+
+ def test_all_combinations_I_can_think_of(self):
+ self.check([], sys_argv=[''], run_stdin=True)
+ self.check(['-'], sys_argv=['-'], run_stdin=True)
+ self.check(['-S'], sys_argv=[''], run_stdin=True, no_site=1)
+ self.check(['-OO'], sys_argv=[''], run_stdin=True, optimize=2)
+ self.check(['-O', '-O'], sys_argv=[''], run_stdin=True, optimize=2)
+ self.check(['-Qnew'], sys_argv=[''], run_stdin=True, division_new=1)
+ self.check(['-Qold'], sys_argv=[''], run_stdin=True, division_new=0)
+ self.check(['-Qwarn'], sys_argv=[''], run_stdin=True, division_warning=1)
+ self.check(['-Qwarnall'], sys_argv=[''], run_stdin=True,
+ division_warning=2)
+ self.check(['-Q', 'new'], sys_argv=[''], run_stdin=True, division_new=1)
+ self.check(['-SOQnew'], sys_argv=[''], run_stdin=True,
+ no_site=1, optimize=1, division_new=1)
+ self.check(['-SOQ', 'new'], sys_argv=[''], run_stdin=True,
+ no_site=1, optimize=1, division_new=1)
+ self.check(['-i'], sys_argv=[''], run_stdin=True,
+ interactive=1, inspect=1)
+ self.check(['-h'], output_contains='usage:')
+ self.check(['-S', '-tO', '-h'], output_contains='usage:')
+ self.check(['-S', '-thO'], output_contains='usage:')
+ self.check(['-S', '-tO', '--help'], output_contains='usage:')
+ self.check(['-S', '-tO', '--info'], output_contains='translation')
+ self.check(['-S', '-tO', '--version'], output_contains='Python')
+ self.check(['-S', '-tOV'], output_contains='Python')
+ self.check(['--jit', 'foobar', '-S'], sys_argv=[''],
+ run_stdin=True, no_site=1)
+ self.check(['-c', 'pass'], sys_argv=['-c'], run_command='pass')
+ self.check(['-cpass'], sys_argv=['-c'], run_command='pass')
+ self.check(['-cpass','x'], sys_argv=['-c','x'], run_command='pass')
+ self.check(['-Sc', 'pass'], sys_argv=['-c'], run_command='pass',
+ no_site=1)
+ self.check(['-Scpass'], sys_argv=['-c'], run_command='pass', no_site=1)
+ self.check(['-c', '', ''], sys_argv=['-c', ''], run_command='')
+ self.check(['-mfoo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+ run_module=True)
+ self.check(['-m', 'foo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+ run_module=True)
+ self.check(['-Smfoo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+ run_module=True, no_site=1)
+ self.check(['-Sm', 'foo', 'bar', 'baz'], sys_argv=['foo', 'bar', 'baz'],
+ run_module=True, no_site=1)
+ self.check(['-', 'foo', 'bar'], sys_argv=['-', 'foo', 'bar'],
+ run_stdin=True)
+ self.check(['foo', 'bar'], sys_argv=['foo', 'bar'])
+ self.check(['foo', '-i'], sys_argv=['foo', '-i'])
+ self.check(['-i', 'foo'], sys_argv=['foo'], interactive=1, inspect=1)
+ self.check(['--', 'foo'], sys_argv=['foo'])
+ self.check(['--', '-i', 'foo'], sys_argv=['-i', 'foo'])
+ self.check(['--', '-', 'foo'], sys_argv=['-', 'foo'], run_stdin=True)
+ self.check(['-Wbog'], sys_argv=[''], warnoptions=['bog'], run_stdin=True)
+ self.check(['-W', 'ab', '-SWc'], sys_argv=[''], warnoptions=['ab', 'c'],
+ run_stdin=True, no_site=1)
+
+
class TestInteraction:
"""
These tests require pexpect (UNIX-only).
@@ -446,7 +533,7 @@ class TestNonInteractive:
def test_option_W_crashing(self):
data = self.run('-W')
- assert 'Argument expected for the -W option' in data
+ assert "Argument expected for the '-W' option" in data
def test_option_W_arg_ignored(self):
data = self.run('-Wc')
--- a/pypy/rlib/rsdl/test/conftest.py
+++ b/pypy/rlib/rsdl/test/conftest.py
@@ -1,8 +1,10 @@
from pypy.rlib.rsdl.eci import check_sdl_installation, SDLNotInstalled
import py
-def pytest_collect_directory():
+def pytest_ignore_collect(path):
try:
check_sdl_installation()
except SDLNotInstalled, e:
- py.test.skip("SDL not installed(?): %s" % (e,))
+ return True
+ else:
+ return False
--- a/pypy/translator/benchmark/jitbench.py
+++ /dev/null
@@ -1,30 +0,0 @@
-import sys, os
-from optparse import OptionParser
-
-parser = OptionParser()
-parser.add_option(
- '--size-factor-list', dest='sizefactorlist',
- default='1,2,5,20,1,2,5,20,1,2,5,20',
- )
-options, args = parser.parse_args(sys.argv[1:])
-args = args or [sys.executable]
-executables = [os.path.abspath(executable) for executable in args]
-sizefactors = [int(s) for s in options.sizefactorlist.split(',')]
-
-os.chdir(os.path.dirname(sys.argv[0]) or '.')
-
-errors = []
-
-for sizefactor in sizefactors:
- for executable in executables:
- sys.argv[1:] = [executable, '--pickle=jitbench.benchmark_result',
- '-v', '--no-cpython',
- '--size-factor=%d' % sizefactor]
- try:
- execfile('bench-custom.py')
- except SystemExit, e:
- errors.append('%s:*%s: %s' % (executable, sizefactor, e))
-
-if errors:
- print '\n'.join(errors)
- sys.exit(1)
--- a/pypy/translator/benchmark/__init__.py
+++ /dev/null
@@ -1,1 +0,0 @@
-#
--- a/pypy/interpreter/baseobjspace.py
+++ b/pypy/interpreter/baseobjspace.py
@@ -800,8 +800,8 @@ class ObjSpace(object):
def call_obj_args(self, w_callable, w_obj, args):
if not self.config.objspace.disable_call_speedhacks:
- # XXX start of hack for performance
- from pypy.interpreter.function import Function
+ # XXX start of hack for performance
+ from pypy.interpreter.function import Function
if isinstance(w_callable, Function):
return w_callable.call_obj_args(w_obj, args)
# XXX end of hack for performance
@@ -1183,24 +1183,27 @@ class ObjSpace(object):
return value
def c_filedescriptor_w(self, w_fd):
- try:
- fd = self.c_int_w(w_fd)
- except OperationError, e:
- if not e.match(self, self.w_TypeError):
- raise
+ if (not self.isinstance_w(w_fd, self.w_int) and
+ not self.isinstance_w(w_fd, self.w_long)):
try:
- w_fileno = self.getattr(w_fd, self.wrap('fileno'))
+ w_fileno = self.getattr(w_fd, self.wrap("fileno"))
except OperationError, e:
if e.match(self, self.w_AttributeError):
raise OperationError(self.w_TypeError,
- self.wrap("argument must be an int, "
- "or have a fileno() method."))
+ self.wrap("argument must be an int, or have a fileno() "
+ "method.")
+ )
raise
w_fd = self.call_function(w_fileno)
- fd = self.c_int_w(w_fd)
+ if not self.isinstance_w(w_fd, self.w_int):
+ raise OperationError(self.w_TypeError,
+ self.wrap("fileno() must return an integer")
+ )
+ fd = self.int_w(w_fd)
if fd < 0:
raise operationerrfmt(self.w_ValueError,
- "file descriptor cannot be a negative integer (%d)", fd)
+ "file descriptor cannot be a negative integer (%d)", fd
+ )
return fd
def warn(self, msg, w_warningcls):
@@ -1405,4 +1408,3 @@ ObjSpace.IrregularOpTable = [
'call_args',
'marshal_w',
]
-
--- a/pypy/translator/benchmark/benchmarks.py
+++ /dev/null
@@ -1,197 +0,0 @@
-import os, sys, time, pickle, re, py
-import yaml
-
-class BenchmarkFailed(Exception):
- pass
-
-PYSTONE_CMD = 'from test import pystone;pystone.main(%s)'
-PYSTONE_PATTERN = 'This machine benchmarks at'
-
-RICHARDS_CMD = 'from richards import *;main(iterations=%d)'
-RICHARDS_PATTERN = 'Average time per iteration:'
-
-TIME_FMT = 'max mem used: %Mk\nelapsed time: %e\nsystem time: %S\nuser time: %U\nCPU use: %P'
-
-def get_result(txt, pattern):
- for line in txt.split('\n'):
- if line.startswith(pattern):
- break
- else:
- raise BenchmarkFailed
- return float(line.split()[len(pattern.split())])
-
-class Benchmark(object):
- def __init__(self, name, runner, asc_good, units,
- check=lambda:True, sizefactor=1):
- if sizefactor > 1:
- self.name = name + '*%d' % sizefactor
- else:
- self.name = name
- self._basename = name
- self._run = runner
- self.asc_good = asc_good
- self.units = units
- self.check = check
- self.sizefactor = sizefactor
- def __mul__(self, n):
- return Benchmark(self._basename, self._run, self.asc_good, self.units,
- self.check, self.sizefactor * n)
- def run(self, exe):
- self.latest_output = ''
- try:
- result, latest_output = self._run(exe, self.sizefactor)
- self.latest_output = latest_output
- except BenchmarkFailed, e:
- result = '-FAILED-'
- return result
-
-def external_dependency(dirname, svnurl, revision=None):
- directory = py.path.local(__file__).dirpath().join(dirname)
- wc = py.path.svnwc(directory)
- wc.checkout(svnurl, rev=revision)
- return True
-
-def run_cmd(cmd):
- pipe = os.popen(cmd + ' 2>&1')
- r = pipe.read()
- status = pipe.close()
- if status:
- raise BenchmarkFailed(status)
- return r
-
-def run_pystone(executable, sizefactor=1):
- from pypy.tool import autopath
- distdir = py.path.local(autopath.pypydir).dirpath()
- pystone = py.path.local(autopath.libpythondir).join('test', 'pystone.py')
- txt = run_cmd('"%s" "%s" %d' % (executable, pystone, 50000 * sizefactor))
- return get_result(txt, PYSTONE_PATTERN), txt
-
-def run_richards(executable, sizefactor=1):
- richards = py.path.local(__file__).dirpath().dirpath().join('goal').join('richards.py')
- txt = run_cmd('"%s" %s %d' % (executable, richards, 5 * sizefactor))
- return get_result(txt, RICHARDS_PATTERN), txt
-
-def run_translate(executable):
- translate = py.path.local(__file__).dirpath().dirpath().join('goal').join('translate.py')
- target = py.path.local(__file__).dirpath().dirpath().join('goal').join('targetrpystonedalone.py')
- argstr = '%s %s --batch --backendopt --no-compile %s > /dev/null 2> /dev/null'
- T = time.time()
- status = os.system(argstr%(executable, translate, target))
- r = time.time() - T
- if status:
- raise BenchmarkFailed(status)
- return r
-
-def run_templess(executable, sizefactor=1):
- """ run some script in the templess package
-
- templess is some simple templating language.
- We have a copy at
- 'http://codespeak.net/svn/user/arigo/hack/pypy-hack/templess'
- """
- here = py.path.local(__file__).dirpath()
- pypath = os.path.dirname(os.path.dirname(py.__file__))
- templessdir = here.join('templess')
- testscript = templessdir.join('test/oneshot.py')
- command = 'PYTHONPATH="%s:%s" "%s" "%s" %d' % (here, pypath,
- executable, testscript,
- 100 * sizefactor)
- txt = run_cmd(command)
- for line in txt.split('\n'):
- if '.' in line:
- try:
- return float(line) / sizefactor, txt
- except ValueError:
- pass
- else:
- raise BenchmarkFailed
-
-def check_templess():
- return external_dependency('templess',
- 'http://codespeak.net/svn/user/arigo/hack/pypy-hack/templess')
-
-def run_gadfly(executable, sizefactor=1):
- """ run some tests in the gadfly pure Python database """
- here = py.path.local(__file__).dirpath()
- gadfly = here.join('gadfly')
- testscript = gadfly.join('test', 'testsubset.py')
- command = 'PYTHONPATH="%s" "%s" "%s" %d' % (gadfly, executable, testscript,
- sizefactor)
- txt = run_cmd(command)
- return get_result(txt, 'Total running time:') / sizefactor, txt
-
-def check_gadfly():
- return external_dependency('gadfly',
- 'http://codespeak.net/svn/user/arigo/hack/pypy-hack/gadflyZip',
- 70117)
-
-def run_mako(executable, sizefactor=1):
- """ run some tests in the mako templating system """
- here = py.path.local(__file__).dirpath()
- mako = here.join('mako')
- testscript = mako.join('examples', 'bench', 'basic.py')
- command = 'PYTHONPATH="%s" "%s" "%s" -n%d mako' % (mako.join('lib'),
- executable, testscript,
- 2000 * sizefactor)
- txt = run_cmd(command)
- return get_result(txt, 'Mako:'), txt
-
-def check_mako():
- return external_dependency('mako',
- 'http://codespeak.net/svn/user/arigo/hack/pypy-hack/mako',
- 70118)
-
-def check_translate():
- return False # XXX what should we do about the dependency on ctypes?
-
-class LanguageShootoutBenchmark(Benchmark):
- def __init__(self, name, sizefactor=1, test=False):
- self.test = test
- self.basename = name
- Benchmark.__init__(self, name, self.runner, False, 'ms',
- self.check, sizefactor)
-
- def __mul__(self, i):
- return LanguageShootoutBenchmark(self.name, self.sizefactor * i,
- self.test)
-
- def runner(self, executable, sizefactor=1):
- shootout = py.path.local(__file__).dirpath().join(
- 'shootout_benchmarks')
- argsfile = shootout.join('tests.yml')
- if self.test:
- kind = 'test'
- else:
- kind = 'run'
- args = yaml.load(argsfile.read())[self.basename][kind]['args']
- progname = str(shootout.join(self.basename)) + '.py'
- cmd = 'time -f "%s" %s %s %s %d' % (TIME_FMT, executable, progname,
- " ".join(args), sizefactor)
- txt = run_cmd(cmd)
- return get_result(txt, 'elapsed time:'), txt
-
- def check(self):
- return external_dependency('shootout_benchmarks',
- 'http://codespeak.net/svn/pypy/benchmarks/shootout')
-
-BENCHMARKS = [Benchmark('richards', run_richards, False, 'ms'),
- Benchmark('pystone', run_pystone, True, ''),
- Benchmark('translate', run_translate, False, 'ms',
- check_translate),
- Benchmark('templess', run_templess, False,
- 's', check_templess),
- Benchmark('gadfly2', run_gadfly, False,
- 's', check_gadfly),
- Benchmark('mako', run_mako, False,
- 's', check_mako),
- ]
-
-SHOOTOUT_NAMES = ['binary-trees', 'fannkuch', 'fasta', 'float',
- 'meteor-contest', 'nbody', 'spectral-norm']
-
-#for name in SHOOTOUT_NAMES:
-# BENCHMARKS.append(LanguageShootoutBenchmark(name))
-
-BENCHMARKS_BY_NAME = {}
-for _b in BENCHMARKS:
- BENCHMARKS_BY_NAME[_b.name] = _b
--- a/pypy/module/sys/version.py
+++ b/pypy/module/sys/version.py
@@ -45,6 +45,7 @@ def rev2int(rev):
import pypy
pypydir = os.path.dirname(os.path.abspath(pypy.__file__))
del pypy
+from pypy.tool.version import get_mercurial_info
import time as t
gmtime = t.gmtime()
@@ -98,39 +99,18 @@ def get_subversion_info(space):
space.wrap(svnbranch),
space.wrap(str(svn_revision()))])
-def get_mercurial_info(space):
- '''Obtain Mercurial version information by invoking the 'hg' command.'''
- # TODO: support extracting from .hg_archival.txt
- import py
- from subprocess import Popen, PIPE
- pypyroot = os.path.abspath(os.path.join(pypydir, '..'))
- hgexe = py.path.local.sysfind('hg')
-
- if hgexe and os.path.isdir(os.path.join(pypyroot, '.hg')):
- env = dict(os.environ)
- # get Mercurial into scripting mode
- env['HGPLAIN'] = '1'
- # disable user configuration, extensions, etc.
- env['HGRCPATH'] = os.devnull
-
- p = Popen([str(hgexe), 'id', '-i', pypyroot], stdout=PIPE, env=env)
- hgid = p.stdout.read().strip()
-
- p = Popen([str(hgexe), 'id', '-t', pypyroot], stdout=PIPE, env=env)
- hgtag = p.stdout.read().strip().split()[0]
-
- if hgtag == 'tip':
- # use the branch instead
- p = Popen([str(hgexe), 'id', '-b', pypyroot], stdout=PIPE, env=env)
- hgtag = p.stdout.read().strip()
-
- return space.newtuple([space.wrap('PyPy'),
+def wrap_mercurial_info(space):
+ info = get_mercurial_info()
+ if info:
+ project, hgtag, hgid = info
+ return space.newtuple([space.wrap(project),
space.wrap(hgtag),
space.wrap(hgid)])
else:
return space.w_None
+
def tuple2hex(ver):
d = {'alpha': 0xA,
'beta': 0xB,
--- a/pypy/module/sys/test/test_sysmodule.py
+++ b/pypy/module/sys/test/test_sysmodule.py
@@ -484,6 +484,15 @@ class AppTestSysModulePortedFromCPython:
assert svnbranch == svnbranch.strip('/')
assert revision.isdigit()
+ def test__mercurial(self):
+ info = sys._mercurial
+ print info
+ if info:
+ project, hgtag, hgid = info
+ assert project == 'PyPy'
+ assert hgtag # no clue how to check something more :-/
+ assert hgid
+
def test_trace_exec_execfile(self):
found = []
def do_tracing(f, *args):
--- a/pypy/jit/backend/x86/assembler.py
+++ b/pypy/jit/backend/x86/assembler.py
@@ -84,7 +84,7 @@ class Assembler386(object):
self.fail_boxes_count = 0
self._current_depths_cache = (0, 0)
self.datablockwrapper = None
- self.stack_check_slowpath_imm = imm0
+ self.stack_check_slowpath = 0
self.teardown()
def leave_jitted_hook(self):
@@ -196,10 +196,12 @@ class Assembler386(object):
rawstart = mc.materialize(self.cpu.asmmemmgr, [])
self.malloc_fixedsize_slowpath2 = rawstart
- _STACK_CHECK_SLOWPATH = lltype.Ptr(lltype.FuncType([lltype.Signed],
- lltype.Void))
def _build_stack_check_slowpath(self):
from pypy.rlib import rstack
+ _, _, slowpathaddr = self.cpu.insert_stack_check()
+ if slowpathaddr == 0 or self.cpu.exit_frame_with_exception_v < 0:
+ return # no stack check (for tests, or non-translated)
+ #
mc = codebuf.MachineCodeBlockWrapper()
mc.PUSH_r(ebp.value)
mc.MOV_rr(ebp.value, esp.value)
@@ -220,9 +222,7 @@ class Assembler386(object):
mc.LEA_rb(edi.value, +16)
mc.AND_ri(esp.value, -16)
#
- f = llhelper(self._STACK_CHECK_SLOWPATH, rstack.stack_check_slowpath)
- addr = rffi.cast(lltype.Signed, f)
- mc.CALL(imm(addr))
+ mc.CALL(imm(slowpathaddr))
#
mc.MOV(eax, heap(self.cpu.pos_exception()))
mc.TEST_rr(eax.value, eax.value)
@@ -257,7 +257,6 @@ class Assembler386(object):
addr = self.cpu.get_on_leave_jitted_int(save_exception=False)
mc.CALL(imm(addr))
#
- assert self.cpu.exit_frame_with_exception_v >= 0
mc.MOV_ri(eax.value, self.cpu.exit_frame_with_exception_v)
#
# footer -- note the ADD, which skips the return address of this
@@ -270,7 +269,7 @@ class Assembler386(object):
mc.RET()
#
rawstart = mc.materialize(self.cpu.asmmemmgr, [])
- self.stack_check_slowpath_imm = imm(rawstart)
+ self.stack_check_slowpath = rawstart
def assemble_loop(self, inputargs, operations, looptoken, log):
'''adds the following attributes to looptoken:
@@ -547,16 +546,16 @@ class Assembler386(object):
self.mc.PUSH_r(regloc.value)
def _call_header_with_stack_check(self):
- startaddr, length, slowpathaddr = self.cpu.insert_stack_check()
- if slowpathaddr == 0:
+ if self.stack_check_slowpath == 0:
pass # no stack check (e.g. not translated)
else:
+ startaddr, length, _ = self.cpu.insert_stack_check()
self.mc.MOV(eax, esp) # MOV eax, current
self.mc.SUB(eax, heap(startaddr)) # SUB eax, [startaddr]
self.mc.CMP(eax, imm(length)) # CMP eax, length
self.mc.J_il8(rx86.Conditions['B'], 0) # JB .skip
jb_location = self.mc.get_relative_pos()
- self.mc.CALL(self.stack_check_slowpath_imm) # CALL slowpath
+ self.mc.CALL(imm(self.stack_check_slowpath))# CALL slowpath
# patch the JB above # .skip:
offset = self.mc.get_relative_pos() - jb_location
assert 0 < offset <= 127
--- a/pypy/translator/goal/app_main.py
+++ b/pypy/translator/goal/app_main.py
@@ -115,7 +115,7 @@ def display_exception():
# ____________________________________________________________
# Option parsing
-def print_info():
+def print_info(*args):
try:
options = sys.pypy_translation_info
except AttributeError:
@@ -125,15 +125,17 @@ def print_info():
optitems.sort()
for name, value in optitems:
print ' %51s: %s' % (name, value)
+ raise SystemExit
-def print_help():
+def print_help(*args):
print 'usage: %s [options]' % (sys.executable,)
print __doc__.rstrip()
if 'pypyjit' in sys.builtin_module_names:
- print_jit_help()
+ _print_jit_help()
print
+ raise SystemExit
-def print_jit_help():
+def _print_jit_help():
import pypyjit
items = pypyjit.defaults.items()
items.sort()
@@ -141,6 +143,18 @@ def print_jit_help():
print ' --jit %s=N %slow-level JIT parameter (default %s)' % (
key, ' '*(18-len(key)), value)
+def print_version(*args):
+ print "Python", sys.version
+ raise SystemExit
+
+def set_jit_option(options, jitparam, *args):
+ if 'pypyjit' not in sys.builtin_module_names:
+ print >> sys.stderr, ("Warning: No jit support in %s" %
+ (sys.executable,))
+ else:
+ import pypyjit
+ pypyjit.set_param(jitparam)
+
class CommandLineError(Exception):
pass
@@ -176,18 +190,6 @@ if 'nt' in sys.builtin_module_names:
else:
IS_WINDOWS = False
-def get_argument(option, argv, i):
- arg = argv[i]
- n = len(option)
- if len(arg) > n:
- return arg[n:], i
- else:
- i += 1
- if i >= len(argv):
- raise CommandLineError('Argument expected for the %s option' %
- option)
- return argv[i], i
-
def get_library_path(executable):
search = executable
while 1:
@@ -205,10 +207,7 @@ def get_library_path(executable):
break # found!
return newpath
-def setup_initial_paths(executable, nanos, ignore_environment=False, **extra):
- # a substituted os if we are translated
- global os
- os = nanos
+def setup_initial_paths(executable, ignore_environment=False, **extra):
# find the full path to the executable, assuming that if there is no '/'
# in the provided one then we must look along the $PATH
if we_are_translated() and IS_WINDOWS and not executable.lower().endswith('.exe'):
@@ -264,114 +263,144 @@ default_options = dict.fromkeys(
"run_module",
"run_stdin",
"warnoptions",
- "unbuffered"), False)
+ "unbuffered"), 0)
+
+
+PYTHON26 = True
+
+def simple_option(options, name, iterargv):
+ options[name] += 1
+
+def div_option(options, div, iterargv):
+ if div == "warn":
+ options["division_warning"] = 1
+ elif div == "warnall":
+ options["division_warning"] = 2
+ elif div == "new":
+ options["division_new"] = 1
+ elif div != "old":
+ raise CommandLineError("invalid division option: %r" % (div,))
+
+def c_option(options, runcmd, iterargv):
+ options["run_command"] = runcmd
+ return ['-c'] + list(iterargv)
+
+def m_option(options, runmodule, iterargv):
+ options["run_module"] = True
+ return [runmodule] + list(iterargv)
+
+def W_option(options, warnoption, iterargv):
+ options["warnoptions"].append(warnoption)
+
+def end_options(options, _, iterargv):
+ return list(iterargv)
+
+cmdline_options = {
+ # simple options just increment the counter of the options listed above
+ 'd': (simple_option, 'debug'),
+ 'i': (simple_option, 'interactive'),
+ 'O': (simple_option, 'optimize'),
+ 'S': (simple_option, 'no_site'),
+ 'E': (simple_option, 'ignore_environment'),
+ 't': (simple_option, 'tabcheck'),
+ 'v': (simple_option, 'verbose'),
+ 'U': (simple_option, 'unicode'),
+ 'u': (simple_option, 'unbuffered'),
+ # more complex options
+ 'Q': (div_option, Ellipsis),
+ 'c': (c_option, Ellipsis),
+ 'm': (m_option, Ellipsis),
+ 'W': (W_option, Ellipsis),
+ 'V': (print_version, None),
+ '--version': (print_version, None),
+ '--info': (print_info, None),
+ 'h': (print_help, None),
+ '--help': (print_help, None),
+ '--jit': (set_jit_option, Ellipsis),
+ '--': (end_options, None),
+ }
+
+if PYTHON26:
+ cmdline_options.update({
+ '3': (simple_option, 'py3k_warning'),
+ 'B': (simple_option, 'dont_write_bytecode'),
+ 's': (simple_option, 'no_user_site'),
+ 'b': (simple_option, 'bytes_warning'),
+ })
+
+
+def handle_argument(c, options, iterargv, iterarg=iter(())):
+ function, funcarg = cmdline_options[c]
+ #
+ # If needed, fill in the real argument by taking it from the command line
+ if funcarg is Ellipsis:
+ remaining = list(iterarg)
+ if remaining:
+ funcarg = ''.join(remaining)
+ else:
+ try:
+ funcarg = iterargv.next()
+ except StopIteration:
+ if len(c) == 1:
+ c = '-' + c
+ raise CommandLineError('Argument expected for the %r option' % c)
+ #
+ return function(options, funcarg, iterargv)
def parse_command_line(argv):
options = default_options.copy()
options['warnoptions'] = []
- print_sys_flags = False
- i = 0
- while i < len(argv):
- arg = argv[i]
- if not arg.startswith('-'):
- break
- if arg == '-i':
- options["inspect"] = options["interactive"] = True
- elif arg == '-d':
- options["debug"] = True
- elif arg == '-3':
- options["py3k_warning"] = True
- elif arg == '-E':
- options["ignore_environment"] = True
- elif arg == '-U':
- options["unicode"] = True
- elif arg.startswith('-b'):
- options["bytes_warning"] = arg.count('b')
- elif arg.startswith('-t'):
- options["tabcheck"] = arg.count('t')
- elif arg.startswith('-v'):
- options["verbose"] += arg.count('v')
- elif arg.startswith('-Q'):
- div, i = get_argument("-Q", argv, i)
- if div == "warn":
- options["division_warning"] = 1
- elif div == "warnall":
- options["division_warning"] = 2
- elif div == "new":
- options["division_new"] = True
- elif div != "old":
- raise CommandLineError("invalid division option: %r" % (div,))
- elif arg.startswith('-O'):
- options["optimize"] = arg.count('O')
- elif arg == '-B':
- options["dont_write_bytecode"] = True
- elif arg.startswith('-c'):
- options["cmd"], i = get_argument('-c', argv, i)
- argv[i] = '-c'
- options["run_command"] = True
- break
- elif arg == '-u':
- options["unbuffered"] = True
- elif arg == '-O' or arg == '-OO':
- pass
- elif arg == '--version' or arg == '-V':
- print "Python", sys.version
- return
- elif arg == '--info':
- print_info()
- return
- elif arg == '-h' or arg == '--help':
- print_help()
- return
- elif arg == '-s':
- options["no_user_site"] = True
- elif arg == '-S':
- options["no_site"] = True
- elif arg == '-':
- options["run_stdin"] = True
- break # not an option but a file name representing stdin
- elif arg.startswith('-m'):
- module, i = get_argument('-m', argv, i)
- argv[i] = module
- options["run_module"] = True
- break
- elif arg.startswith('-W'):
- warnoption, i = get_argument('-W', argv, i)
- options["warnoptions"].append(warnoption)
- elif arg.startswith('--jit'):
- jitparam, i = get_argument('--jit', argv, i)
- if 'pypyjit' not in sys.builtin_module_names:
- print >> sys.stderr, ("Warning: No jit support in %s" %
- (sys.executable,))
- else:
- import pypyjit
- pypyjit.set_param(jitparam)
- elif arg == '--':
- i += 1
- break # terminates option list
- # for testing
- elif not we_are_translated() and arg == "--print-sys-flags":
- print_sys_flags = True
+ #
+ iterargv = iter(argv)
+ argv = None
+ for arg in iterargv:
+ #
+ # If the next argument isn't at least two characters long or
+ # doesn't start with '-', stop processing
+ if len(arg) < 2 or arg[0] != '-':
+ if IS_WINDOWS and arg == '/?': # special case
+ print_help()
+ argv = [arg] + list(iterargv) # finishes processing
+ #
+ # If the next argument is directly in cmdline_options, handle
+ # it as a single argument
+ elif arg in cmdline_options:
+ argv = handle_argument(arg, options, iterargv)
+ #
+ # Else interpret the rest of the argument character by character
else:
- raise CommandLineError('unrecognized option %r' % (arg,))
- i += 1
- sys.argv[:] = argv[i:] # don't change the list that sys.argv is bound to
- if not sys.argv: # (relevant in case of "reload(sys)")
- sys.argv.append('')
+ iterarg = iter(arg)
+ iterarg.next() # skip the '-'
+ for c in iterarg:
+ if c not in cmdline_options:
+ raise CommandLineError('Unknown option: -%s' % (c,))
+ argv = handle_argument(c, options, iterargv, iterarg)
+
+ if not argv:
+ argv = ['']
options["run_stdin"] = True
- if not options["ignore_environment"] and os.getenv('PYTHONINSPECT'):
+ elif argv[0] == '-':
+ options["run_stdin"] = True
+
+ # don't change the list that sys.argv is bound to
+ # (relevant in case of "reload(sys)")
+ sys.argv[:] = argv
+
+ if (options["interactive"] or
+ (not options["ignore_environment"] and os.getenv('PYTHONINSPECT'))):
options["inspect"] = True
- if print_sys_flags:
- flag_opts = ["%s=%s" % (opt, int(value))
- for opt, value in options.iteritems()
- if isinstance(value, int)]
- "(%s)" % (", ".join(flag_opts),)
- print flag_opts
- if we_are_translated():
+
+ if PYTHON26 and we_are_translated():
flags = [options[flag] for flag in sys_flags]
sys.flags = type(sys.flags)(flags)
sys.py3kwarning = sys.flags.py3k_warning
+
+## if not we_are_translated():
+## for key in sorted(options):
+## print '%40s: %s' % (key, options[key])
+## print '%40s: %s' % ("sys.argv", sys.argv)
+
return options
def run_command_line(interactive,
@@ -383,7 +412,6 @@ def run_command_line(interactive,
warnoptions,
unbuffered,
ignore_environment,
- cmd=None,
**ignored):
# with PyPy in top of CPython we can only have around 100
# but we need more in the translated PyPy for the compiler package
@@ -445,13 +473,13 @@ def run_command_line(interactive,
success = True
try:
- if run_command:
+ if run_command != 0:
# handle the "-c" command
# Put '' on sys.path
sys.path.insert(0, '')
def run_it():
- exec cmd in mainmodule.__dict__
+ exec run_command in mainmodule.__dict__
success = run_toplevel(run_it)
elif run_module:
# handle the "-m" command
@@ -547,14 +575,15 @@ def print_banner():
'"license" for more information.')
def entry_point(executable, argv, nanos):
+ # a substituted os if we are translated
+ global os
+ os = nanos
try:
cmdline = parse_command_line(argv)
except CommandLineError, e:
print_error(str(e))
return 2
- if cmdline is None:
- return 0
- setup_initial_paths(executable, nanos, **cmdline)
+ setup_initial_paths(executable, **cmdline)
return run_command_line(**cmdline)
--- a/pypy/translator/benchmark/result.py
+++ /dev/null
@@ -1,188 +0,0 @@
-import os, pickle, sys, time, re
-
-STAT2TITLE = {
- 'stat:st_mtime': "date",
- 'exe_name': "executable",
-}
-
-def stat2title(s):
- if s.startswith('bench:'):
- return s[6:]
- else:
- return STAT2TITLE.get(s, s)
-
-
-class BenchmarkResultSet(object):
- def __init__(self, max_results=10):
- self.benchmarks = {}
- self.max_results = max_results
-
- def result(self, exe, allowcreate=False):
- if exe in self.benchmarks or not allowcreate:
- return self.benchmarks[exe]
- else:
- r = self.benchmarks[exe] = BenchmarkResult(exe, self.max_results)
- return r
-
- def txt_summary(self, stats, **kw):
- sortkey = kw.get('sortby', 'stat:st_mtime')
- lst = self.benchmarks.values()
- lst.sort(key=lambda x:x.getstat(sortkey, None), reverse=kw.get('reverse', False))
- if 'filteron' in kw:
- filteron = kw['filteron']
- lst = [r for r in lst if filteron(r)]
- relto = kw.get('relto', None)
- table = [[(stat2title(s),0) for s in stats]]
- for r in lst:
- row = []
- for stat in stats:
- if stat.startswith('bench:'):
- benchname = stat[6:]
- if r.getstat(stat, None) is None:
- row.append(('XXX',-1))
- elif relto:
- factor = self.result(relto).getstat(stat)/r.getstat(stat)
- if not r.asc_goods[benchname]:
- factor = 1/factor
- s, f = r.fmtstat(stat)
- row.append((s + ' (%6.2fx)'%factor, f))
- else:
- row.append(r.fmtstat(stat))
- else:
- row.append(r.fmtstat(stat))
- table.append(row)
- widths = [0 for thing in stats]
- for row in table:
- for i, cell in enumerate(row):
- widths[i] = max(len(cell[0]), widths[i])
- concretetable = []
- concreterow = []
- for w, cell in zip(widths, table[0]):
- concreterow.append(cell[0].center(w))
- concretetable.append(' '.join(concreterow))
- for row in table[1:]:
- concreterow = []
- for w, cell in zip(widths, row):
- concreterow.append("%*s"%(cell[1]*w, cell[0]))
- concretetable.append(' '.join(concreterow))
- return concretetable
-
-class BenchmarkResult(object):
- IDS = {}
-
- def __init__(self, exe, max_results=10):
- self.max_results = max_results
- self.exe_stat = os.stat(exe)
- self.exe_name = exe
- self.codesize = os.popen('size "%s" | tail -n1 | cut -f1'%(exe,)).read().strip()
- try:
- self.pypy_rev = int(os.popen(
- exe + ' -c "import sys; print sys.pypy_version_info[-1]" 2>/dev/null').read().strip())
- except ValueError:
- self.pypy_rev = -1
- self.best_benchmarks = {}
- self.benchmarks = {}
- self.asc_goods = {}
- self.run_counts = {}
-
- def run_benchmark(self, benchmark, verbose=False):
- self.asc_goods[benchmark.name] = benchmark.asc_good
- if self.run_counts.get(benchmark.name, 0) > self.max_results:
- return -1
- print 'running', benchmark.name, 'for', self.exe_name,
- if verbose and self.pypy_rev > 0:
- print '[rev %d]' % self.pypy_rev,
- sys.stdout.flush()
- new_result = benchmark.run(self.exe_name)
- print new_result
- if verbose:
- print '{'
- lines = benchmark.latest_output.splitlines(False)
- for line in lines[:80]:
- print '\t' + line
- if len(lines) > 80:
- print '\t....'
- print '}'
- self.run_counts[benchmark.name] = self.run_counts.get(benchmark.name, 0) + 1
- if new_result == '-FAILED-':
- return 0
- self.benchmarks.setdefault(benchmark.name, []).append(new_result)
- if benchmark.name in self.best_benchmarks:
- old_result = self.best_benchmarks[benchmark.name]
- if benchmark.asc_good:
- new_result = max(new_result, old_result)
- else:
- new_result = min(new_result, old_result)
- self.best_benchmarks[benchmark.name] = new_result
- return 1
-
- def getstat(self, *args):
- # oh for supplied-p!
- return_default = False
- if len(args) == 1:
- stat, = args
- else:
- stat, default = args
- return_default = True
- if hasattr(self, stat):
- return getattr(self, stat)
- if stat == 'exe':
- myid = len(BenchmarkResult.IDS)
- myid = BenchmarkResult.IDS.setdefault(self, myid)
- return '[%s]' % myid
- statkind, statdetail = stat.split(':')
- if statkind == 'stat':
- return getattr(self.exe_stat, statdetail)
- elif statkind == 'bench':
- if return_default:
- return self.best_benchmarks.get(statdetail, default)
- else:
- return self.best_benchmarks[statdetail]
- else:
- 1/0
-
- def fmtstat(self, *args):
- stat = args[0]
- statvalue = self.getstat(*args)
- if stat == 'stat:st_mtime':
- return time.ctime(statvalue), -1
- elif stat == 'exe_name':
- return os.path.basename(statvalue), -1
- elif stat.startswith('bench:'):
- from pypy.translator.benchmark import benchmarks
- statkind, statdetail = stat.split(':', 1)
- if '*' in statdetail:
- statdetail = statdetail.split('*')[0]
- b = benchmarks.BENCHMARKS_BY_NAME[statdetail]
- return "%8.2f%s"%(statvalue, b.units), 1
- elif stat == 'pypy_rev':
- return str(statvalue), 1
- else:
- return str(statvalue), -1
-
- def summary(self, stats):
- return [self.getstat(stat) for stat in stats]
-
- def is_stable(self, name):
- try:
- return self.n_results[name] >= self.max_results
- except:
- return False
-
-if __name__ == '__main__':
- import autopath
- from pypy.translator.benchmark import benchmarks, result
- import cPickle
- if os.path.exists('foo.pickle'):
- s = cPickle.load(open('foo.pickle', 'rb'))
- else:
- s = result.BenchmarkResultSet(4)
- for exe in sys.argv[1:]:
- r = s.result(exe)
- r.run_benchmark(benchmarks.BENCHMARKS_BY_NAME['richards'])
- r.run_benchmark(benchmarks.BENCHMARKS_BY_NAME['pystone'])
- cPickle.dump(s, open('foo.pickle', 'wb'))
- stats = ['stat:st_mtime', 'exe_name', 'bench:richards', 'bench:pystone']
-
- for row in s.txt_summary(stats, sortby="exe_name", reverse=True, relto="/usr/local/bin/python2.4"):
- print row
--- a/pypy/translator/benchmark/conftest.py
+++ /dev/null
@@ -1,4 +0,0 @@
-import py
-
-def pytest_ignore_collect(path):
- return path.basename == "test"
--- a/pypy/module/test_lib_pypy/ctypes_tests/conftest.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import py
-import sys
-
-def pytest_collect_directory():
- if '__pypy__' not in sys.builtin_module_names:
- py.test.skip("these tests are meant to be run on top of pypy-c")
-
-def compile_so_file():
- from pypy.translator.platform import platform
- from pypy.translator.tool.cbuild import ExternalCompilationInfo
- udir = py.test.ensuretemp('_ctypes_test')
- cfile = py.path.local(__file__).dirpath().join("_ctypes_test.c")
-
- if sys.platform == 'win32':
- libraries = ['oleaut32']
- else:
- libraries = []
- eci = ExternalCompilationInfo(libraries=libraries)
-
- return platform.compile([cfile], eci, str(udir.join('_ctypes_test')),
- standalone=False)
-
-def pytest_configure(config):
- global sofile
- sofile = compile_so_file()
--- /dev/null
+++ b/pypy/module/cpyext/conftest.py
@@ -0,0 +1,16 @@
+import py
+from pypy.conftest import option, gettestobjspace
+
+def pytest_collect_directory(parent):
+ if parent.config.option.runappdirect:
+ py.test.skip("cannot be run by py.test -A")
+
+ # ensure additional functions are registered
+ import pypy.module.cpyext.test.test_cpyext
+
+def pytest_funcarg__space(request):
+ return gettestobjspace(usemodules=['cpyext', 'thread', '_rawffi'])
+
+def pytest_funcarg__api(request):
+ return request.cls.api
+
More information about the Pypy-commit
mailing list