| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
import py |
| 10 |
import os |
| 11 |
import sys, textwrap, types, gc |
| 12 |
from pypy.interpreter.gateway import app2interp_temp |
| 13 |
from pypy.interpreter.error import OperationError |
| 14 |
from pypy.interpreter.function import Method |
| 15 |
from rpython.tool.runsubprocess import run_subprocess |
| 16 |
from pypy.tool.pytest import appsupport |
| 17 |
from rpython.tool.udir import udir |
| 18 |
from pypy import pypydir |
| 19 |
from inspect import getmro |
| 20 |
|
| 21 |
pypyroot = os.path.dirname(pypydir) |
| 22 |
|
| 23 |
|
| 24 |
RENAMED_USEMODULES = { |
| 25 |
'_winreg': 'winreg', |
| 26 |
'exceptions': 'builtins', |
| 27 |
'struct': '_struct', |
| 28 |
'thread': '_thread', |
| 29 |
'operator': '_operator', |
| 30 |
'signal': '_signal', |
| 31 |
'imp': '_imp'} |
| 32 |
if sys.platform == 'win32': |
| 33 |
RENAMED_USEMODULES['posix'] = 'nt' |
| 34 |
|
| 35 |
if sys.platform == 'win32': |
| 36 |
RENAMED_USEMODULES['posix'] = 'nt' |
| 37 |
|
| 38 |
class AppError(Exception): |
| 39 |
def __init__(self, excinfo): |
| 40 |
self.excinfo = excinfo |
| 41 |
|
| 42 |
class PythonInterpreter(object): |
| 43 |
def __init__(self, path): |
| 44 |
self.path = path |
| 45 |
self._is_pypy = None |
| 46 |
|
| 47 |
@property |
| 48 |
def is_pypy(self): |
| 49 |
if self._is_pypy is not None: |
| 50 |
return self._is_pypy |
| 51 |
CODE = "import sys; print('__pypy__' in sys.builtin_module_names)" |
| 52 |
res, stdout, stderr = run_subprocess( self.path, ["-c", CODE]) |
| 53 |
if res != 0: |
| 54 |
raise ValueError("Invalid Python interpreter") |
| 55 |
print stdout |
| 56 |
is_pypy = stdout.strip() == 'True' |
| 57 |
self._is_pypy = is_pypy |
| 58 |
return is_pypy |
| 59 |
|
| 60 |
|
| 61 |
def py3k_repr(value): |
| 62 |
"return the repr() that py3k would give for an object.""" |
| 63 |
if isinstance(value, str): |
| 64 |
|
| 65 |
return "b" + repr(value) |
| 66 |
elif isinstance(value, unicode): |
| 67 |
|
| 68 |
return repr(value)[1:] |
| 69 |
elif isinstance(value, list): |
| 70 |
return '[' + ', '.join(py3k_repr(item) for item in value) + ']' |
| 71 |
elif isinstance(value, tuple): |
| 72 |
return '(' + ', '.join(py3k_repr(item) for item in value) + ',)' |
| 73 |
elif isinstance(value, dict): |
| 74 |
return '{' + ', '.join('%s: %s' % (py3k_repr(key), py3k_repr(value)) |
| 75 |
for key, value in value.items()) + '}' |
| 76 |
elif isinstance(value, long): |
| 77 |
return repr(value)[:-1] |
| 78 |
elif isinstance(value, float): |
| 79 |
r = repr(value) |
| 80 |
if r in ('nan', 'inf', '-inf'): |
| 81 |
return "float(%r)" % r |
| 82 |
else: |
| 83 |
return r |
| 84 |
elif isinstance(value, type): |
| 85 |
return type.__name__ |
| 86 |
else: |
| 87 |
return repr(value) |
| 88 |
|
| 89 |
|
| 90 |
def _rename_module(name): |
| 91 |
return str(RENAMED_USEMODULES.get(name, name)) |
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
helpers = r"""# -*- encoding: utf-8 -*- |
| 97 |
if 1: |
| 98 |
import sys |
| 99 |
sys.path.append(%r) |
| 100 |
%s |
| 101 |
def skip(message): |
| 102 |
print(message) |
| 103 |
raise SystemExit(0) |
| 104 |
__builtins__.skip = skip |
| 105 |
__builtins__.py3k_skip = skip |
| 106 |
class ExceptionWrapper: |
| 107 |
pass |
| 108 |
def raises(exc, *args, **kwargs): |
| 109 |
if not args: |
| 110 |
return RaisesContext(exc) |
| 111 |
func = args[0] |
| 112 |
args = args[1:] |
| 113 |
import os |
| 114 |
try: |
| 115 |
if isinstance(func, str): |
| 116 |
if func.startswith((' ', os.linesep, '\n')): |
| 117 |
# it's probably an indented block, so we prefix if True: |
| 118 |
# to avoid SyntaxError |
| 119 |
func = "if True:\n" + func |
| 120 |
frame = sys._getframe(1) |
| 121 |
exec(func, frame.f_globals, frame.f_locals) |
| 122 |
else: |
| 123 |
func(*args, **kwargs) |
| 124 |
except exc as e: |
| 125 |
res = ExceptionWrapper() |
| 126 |
res.value = e |
| 127 |
res.traceback = e.__traceback__ |
| 128 |
return res |
| 129 |
else: |
| 130 |
raise AssertionError("DID NOT RAISE") |
| 131 |
|
| 132 |
class RaisesContext(object): |
| 133 |
def __init__(self, expected_exception): |
| 134 |
self.expected_exception = expected_exception |
| 135 |
self.excinfo = None |
| 136 |
|
| 137 |
def __enter__(self): |
| 138 |
return self |
| 139 |
|
| 140 |
def __exit__(self, *tp): |
| 141 |
__tracebackhide__ = True |
| 142 |
if tp[0] is None: |
| 143 |
raise AssertionError("DID NOT RAISE") |
| 144 |
self.value = tp[1] |
| 145 |
return issubclass(tp[0], self.expected_exception) |
| 146 |
|
| 147 |
__builtins__.raises = raises |
| 148 |
class Test: |
| 149 |
pass |
| 150 |
self = Test() |
| 151 |
""" |
| 152 |
|
| 153 |
def run_with_python(python_, target_, usemodules, **definitions): |
| 154 |
if python_ is None: |
| 155 |
py.test.skip("Cannot find the default python3 interpreter to run with -A") |
| 156 |
defs = [] |
| 157 |
for symbol, value in sorted(definitions.items()): |
| 158 |
if isinstance(value, tuple) and isinstance(value[0], py.code.Source): |
| 159 |
code, args = value |
| 160 |
defs.append(str(code)) |
| 161 |
arg_repr = [] |
| 162 |
for arg in args: |
| 163 |
if isinstance(arg, types.FunctionType): |
| 164 |
arg_repr.append(arg.__name__) |
| 165 |
elif isinstance(arg, types.MethodType): |
| 166 |
arg_repr.append(arg.__name__) |
| 167 |
else: |
| 168 |
arg_repr.append(py3k_repr(arg)) |
| 169 |
args = ', '.join(arg_repr) |
| 170 |
defs.append("self.%s = anonymous(%s)\n" % (symbol, args)) |
| 171 |
elif isinstance(value, types.MethodType): |
| 172 |
|
| 173 |
code = py.code.Code(value) |
| 174 |
defs.append(str(code.source())) |
| 175 |
defs.append("type(self).%s = %s\n" % (symbol, value.__name__)) |
| 176 |
elif isinstance(value, types.ModuleType): |
| 177 |
name = value.__name__ |
| 178 |
defs.append("import %s; self.%s = %s\n" % (name, symbol, name)) |
| 179 |
elif isinstance(value, (str, unicode, int, long, float, list, tuple, |
| 180 |
dict)) or value is None: |
| 181 |
defs.append("self.%s = %s\n" % (symbol, py3k_repr(value))) |
| 182 |
|
| 183 |
check_usemodules = '' |
| 184 |
if usemodules: |
| 185 |
usemodules = [_rename_module(name) for name in usemodules] |
| 186 |
check_usemodules = """\ |
| 187 |
missing = set(%r).difference(sys.builtin_module_names) |
| 188 |
if missing: |
| 189 |
if not hasattr(sys, 'pypy_version_info'): |
| 190 |
# They may be extension modules on CPython |
| 191 |
name = None |
| 192 |
for name in missing.copy(): |
| 193 |
if name in ['cpyext', '_cffi_backend', '_rawffi']: |
| 194 |
missing.remove(name) |
| 195 |
continue |
| 196 |
try: |
| 197 |
__import__(name) |
| 198 |
except ImportError: |
| 199 |
pass |
| 200 |
else: |
| 201 |
missing.remove(name) |
| 202 |
del name |
| 203 |
if missing: |
| 204 |
sys.exit(81) |
| 205 |
del missing""" % usemodules |
| 206 |
|
| 207 |
source = list(py.code.Source(target_)) |
| 208 |
while source[0].startswith(('@py.test.mark.', '@pytest.mark.')): |
| 209 |
source.pop(0) |
| 210 |
source = source[1:] |
| 211 |
|
| 212 |
pyfile = udir.join('src.py') |
| 213 |
if isinstance(target_, str): |
| 214 |
|
| 215 |
target_name = target_.split('(', 1)[0] |
| 216 |
else: |
| 217 |
target_name = target_.__name__ |
| 218 |
with pyfile.open('w') as f: |
| 219 |
f.write(helpers % (pypyroot, check_usemodules)) |
| 220 |
f.write('\n'.join(defs)) |
| 221 |
f.write('def %s():\n' % target_name) |
| 222 |
f.write('\n'.join(source)) |
| 223 |
f.write("\ntry:\n %s()\n" % target_name) |
| 224 |
f.write('finally:\n print("===aefwuiheawiu===")') |
| 225 |
helper_dir = os.path.join(pypydir, 'tool', 'cpyext') |
| 226 |
env = os.environ.copy() |
| 227 |
env['PYTHONPATH'] = helper_dir |
| 228 |
res, stdout, stderr = run_subprocess( |
| 229 |
python_, [str(pyfile)], env=env) |
| 230 |
print pyfile.read() |
| 231 |
print "from", str(pyfile) |
| 232 |
print >> sys.stdout, stdout |
| 233 |
print >> sys.stderr, stderr |
| 234 |
if res == 81: |
| 235 |
py.test.skip('%r was not compiled w/ required usemodules: %r' % |
| 236 |
(python_, usemodules)) |
| 237 |
elif res != 0: |
| 238 |
raise AssertionError( |
| 239 |
"Subprocess failed with exit code %s:\n%s" % (res, stderr)) |
| 240 |
elif "===aefwuiheawiu===" not in stdout: |
| 241 |
raise AssertionError("%r crashed:\n%s" % (python_, stderr)) |
| 242 |
|
| 243 |
|
| 244 |
def extract_docstring_if_empty_function(fn): |
| 245 |
def empty_func(): |
| 246 |
"" |
| 247 |
pass |
| 248 |
empty_func_code = empty_func.func_code |
| 249 |
fn_code = fn.func_code |
| 250 |
if fn_code.co_code == empty_func_code.co_code and fn.__doc__ is not None: |
| 251 |
fnargs = py.std.inspect.getargs(fn_code).args |
| 252 |
head = '%s(%s):' % (fn.func_name, ', '.join(fnargs)) |
| 253 |
body = py.code.Source(fn.__doc__) |
| 254 |
return head + str(body.indent()) |
| 255 |
else: |
| 256 |
return fn |
| 257 |
|
| 258 |
|
| 259 |
class AppTestMethod(py.test.collect.Function): |
| 260 |
def _prunetraceback(self, traceback): |
| 261 |
return traceback |
| 262 |
|
| 263 |
def execute_appex(self, space, target, *args): |
| 264 |
self.space = space |
| 265 |
space.getexecutioncontext().set_sys_exc_info(None) |
| 266 |
try: |
| 267 |
target(*args) |
| 268 |
except OperationError as e: |
| 269 |
if self.config.option.raise_operr: |
| 270 |
raise |
| 271 |
tb = sys.exc_info()[2] |
| 272 |
if e.match(space, space.w_KeyboardInterrupt): |
| 273 |
raise KeyboardInterrupt, KeyboardInterrupt(), tb |
| 274 |
appexcinfo = appsupport.AppExceptionInfo(space, e) |
| 275 |
if appexcinfo.traceback: |
| 276 |
raise AppError, AppError(appexcinfo), tb |
| 277 |
raise |
| 278 |
|
| 279 |
def repr_failure(self, excinfo): |
| 280 |
if excinfo.errisinstance(AppError): |
| 281 |
excinfo = excinfo.value.excinfo |
| 282 |
return super(AppTestMethod, self).repr_failure(excinfo) |
| 283 |
|
| 284 |
def _getdynfilename(self, func): |
| 285 |
code = getattr(func, 'im_func', func).func_code |
| 286 |
return "[%s:%s]" % (code.co_filename, code.co_firstlineno) |
| 287 |
|
| 288 |
def track_allocations_collect(self): |
| 289 |
gc.collect() |
| 290 |
|
| 291 |
|
| 292 |
if hasattr(self, 'space'): |
| 293 |
self.space.getexecutioncontext()._run_finalizers_now() |
| 294 |
|
| 295 |
def setup(self): |
| 296 |
super(AppTestMethod, self).setup() |
| 297 |
instance = self.parent.obj |
| 298 |
w_instance = self.parent.w_instance |
| 299 |
space = instance.space |
| 300 |
for name in dir(instance): |
| 301 |
if name.startswith('w_'): |
| 302 |
if self.config.option.runappdirect: |
| 303 |
setattr(instance, name[2:], getattr(instance, name)) |
| 304 |
else: |
| 305 |
obj = getattr(instance, name) |
| 306 |
if isinstance(obj, types.MethodType): |
| 307 |
source = py.code.Source(obj).indent() |
| 308 |
w_func = space.appexec([], textwrap.dedent(""" |
| 309 |
(): |
| 310 |
%s |
| 311 |
return %s |
| 312 |
""") % (source, obj.__name__)) |
| 313 |
w_obj = Method(space, w_func, w_instance) |
| 314 |
else: |
| 315 |
w_obj = obj |
| 316 |
space.setattr(w_instance, space.wrap(name[2:]), w_obj) |
| 317 |
|
| 318 |
def runtest(self): |
| 319 |
target = self.obj |
| 320 |
src = extract_docstring_if_empty_function(target.im_func) |
| 321 |
space = target.im_self.space |
| 322 |
if self.config.option.runappdirect: |
| 323 |
appexec_definitions = self.parent.obj.__dict__ |
| 324 |
spaceconfig = getattr(self.parent.obj, 'spaceconfig', None) |
| 325 |
usemodules = spaceconfig.get('usemodules') if spaceconfig else None |
| 326 |
return run_with_python(self.config.option.python, src, usemodules, |
| 327 |
**appexec_definitions) |
| 328 |
filename = self._getdynfilename(target) |
| 329 |
func = app2interp_temp(src, filename=filename) |
| 330 |
w_instance = self.parent.w_instance |
| 331 |
self.execute_appex(space, func, space, w_instance) |
| 332 |
|
| 333 |
|
| 334 |
class AppClassInstance(py.test.collect.Instance): |
| 335 |
Function = AppTestMethod |
| 336 |
|
| 337 |
def setup(self): |
| 338 |
super(AppClassInstance, self).setup() |
| 339 |
instance = self.obj |
| 340 |
space = instance.space |
| 341 |
w_class = self.parent.w_class |
| 342 |
if self.config.option.runappdirect: |
| 343 |
self.w_instance = instance |
| 344 |
else: |
| 345 |
self.w_instance = space.call_function(w_class) |
| 346 |
|
| 347 |
|
| 348 |
class AppClassCollector(py.test.Class): |
| 349 |
Instance = AppClassInstance |
| 350 |
|
| 351 |
def setup(self): |
| 352 |
super(AppClassCollector, self).setup() |
| 353 |
cls = self.obj |
| 354 |
|
| 355 |
|
| 356 |
for name in dir(cls): |
| 357 |
if name.startswith('test_'): |
| 358 |
func = getattr(cls, name, None) |
| 359 |
code = getattr(func, 'func_code', None) |
| 360 |
if code and code.co_flags & 32: |
| 361 |
raise AssertionError("unsupported: %r is a generator " |
| 362 |
"app-level test method" % (name,)) |
| 363 |
|
| 364 |
|
| 365 |
space = cls.space |
| 366 |
clsname = cls.__name__ |
| 367 |
if self.config.option.runappdirect: |
| 368 |
w_class = cls |
| 369 |
else: |
| 370 |
w_class = space.call_function(space.w_type, |
| 371 |
space.wrap(clsname), |
| 372 |
space.newtuple([]), |
| 373 |
space.newdict()) |
| 374 |
self.w_class = w_class |