Debian Codegraph @

pypy/module/_hpy_universal/test/_vendored/support.py

raw symbols SCIP
1 import os, sys
2 # from filelock import FileLock
3 import pytest
4 import re
5 import subprocess
6 import textwrap
7 import distutils
8 try:
9 from pathlib import Path
10 except ImportError:
11 Path = None
12
13 PY2 = sys.version_info[0] == 2
14
15 # HPY_ROOT = Path(__file__).parent.parent
16 # LOCK = FileLock(HPY_ROOT / ".hpy.lock")
17
18 # True if `sys.executable` is set to a value that allows a Python equivalent to
19 # the current Python to be launched via, e.g., `python_subprocess.run(...)`.
20 # By default is `True` if sys.executable is set to a true value.
21 SUPPORTS_SYS_EXECUTABLE = False
22 # True if we are running on the CPython debug build
23 IS_PYTHON_DEBUG_BUILD = False
24
25 # pytest marker to run tests only on linux
26 ONLY_LINUX = pytest.mark.skipif(sys.platform!='linux', reason='linux only')
27
28 SUPPORTS_MEM_PROTECTION = '_HPY_DEBUG_FORCE_DEFAULT_MEM_PROTECT' not in os.environ
29
30 def reindent(s, indent):
31 s = textwrap.dedent(s)
32 return ''.join(' '*indent + line if line.strip() else line
33 for line in s.splitlines(True))
34
35 def atomic_run(*args, **kwargs):
36 with LOCK:
37 return subprocess.run(*args, **kwargs)
38
39
40 def make_hpy_abi_fixture(ABIs, class_fixture=False):
41 """
42 Make an hpy_abi fixture.
43
44 conftest.py defines a default hpy_abi for all tests, but individual files
45 and classes can override the set of ABIs they want to use. The indented
46 usage is the following:
47
48 # at the top of a file
49 hpy_abi = make_hpy_abi_fixture(['universal', 'debug'])
50
51 # in a class
52 class TestFoo(HPyTest):
53 hpy_abi = make_hpy_abi_fixture('with hybrid', class_fixture=True)
54 """
55 if ABIs == 'default':
56 ABIs = ['cpython', 'universal', 'debug']
57 elif ABIs == 'with hybrid':
58 ABIs = ['cpython', 'hybrid', 'hybrid+debug']
59 elif isinstance(ABIs, list):
60 pass
61 else:
62 raise ValueError("ABIs must be 'default', 'with hybrid' "
63 "or a list of strings. Got: %s" % ABIs)
64
65 if class_fixture:
66 @pytest.fixture(params=ABIs)
67 def hpy_abi(self, request):
68 abi = request.param
69 yield abi
70 else:
71 @pytest.fixture(params=ABIs)
72 def hpy_abi(request):
73 abi = request.param
74 yield abi
75
76 return hpy_abi
77
78
79 class DefaultExtensionTemplate(object):
80
81 INIT_TEMPLATE = textwrap.dedent(
82 """
83 static HPyDef *moduledefs[] = {
84 %(defines)s
85 NULL
86 };
87 %(globals_defs)s
88 static HPyModuleDef moduledef = {
89 .doc = "some test for hpy",
90 .size = 0,
91 .legacy_methods = %(legacy_methods)s,
92 .defines = moduledefs,
93 %(globals_field)s
94 };
95
96 HPy_MODINIT(%(name)s, moduledef)
97 """)
98
99 INIT_TEMPLATE_WITH_TYPES_INIT = textwrap.dedent(
100 """
101 HPyDef_SLOT(generated_init, HPy_mod_exec)
102 static int generated_init_impl(HPyContext *ctx, HPy m)
103 {
104 // Shouldn't really happen, but jut to silence the unused label warning
105 if (HPy_IsNull(m))
106 goto MODINIT_ERROR;
107
108 %(init_types)s
109 return 0;
110
111 MODINIT_ERROR:
112 return -1;
113 }
114 """ + INIT_TEMPLATE)
115
116 r_marker = re.compile(r"^\s*@([A-Za-z_]+)(\(.*\))?$")
117
118 def __init__(self, src, name):
119 self.src = textwrap.dedent(src)
120 self.name = name
121 self.defines_table = None
122 self.legacy_methods = 'NULL'
123 self.type_table = None
124 self.globals_table = None
125
126 def expand(self):
127 self.defines_table = []
128 self.globals_table = []
129 self.type_table = []
130 self.output = ['#include <hpy.h>']
131 for line in self.src.split('\n'):
132 match = self.r_marker.match(line)
133 if match:
134 name, args = self.parse_marker(match)
135 meth = getattr(self, name)
136 out = meth(*args)
137 if out is not None:
138 out = textwrap.dedent(out)
139 self.output.append(out)
140 else:
141 self.output.append(line)
142 return '\n'.join(self.output)
143
144 def parse_marker(self, match):
145 name = match.group(1)
146 args = match.group(2)
147 if args is None:
148 args = ()
149 else:
150 assert args[0] == '('
151 assert args[-1] == ')'
152 args = args[1:-1].split(',')
153 args = [x.strip() for x in args]
154 return name, args
155
156 def INIT(self):
157 NL_INDENT = '\n '
158 if self.type_table:
159 init_types = '\n'.join(self.type_table)
160 else:
161 init_types = ''
162
163 globals_defs = ''
164 globals_field = ''
165 if self.globals_table:
166 globals_defs = \
167 textwrap.dedent('''
168 static HPyGlobal *module_globals[] = {
169 %s
170 NULL
171 };''') % NL_INDENT.join(self.globals_table)
172 globals_field = '.globals = module_globals'
173
174 template = self.INIT_TEMPLATE
175 if init_types:
176 template = self.INIT_TEMPLATE_WITH_TYPES_INIT
177 self.EXPORT('generated_init')
178 exp = template % {
179 'legacy_methods': self.legacy_methods,
180 'defines': NL_INDENT.join(self.defines_table),
181 'init_types': init_types,
182 'name': self.name,
183 'globals_defs': globals_defs,
184 'globals_field': globals_field}
185 self.output.append(exp)
186 # make sure that we don't fill the tables any more
187 self.defines_table = None
188 self.type_table = None
189
190 def EXPORT(self, meth):
191 self.defines_table.append('&%s,' % meth)
192
193 def EXPORT_GLOBAL(self, var):
194 self.globals_table.append('&%s,' % var)
195
196 def EXPORT_LEGACY(self, pymethoddef):
197 self.legacy_methods = pymethoddef
198
199 def EXPORT_TYPE(self, name, spec):
200 src = """
201 if (!HPyHelpers_AddType(ctx, m, {name}, &{spec}, NULL)) {{
202 goto MODINIT_ERROR;
203 }}
204 """
205 src = reindent(src, 4)
206 self.type_table.append(src.format(
207 name=name,
208 spec=spec))
209
210 def EXTRA_INIT_FUNC(self, func):
211 src = """
212 {func}(ctx, m);
213 if (HPyErr_Occurred(ctx))
214 goto MODINIT_ERROR;
215 """
216 src = reindent(src, 4)
217 self.type_table.append(src.format(func=func))
218
219 def HPy_MODINIT(self, mod):
220 return "HPy_MODINIT({}, {})".format(self.name, mod)
221
222
223 class Spec(object):
224 def __init__(self, name, origin):
225 self.name = name
226 self.origin = origin
227
228
229 class HPyModule(object):
230 def __init__(self, name, so_file):
231 self.name = name
232 self.so_filename = so_file
233
234
235 class ExtensionCompiler:
236 def __init__(self, tmpdir, hpy_devel, hpy_abi, compiler_verbose=False,
237 dump_dir=None,
238 ExtensionTemplate=DefaultExtensionTemplate,
239 extra_include_dirs=None, extra_link_args=[]):
240 """
241 hpy_devel is an instance of HPyDevel which specifies where to find
242 include/, runtime/src, etc. Usually it will point to hpy/devel/, but
243 alternate implementations can point to their own place (e.g. pypy puts
244 it into pypy/module/_hpy_universal/_vendored)
245
246 extra_include_dirs is a list of include dirs which is put BEFORE all
247 others. By default it is empty, but it is used e.g. by PyPy to make
248 sure that #include <Python.h> picks its own version, instead of the
249 system-wide one.
250
251 extra_link_args is appended to the link arguments
252 """
253 self.tmpdir = tmpdir
254 self.dump_dir = dump_dir
255 self.hpy_devel = hpy_devel
256 self.hpy_abi = hpy_abi
257 self.compiler_verbose = compiler_verbose
258 self.ExtensionTemplate = ExtensionTemplate
259 self.extra_include_dirs = extra_include_dirs
260 self.extra_link_args = extra_link_args
261
262 def _expand(self, ExtensionTemplate, name, template):
263 source = ExtensionTemplate(template, name).expand()
264 filename = self.tmpdir.join(name + '.c')
265 dump_file = self.dump_dir.joinpath(name + '.c') if self.dump_dir else None
266 if PY2:
267 # this code is used also by pypy tests, which run on python2. In
268 # this case, we need to write as binary, because source is
269 # "bytes". If we don't and source contains a non-ascii char, we
270 # get an UnicodeDecodeError
271 if dump_file:
272 dump_file.write_text(source)
273 filename.write(source, mode='wb')
274 else:
275 if dump_file:
276 dump_file.write_text(source)
277 filename.write(source)
278 return name + '.c'
279
280 def _fixup_template(self, ExtensionTemplate):
281 return self.ExtensionTemplate if ExtensionTemplate is None else ExtensionTemplate
282
283 def compile_module(self, main_src, ExtensionTemplate=None, name='mytest', extra_sources=()):
284 """
285 Create and compile a HPy module from the template
286 """
287 ExtensionTemplate = self._fixup_template(ExtensionTemplate)
288 from distutils.core import Extension
289 filename = self._expand(ExtensionTemplate, name, main_src)
290 sources = [str(filename)]
291 for i, src in enumerate(extra_sources):
292 extra_filename = self._expand(ExtensionTemplate, 'extmod_%d' % i, src)
293 sources.append(extra_filename)
294 #
295 if self.dump_dir:
296 pytest.skip("dumping test sources only")
297 if sys.platform == 'win32':
298 # not strictly true, could be mingw
299 compile_args = [
300 '/Od',
301 '/WX', # turn warnings into errors (all, for now)
302 # '/Wall', # this is too aggressive, makes windows itself fail
303 '/Zi',
304 '-D_CRT_SECURE_NO_WARNINGS', # something about _snprintf and _snprintf_s
305 '/FS', # Since the tests run in parallel
306 ]
307 link_args = [
308 '/DEBUG',
309 '/LTCG',
310 ]
311 else:
312 compile_args = [
313 '-g', '-O0',
314 '-Wfatal-errors', # stop after one error (unrelated to warnings)
315 '-Werror', # turn warnings into errors (all, for now)
316 ]
317 link_args = [
318 '-g',
319 ]
320 #
321 ext = Extension(
322 name,
323 sources=sources,
324 include_dirs=self.extra_include_dirs,
325 extra_compile_args=compile_args,
326 extra_link_args=link_args + self.extra_link_args)
327
328 hpy_abi = self.hpy_abi
329 if hpy_abi == 'debug' or hpy_abi == 'trace':
330 # there is no compile-time difference between universal and debug
331 # extensions. The only difference happens at load time
332 hpy_abi = 'universal'
333 elif hpy_abi in ('hybrid+debug', 'hybrid+trace'):
334 hpy_abi = 'hybrid'
335 so_filename = c_compile(str(self.tmpdir), ext,
336 hpy_devel=self.hpy_devel,
337 hpy_abi=hpy_abi,
338 compiler_verbose=self.compiler_verbose)
339 return HPyModule(name, so_filename)
340
341 def make_module(self, main_src, ExtensionTemplate=None, name='mytest',
342 extra_sources=()):
343 """
344 Compile & load a module. This is NOT a proper import: e.g.
345 the module is not put into sys.modules.
346
347 We don't want to unnecessarily modify the global state inside tests:
348 if you are writing a test which needs a proper import, you should not
349 use make_module but explicitly use compile_module and import it
350 manually as required by your test.
351 """
352 ExtensionTemplate = self._fixup_template(ExtensionTemplate)
353 module = self.compile_module(
354 main_src, ExtensionTemplate, name, extra_sources)
355 so_filename = module.so_filename
356 from hpy.universal import MODE_UNIVERSAL, MODE_DEBUG, MODE_TRACE
357 if self.hpy_abi in ('universal', 'hybrid'):
358 return self.load_universal_module(name, so_filename, mode=MODE_UNIVERSAL)
359 elif self.hpy_abi in ('debug', 'hybrid+debug'):
360 return self.load_universal_module(name, so_filename, mode=MODE_DEBUG)
361 elif self.hpy_abi in ('trace', 'hybrid+trace'):
362 return self.load_universal_module(name, so_filename, mode=MODE_TRACE)
363 elif self.hpy_abi == 'cpython':
364 return self.load_cpython_module(name, so_filename)
365 else:
366 assert False
367
368 def load_universal_module(self, name, so_filename, mode):
369 assert self.hpy_abi in ('universal', 'hybrid', 'debug', 'hybrid+debug',
370 'trace', 'hybrid+trace')
371 import sys
372 import hpy.universal
373 import importlib.util
374 assert name not in sys.modules
375 spec = importlib.util.spec_from_file_location(name, so_filename)
376 mod = hpy.universal.load(name, so_filename, spec, mode=mode)
377 mod.__file__ = so_filename
378 mod.__spec__ = spec
379 return mod
380
381 def load_cpython_module(self, name, so_filename):
382 assert self.hpy_abi == 'cpython'
383 # we've got a normal CPython module compiled with the CPython API/ABI,
384 # let's load it normally. It is important to do the imports only here,
385 # because this file will be imported also by PyPy tests which runs on
386 # Python2
387 import importlib.util
388 import sys
389 assert name not in sys.modules
390 spec = importlib.util.spec_from_file_location(name, so_filename)
391 try:
392 # module_from_spec adds the module to sys.modules
393 module = importlib.util.module_from_spec(spec)
394 finally:
395 if name in sys.modules:
396 del sys.modules[name]
397 spec.loader.exec_module(module)
398 return module
399
400
401 class PythonSubprocessRunner:
402 def __init__(self, verbose, hpy_abi):
403 self.verbose = verbose
404 self.hpy_abi = hpy_abi
405
406 def run(self, mod, code):
407 """ Starts new subprocess that loads given module as 'mod' using the
408 correct ABI mode and then executes given code snippet. Use
409 "--subprocess-v" to enable logging from this.
410 """
411 env = os.environ.copy()
412 pythonpath = [os.path.dirname(mod.so_filename)]
413 if 'PYTHONPATH' in env:
414 pythonpath.append(env['PYTHONPATH'])
415 env["PYTHONPATH"] = os.pathsep.join(pythonpath)
416 if self.hpy_abi in ['universal', 'debug']:
417 # HPy module
418 load_module = "import sys;" + \
419 "import hpy.universal;" + \
420 "import importlib.util;" + \
421 "spec = importlib.util.spec_from_file_location('{name}', '{so_filename}');" + \
422 "mod = hpy.universal.load('{name}', '{so_filename}', spec, debug={debug});"
423 escaped_filename = mod.so_filename.replace("\\", "\\\\") # Needed for Windows paths
424 load_module = load_module.format(name=mod.name, so_filename=escaped_filename,
425 debug=self.hpy_abi == 'debug')
426 else:
427 # CPython module
428 assert self.hpy_abi == 'cpython'
429 load_module = "import {} as mod;".format(mod.name)
430 if self.verbose:
431 print("\n---\nExecuting in subprocess: {}".format(load_module + code))
432 result = atomic_run([sys.executable, "-c", load_module + code], env=env,
433 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
434 if self.verbose:
435 print("stdout/stderr:")
436 try:
437 out = result.stdout.decode('latin-1')
438 err = result.stderr.decode('latin-1')
439 print("----\n{out}--\n{err}-----".format(out=out, err=err))
440 except UnicodeDecodeError:
441 print("Warning: stdout or stderr could not be decoded with 'latin-1' encoding")
442 return result
443
444
445 @pytest.mark.usefixtures('initargs')
446 class HPyTest:
447 ExtensionTemplate = DefaultExtensionTemplate
448
449 @pytest.fixture()
450 def initargs(self, compiler, leakdetector, capfd):
451 self.compiler = compiler
452 self.leakdetector = leakdetector
453 self.capfd = capfd
454
455 def make_module(self, main_src, name='mytest', extra_sources=()):
456 ExtensionTemplate = self.ExtensionTemplate
457 return self.compiler.make_module(main_src, ExtensionTemplate, name,
458 extra_sources)
459
460 def compile_module(self, main_src, name='mytest', extra_sources=()):
461 ExtensionTemplate = self.ExtensionTemplate
462 return self.compiler.compile_module(main_src, ExtensionTemplate, name,
463 extra_sources)
464
465 def expect_make_error(self, main_src, error):
466 with pytest.raises(distutils.errors.CompileError):
467 self.make_module(main_src)
468 #
469 # capfd.readouterr() "eats" the output, but we want to still see it in
470 # case of failure. Just print it again
471 cap = self.capfd.readouterr()
472 sys.stdout.write(cap.out)
473 sys.stderr.write(cap.err)
474 #
475 # gcc prints compiler errors to stderr, but MSVC seems to print them
476 # to stdout. Let's just check both
477 if error in cap.out or error in cap.err:
478 # the error was found, we are good
479 return
480 raise Exception("The following error message was not found in the compiler "
481 "output:\n " + error)
482
483
484 def supports_refcounts(self):
485 """ Returns True if the underlying Python implementation supports
486 reference counts.
487
488 By default, returns True on CPython and False on other
489 implementations.
490 """
491 return sys.implementation.name == "cpython"
492
493 def supports_ordinary_make_module_imports(self):
494 """ Returns True if `.make_module(...)` loads modules using a
495 standard Python import mechanism (e.g. `importlib.import_module`).
496
497 By default, returns True because the base implementation of
498 `.make_module(...)` uses an ordinary import. Sub-classes that
499 override `.make_module(...)` may also want to override this
500 method.
501 """
502 return True
503
504 def supports_refcounts(self):
505 """ Returns True if the underlying Python implementation supports
506 the vectorcall protocol.
507
508 By default, this returns True for Python version 3.8+ on all
509 implementations.
510 """
511 return sys.version_info >= (3, 8)
512
513 def supports_sys_executable(self):
514 """ Returns True is `sys.executable` is set to a value that allows
515 a Python equivalent to the current Python to be launched via, e.g.,
516 `subprocess.run(...)`.
517
518 By default returns `True` if sys.executable is set to a true value.
519 """
520 return bool(getattr(sys, "executable", None))
521
522
523 class HPyDebugCapture:
524 """
525 Context manager that sets HPy debug invalid handle hook and remembers the
526 number of invalid handles reported. Once closed, sets the invalid handle
527 hook back to None.
528 """
529 def __init__(self):
530 self.invalid_handles_count = 0
531 self.invalid_builders_count = 0
532
533 def _capture_report(self):
534 self.invalid_handles_count += 1
535
536 def _capture_builder_report(self):
537 self.invalid_builders_count += 1
538
539 def __enter__(self):
540 from hpy.universal import _debug
541 _debug.set_on_invalid_handle(self._capture_report)
542 _debug.set_on_invalid_builder_handle(self._capture_builder_report)
543 return self
544
545 def __exit__(self, exc_type, exc_val, exc_tb):
546 from hpy.universal import _debug
547 _debug.set_on_invalid_handle(None)
548 _debug.set_on_invalid_builder_handle(None)
549
550
551 class HPyDebugTest(HPyTest):
552 """
553 Like HPyTest, but force hpy_abi=='debug' and thus run only [debug] tests
554 """
555
556 # override initargs to avoid using hpy_debug (we don't want to detect
557 # leaks here, we make them on purpose!
558 @pytest.fixture()
559 def initargs(self, compiler):
560 self.compiler = compiler
561
562 @pytest.fixture(params=['debug'])
563 def hpy_abi(self, request):
564 return request.param
565
566 # the few functions below are copied and adapted from cffi/ffiplatform.py
567
568 def c_compile(tmpdir, ext, hpy_devel, hpy_abi, compiler_verbose=0, debug=None):
569 """Compile a C extension module using distutils."""
570 saved_environ = os.environ.copy()
571 try:
572 outputfilename = _build(tmpdir, ext, hpy_devel, hpy_abi, compiler_verbose, debug)
573 outputfilename = os.path.abspath(outputfilename)
574 finally:
575 # workaround for a distutils bugs where some env vars can
576 # become longer and longer every time it is used
577 for key, value in saved_environ.items():
578 if os.environ.get(key) != value:
579 os.environ[key] = value
580 return outputfilename
581
582
583 def _build(tmpdir, ext, hpy_devel, hpy_abi, compiler_verbose=0, debug=None):
584 # XXX compact but horrible :-(
585 from distutils.core import Distribution
586 import distutils.errors
587 import distutils.log
588 #
589 dist = Distribution()
590 dist.parse_config_files()
591 if debug is None:
592 debug = sys.flags.debug
593 options_build_ext = dist.get_option_dict('build_ext')
594 options_build_ext['debug'] = ('ffiplatform', debug)
595 options_build_ext['force'] = ('ffiplatform', True)
596 options_build_ext['build_lib'] = ('ffiplatform', tmpdir)
597 options_build_ext['build_temp'] = ('ffiplatform', tmpdir)
598 options_build_py = dist.get_option_dict('build_py')
599 options_build_py['build_lib'] = ('ffiplatform', tmpdir)
600
601 # this is the equivalent of passing --hpy-abi from setup.py's command line
602 dist.hpy_abi = hpy_abi
603 # Use static libs when they have been pre-built (speeds up test compilation
604 # by avoiding recompiling the same helper sources for every test module).
605 dist.hpy_use_static_libs = bool(hpy_devel.get_static_libs(hpy_abi))
606 dist.hpy_ext_modules = [ext]
607 # We need to explicitly specify which Python modules we expect because some
608 # test cases create several distributions in the same temp directory.
609 dist.py_modules = [ext.name]
610 hpy_devel.fix_distribution(dist)
611
612 old_level = distutils.log.set_threshold(0) or 0
613 old_dir = os.getcwd()
614 try:
615 os.chdir(tmpdir)
616 distutils.log.set_verbosity(compiler_verbose)
617 dist.run_command('build_ext')
618 cmd_obj = dist.get_command_obj('build_ext')
619 outputs = cmd_obj.get_outputs()
620 sonames = [x for x in outputs if
621 not x.endswith(".py") and not x.endswith(".pyc")]
622 assert len(sonames) == 1, 'build_ext is not supposed to return multiple DLLs'
623 soname = sonames[0]
624 finally:
625 os.chdir(old_dir)
626 distutils.log.set_threshold(old_level)
627
628 return soname
629
630
631 # For situations when one wants to have "support.py" on the call stack.
632 # For example, for asserting that it is in a stack trace.
633 def trampoline(fun, *args, **kwargs):
634 fun(*args, **kwargs)