Coverage for tests/test_all.py: 92%
94 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 11:16 -0800
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-26 11:16 -0800
1# This file is part of sconsUtils.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (https://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <https://www.gnu.org/licenses/>.
22"""
23Tests for sconsUtils
25Run with:
26 python test_all.py
27or by typing
28 pytest
29"""
31import contextlib
32import os
33import shutil
34import subprocess
35import sys
36import tempfile
37import unittest
39from lsst.sconsUtils.pkgconfig import PkgConfigError, find_executable
42def _pkg_config():
43 """Return the pkg-config implementation sconsUtils runs, or `None`."""
44 try:
45 return find_executable()
46 except PkgConfigError:
47 return None
50def _conda_prefix():
51 """Return the conda environment pytest runs in, or `None`.
53 Under scons ``CONDA_PREFIX`` is not forwarded to the tests (it is not in
54 state.py's preserveVars), so fall back to the prefix of the running
55 interpreter when that is a conda environment.
56 """
57 if os.environ.get("CONDA_PREFIX"): 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true
58 return os.environ["CONDA_PREFIX"]
59 if os.path.isdir(os.path.join(sys.prefix, "conda-meta")): 59 ↛ 61line 59 didn't jump to line 61 because the condition on line 59 was always true
60 return sys.prefix
61 return None
64def _has_pybind11():
65 """Return whether pkg-config can find the ``pybind11`` and ``python3``
66 modules that the testPkgConfig fixture needs to build its Python
67 module."""
68 executable = _pkg_config()
69 if executable is None: 69 ↛ 70line 69 didn't jump to line 70 because the condition on line 69 was never true
70 return False
71 return subprocess.run([executable, "--exists", "pybind11", "python3"]).returncode == 0
74@contextlib.contextmanager
75def _fixtureCopy():
76 """Copy the testPkgConfig fixture into a temporary directory and yield
77 the path of the copy.
79 Every test builds in its own copy, so that tests running concurrently
80 never see one another's build products, and the fixture itself is
81 never built in.
82 """
83 fixture = os.path.join(os.path.dirname(__file__), "testPkgConfig")
84 with tempfile.TemporaryDirectory() as tmp:
85 copy = os.path.join(tmp, "testPkgConfig")
86 shutil.copytree(
87 fixture, copy, ignore=shutil.ignore_patterns(".sconf_temp", ".sconsign.dblite", "config.log")
88 )
89 yield copy
92class SconsUtilsTestCase(unittest.TestCase):
93 """A test case for sconsUtils"""
95 def setUp(self):
96 pass
98 def tearDown(self):
99 pass
101 def testCheckErrorCode(self):
102 self.assertTrue(
103 subprocess.call(
104 f"""
105 cd "{os.path.dirname(__file__)}/testFailedTests"
106 scons > /dev/null 2>&1
107 """,
108 shell=True,
109 ),
110 "Failed to detect failed tests",
111 )
113 @unittest.skipUnless(
114 _pkg_config() and _conda_prefix() and _has_pybind11(),
115 "pkgconf or pkg-config, a conda environment and pybind11 are required to build the testPkgConfig "
116 "fixture",
117 )
118 def testPkgConfigPackage(self):
119 fixture = self.enterContext(_fixtureCopy())
120 sconsEnv = dict(os.environ, CONDA_PREFIX=_conda_prefix())
122 def clean():
123 subprocess.run(
124 ["scons", "-Q", "--clean"],
125 cwd=fixture,
126 env=sconsEnv,
127 capture_output=True,
128 )
130 self.addCleanup(clean)
132 def build():
133 result = subprocess.run(
134 ["scons", "-Q", "lib", "python", "examples"],
135 cwd=fixture,
136 env=sconsEnv,
137 capture_output=True,
138 )
139 self.assertEqual(
140 result.returncode,
141 0,
142 f"scons build of testPkgConfig fixture failed:\n"
143 f"stdout:\n{result.stdout.decode()}\nstderr:\n{result.stderr.decode()}",
144 )
146 pc = os.path.join(fixture, "lib", "pkgconfig", "lsst_testPkgConfig.pc")
147 build()
148 self.assertTrue(os.path.exists(pc))
149 self.assertTrue(os.path.exists(os.path.join(fixture, "examples", "hello")))
150 # The pybind11 module compiles, because python3 is among the
151 # template's build requirements, and works.
152 moduleDir = os.path.join(fixture, "python", "lsst", "testPkgConfig")
153 self.assertTrue(os.path.exists(os.path.join(moduleDir, "_testPkgConfig.so")))
154 hello = subprocess.run(
155 ["python", "-c", "import _testPkgConfig; print(_testPkgConfig.hello())"],
156 cwd=moduleDir,
157 env=dict(
158 sconsEnv,
159 LD_LIBRARY_PATH=os.path.join(fixture, "lib"),
160 DYLD_LIBRARY_PATH=os.path.join(fixture, "lib"),
161 ),
162 capture_output=True,
163 text=True,
164 )
165 self.assertEqual(hello.stdout.strip(), "42", hello.stderr)
166 # An unchanged .pc file is not rewritten.
167 mtime = os.path.getmtime(pc)
168 build()
169 self.assertEqual(os.path.getmtime(pc), mtime)
171 env = dict(sconsEnv, PKG_CONFIG_PATH=os.path.dirname(pc))
172 version = subprocess.check_output([_pkg_config(), "--modversion", "lsst_testPkgConfig"], env=env)
173 version = version.decode().strip()
174 self.assertNotEqual(version, "")
175 self.assertNotIn("@VERSION@", version)
177 # pkg-config does not normalize ${pcfiledir}/../.., so compare
178 # realpaths.
179 cflags = subprocess.check_output([_pkg_config(), "--cflags", "lsst_testPkgConfig"], env=env)
180 cflags = cflags.decode().split()
181 self.assertEqual(
182 [os.path.realpath(f[2:]) for f in cflags],
183 [os.path.realpath(os.path.join(fixture, "include"))],
184 )
186 libs = subprocess.check_output([_pkg_config(), "--libs", "lsst_testPkgConfig"], env=env)
187 libs = libs.decode().split()
188 self.assertEqual(os.path.realpath(libs[0][2:]), os.path.realpath(os.path.join(fixture, "lib")))
189 self.assertEqual(libs[1:], ["-ltestPkgConfig"])
191 clean()
192 self.assertFalse(os.path.exists(pc), "Generated .pc file should be removed by scons --clean")
194 def _configureFixtureCopy(self, modify):
195 """Configure a modified copy of the testPkgConfig fixture with scons
196 and return the completed process."""
197 with _fixtureCopy() as copy:
198 modify(copy)
199 return subprocess.run(
200 ["scons", "-Q", "lib"],
201 cwd=copy,
202 env=dict(os.environ, CONDA_PREFIX=_conda_prefix()),
203 capture_output=True,
204 text=True,
205 )
207 @unittest.skipUnless(
208 _pkg_config() and _conda_prefix(),
209 "pkgconf or pkg-config and a conda environment are required to configure the testPkgConfig fixture",
210 )
211 def testPkgConfigConfigurationErrors(self):
212 def addCfgFile(root):
213 os.makedirs(os.path.join(root, "ups"))
214 with open(os.path.join(root, "ups", "testPkgConfig.cfg"), "w") as f:
215 f.write("")
217 def dropVersionToken(root):
218 template = os.path.join(root, "lsst_testPkgConfig.pc.in")
219 with open(template) as f:
220 contents = f.read()
221 with open(template, "w") as f:
222 f.write(contents.replace("@VERSION@", "1.0"))
224 for modify, message in (
225 (addCfgFile, "testPkgConfig.cfg"),
226 (dropVersionToken, "does not contain the @VERSION@ token"),
227 ):
228 with self.subTest(modify=modify.__name__):
229 result = self._configureFixtureCopy(modify)
230 self.assertNotEqual(result.returncode, 0)
231 self.assertIn(message, result.stderr)
234if __name__ == "__main__":
235 unittest.main()