Debian Codegraph @

pypy/tool/pytest/apptest2.py

raw symbols SCIP
1 import sys
2 import os
3 import re
4 import json
5
6 import pytest
7 from pypy import pypydir
8 import pypy.interpreter.function
9 from pypy.tool.pytest import app_rewrite
10 from pypy.interpreter.error import OperationError
11 from pypy.interpreter.module import Module
12 from pypy.tool.pytest import objspace
13 from pypy.tool.pytest import appsupport
14 from pypy.tool.pytest.astrewriter.ast_rewrite import rewrite_asserts_ast
15
16
17 class AppTestModule(pytest.Module):
18 def __init__(self, path, parent, rewrite_asserts=False):
19 super(AppTestModule, self).__init__(path, parent)
20 self.rewrite_asserts = rewrite_asserts
21
22 def collect(self):
23 _, source = app_rewrite._prepare_source(self.fspath)
24 spaceconfig = extract_spaceconfig_from_source(source)
25 space = objspace.gettestobjspace(**spaceconfig)
26 w_rootdir = space.newtext(
27 os.path.join(pypydir, 'tool', 'pytest', 'astrewriter'))
28 w_source = space.newtext(source)
29 fname = str(self.fspath)
30 w_name = space.newtext(str(self.fspath.purebasename))
31 w_fname = space.newtext(fname)
32 if self.rewrite_asserts:
33 # actually a w_code, but works fine with space.exec_
34 source = space._cached_compile(
35 fname, source, "exec", 0, False,
36 ast_transform=rewrite_asserts_ast)
37 w_mod = create_module(space, w_name, fname, source)
38 mod_dict = w_mod.getdict(space).unwrap(space)
39 items = []
40 for name, w_obj in mod_dict.items():
41 if not name.startswith('test_'):
42 continue
43 if not isinstance(w_obj, pypy.interpreter.function.Function):
44 continue
45 items.append(AppTestFunction(name, self, w_obj))
46 items.sort(key=lambda item: item.reportinfo()[:2])
47 return items
48
49 def setup(self):
50 pass
51
52 def create_module(space, w_name, filename, source):
53 w_mod = Module(space, w_name)
54 w_dict = w_mod.getdict(space)
55 space.setitem(w_dict, space.newtext('__file__'), space.newtext(filename))
56 space.exec_(source, w_dict, w_dict, filename=filename)
57 return w_mod
58
59 def extract_spaceconfig_from_source(source):
60 '''
61 spaceconfig is defined in a comment where it can be any valid json dictionary object
62 '''
63 for line in source.split('\n'):
64 match = re.search('#\s*spaceconfig\s*=\s*(\{.+\})\s*', line)
65 if match:
66 return json.loads(match.group(1))
67 return {}
68
69 class AppError(Exception):
70
71 def __init__(self, excinfo):
72 self.excinfo = excinfo
73
74
75 class AppTestFunction(pytest.Item):
76
77 def __init__(self, name, parent, w_obj):
78 super(AppTestFunction, self).__init__(name, parent)
79 self.w_obj = w_obj
80
81 def runtest(self):
82 target = self.w_obj
83 space = target.space
84 self.check_run(space, target)
85 self.execute_appex(space, target)
86
87 def repr_failure(self, excinfo):
88 if excinfo.errisinstance(AppError):
89 excinfo = excinfo.value.excinfo
90 return super(AppTestFunction, self).repr_failure(excinfo)
91
92 def check_run(self, space, w_func):
93 space.appexec([w_func], """(func):
94 if hasattr(func, 'skipif'):
95 marker = func.skipif
96 arg = marker.args[0]
97 if isinstance(arg, str):
98 raise ValueError("str argument to skipif isn't supported")
99 else:
100 if arg:
101 import pytest
102 reason = marker.kwargs.get('reason', "Skipping.")
103 pytest.skip(reason)
104 """)
105
106 def execute_appex(self, space, w_func):
107 space.getexecutioncontext().set_sys_exc_info(None)
108 sig = w_func.code._signature
109 if sig.varargname or sig.kwargname or sig.num_kwonlyargnames():
110 raise ValueError(
111 'Test functions may not use *args, **kwargs or '
112 'keyword-only args')
113 args_w = self.get_fixtures(space, sig.argnames)
114 try:
115 space.call_function(w_func, *args_w)
116 except OperationError as e:
117 if self.config.option.raise_operr:
118 raise
119 tb = sys.exc_info()[2]
120 if e.match(space, space.w_KeyboardInterrupt):
121 raise KeyboardInterrupt, KeyboardInterrupt(), tb
122 appexcinfo = appsupport.AppExceptionInfo(space, e)
123 if appexcinfo.traceback:
124 raise AppError, AppError(appexcinfo), tb
125 raise
126
127 def reportinfo(self):
128 """Must return a triple (fspath, lineno, test_name)"""
129 lineno = self.w_obj.code.co_firstlineno
130 return self.parent.fspath, lineno, self.w_obj.name
131
132 def get_fixtures(self, space, fixtures):
133 if not fixtures:
134 return []
135 import imp
136 fixtures_mod = imp.load_source(
137 'fixtures', str(self.parent.fspath.new(basename='fixtures.py')))
138 result = []
139 for name in fixtures:
140 arg = getattr(fixtures_mod, name)(space, self.parent.config)
141 result.append(arg)
142 return result