Debian Codegraph @

extension_helpers/tests/__init__.py

raw
1 import os
2 import subprocess as sp
3 import sys
4
5 import pytest
6
7 from ..conftest import HAS_COVERAGE, SUBPROCESS_COVERAGE, CoverageData
8
9 PACKAGE_DIR = os.path.dirname(__file__)
10
11
12 def run_cmd(cmd, args, path=None, raise_error=True):
13 """
14 Runs a shell command with the given argument list. Changes directory to
15 ``path`` if given, otherwise runs the command in the current directory.
16
17 Returns a 3-tuple of (stdout, stderr, exit code)
18
19 If ``raise_error=True`` raise an exception on non-zero exit codes.
20 """
21
22 if path is not None:
23 # Transparently support py.path objects
24 path = str(path)
25
26 p = sp.Popen([cmd] + list(args), stdout=sp.PIPE, stderr=sp.PIPE, cwd=path)
27 streams = tuple(s.decode("latin1").strip() for s in p.communicate())
28 return_code = p.returncode
29
30 if raise_error and return_code != 0:
31 raise RuntimeError(
32 f"The command `{cmd}` with args {list(args)!r} exited with code {return_code}.\n"
33 f"Stdout:\n\n{streams[0]}\n\nStderr:\n\n{streams[1]}"
34 )
35
36 return streams + (return_code,)
37
38
39 def run_setup(setup_script, args):
40 # This used to call setuptools.sandbox's run_setup, but due to issues with
41 # this and Cython (which caused segmentation faults), we now use subprocess.
42
43 setup_script = os.path.abspath(setup_script)
44
45 path = os.path.dirname(setup_script)
46 setup_script = os.path.basename(setup_script)
47
48 if HAS_COVERAGE:
49 # In this case, we run the command using the coverage command and we
50 # then collect the coverage data into a SUBPROCESS_COVERAGE list which
51 # is set up at the start of the testing process and is then combined
52 # into a single .coverage file at the end of the testing process.
53
54 p = sp.Popen(
55 ["coverage", "run", setup_script] + list(args), cwd=path, stdout=sp.PIPE, stderr=sp.PIPE
56 )
57 stdout, stderr = p.communicate()
58
59 cdata = CoverageData()
60 if HAS_COVERAGE >= 5:
61 # Support coverage<5 and >=5; see
62 # https://github.com/astropy/extension-helpers/issues/24
63 cdata.read()
64 else:
65 cdata.read_file(os.path.join(path, ".coverage"))
66
67 SUBPROCESS_COVERAGE.append(cdata)
68
69 else:
70 # Otherwise we just run the tests with Python
71
72 p = sp.Popen(
73 [sys.executable, setup_script] + list(args), cwd=path, stdout=sp.PIPE, stderr=sp.PIPE
74 )
75 stdout, stderr = p.communicate()
76
77 sys.stdout.write(stdout.decode("utf-8"))
78 sys.stderr.write(stderr.decode("utf-8"))
79
80 if p.returncode != 0:
81 raise SystemExit(p.returncode)
82
83
84 TEST_PACKAGE_SETUP_PY = """\
85 #!/usr/bin/env python
86
87 from setuptools import setup
88
89 NAME = 'extension-helpers-test'
90 VERSION = {version!r}
91
92 setup(name=NAME, version=VERSION,
93 packages=['_extension_helpers_test_'],
94 zip_safe=False)
95 """
96
97
98 def create_testpackage(tmp_path, version="0.1"):
99 source = tmp_path / "testpkg"
100 os.mkdir(source)
101
102 with source.as_cwd():
103 source.mkdir("_extension_helpers_test_")
104 init = source.join("_extension_helpers_test_", "__init__.py")
105 init.write(f"__version__ = {version!r}")
106 setup_py = TEST_PACKAGE_SETUP_PY.format(version=version)
107 source.join("setup.py").write(setup_py)
108
109 # Make the new test package into a git repo
110 run_cmd("git", ["init"])
111 run_cmd("git", ["add", "--all"])
112 run_cmd("git", ["commit", "-m", "test package"])
113
114 return source
115
116
117 @pytest.fixture
118 def testpackage(tmp_path, version="0.1"):
119 """
120 This fixture creates a simplified package called _extension_helpers_test_
121 used primarily for testing ah_boostrap, but without using the
122 extension_helpers package directly and getting it confused with the
123 extension_helpers package already under test.
124 """
125
126 return create_testpackage(tmp_path, version=version)
127
128
129 def cleanup_import(package_name):
130 """Remove all references to package_name from sys.modules"""
131
132 for k in list(sys.modules):
133 if not isinstance(k, str):
134 # Some things will actually do this =_=
135 continue
136 elif k.startswith("extension_helpers.tests"):
137 # Don't delete imported test modules or else the tests will break,
138 # badly
139 continue
140 if k == package_name or k.startswith(package_name + "."):
141 del sys.modules[k]