Coverage for tests/test_pkgconfig.py: 99%
833 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 19:26 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 19:26 +0000
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"""Tests for `lsst.sconsUtils.pkgconfig`."""
24import contextlib
25import glob
26import io
27import os
28import shutil
29import stat
30import subprocess
31import tempfile
32import types
33import unittest
34from unittest import mock
36import SCons.Environment
37from lsst.sconsUtils import dependencies, pkgconfig, state
38from lsst.sconsUtils.pkgconfig import (
39 GENERATED_SHIM_SUBDIR,
40 CyclicDependencyError,
41 PkgConfig,
42 PkgConfigDependencies,
43 PkgConfigError,
44 ResolvedDependencies,
45 apply_to_env,
46 build_search_path,
47 cfg_path,
48 check_single_format,
49 find_executable,
50 main,
51 output_path,
52 remove_generated_pc,
53 resolve,
54 synthesize_cfg_module,
55 template_path,
56 write_pc_from_template,
57 write_shims,
58)
60#: Absolute path to the root of this repository.
61_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
63#: Absolute path to the repository's static shim directory.
64_STATIC_SHIM_DIR = os.path.join(_REPO_ROOT, "python", "lsst", "sconsUtils", "pkgconfig_shims")
67def _python_has_numpy() -> bool:
68 """Return whether the ``python`` on ``PATH`` can import numpy, which is
69 what `write_shims` needs to generate ``numpy.pc``."""
70 try:
71 return subprocess.run(["python", "-c", "import numpy"], capture_output=True).returncode == 0
72 except OSError:
73 return False
76def _find_executable() -> str | None:
77 """Return the pkg-config implementation `PkgConfig` runs by default, or
78 `None` if there is none."""
79 try:
80 return find_executable()
81 except PkgConfigError:
82 return None
85#: The pkg-config implementation found on ``PATH``, or `None`.
86_EXECUTABLE = _find_executable()
89def _pkg_config_executables() -> list[str]:
90 """Return every distinct pkg-config implementation available: the one
91 `PkgConfig` runs by default and any other ``pkgconf`` or ``pkg-config``
92 on ``PATH`` or in ``/usr/bin``, which may be a different implementation
93 or version."""
94 executables = []
95 seen = set()
96 candidates = [_EXECUTABLE]
97 for name in ("pkgconf", "pkg-config"):
98 candidates += [shutil.which(name), os.path.join("/usr/bin", name)]
99 for candidate in candidates:
100 if candidate is None or not os.access(candidate, os.X_OK):
101 continue
102 resolved = os.path.realpath(candidate)
103 if resolved in seen:
104 continue
105 seen.add(resolved)
106 executables.append(candidate)
107 return executables
110def write_stub_python(directory: str, script: str) -> None:
111 """Write an executable ``<directory>/python`` shell script that runs
112 `script`, to stand in for the ``python`` on ``PATH``."""
113 path = os.path.join(directory, "python")
114 with open(path, "w") as f:
115 f.write("#!/bin/sh\n" + script + "\n")
116 os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
119def write_pc(directory: str, name: str, body: str) -> str:
120 """Write ``<directory>/<name>.pc`` with ``body`` and return its path."""
121 path = os.path.join(directory, f"{name}.pc")
122 with open(path, "w") as f:
123 f.write(body)
124 return path
127@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
128class SearchPathTestCase(unittest.TestCase):
129 """Tests for `build_search_path`."""
131 def test_order(self):
132 with (
133 tempfile.TemporaryDirectory() as root,
134 tempfile.TemporaryDirectory() as foo_dir,
135 tempfile.TemporaryDirectory() as bar_dir,
136 tempfile.TemporaryDirectory() as shim_dir,
137 mock.patch.object(pkgconfig, "static_shim_dir", return_value=shim_dir),
138 ):
139 os.makedirs(os.path.join(root, "lib", "pkgconfig"))
140 os.makedirs(os.path.join(foo_dir, "lib", "pkgconfig"))
141 # bar_dir deliberately has no lib/pkgconfig subdirectory.
143 environ = {
144 "FOO_DIR": foo_dir,
145 "BAR_DIR": bar_dir,
146 "PKG_CONFIG_PATH": "/x:/y",
147 }
148 path = build_search_path(root, environ)
149 self.assertEqual(
150 path,
151 [
152 os.path.join(root, "lib", "pkgconfig"),
153 os.path.join(foo_dir, "lib", "pkgconfig"),
154 shim_dir,
155 os.path.join(root, GENERATED_SHIM_SUBDIR),
156 "/x",
157 "/y",
158 ],
159 )
161 def test_missing_static_shims_are_skipped(self):
162 with (
163 tempfile.TemporaryDirectory() as root,
164 mock.patch.object(pkgconfig, "static_shim_dir", return_value=None),
165 ):
166 path = build_search_path(root, {})
167 self.assertEqual(
168 path,
169 [os.path.join(root, "lib", "pkgconfig"), os.path.join(root, GENERATED_SHIM_SUBDIR)],
170 )
172 def test_dir_extra_is_ignored(self):
173 with (
174 tempfile.TemporaryDirectory() as root,
175 tempfile.TemporaryDirectory() as foo_dir_extra,
176 ):
177 # Create the lib/pkgconfig subdirectory so that, if the
178 # `_EXTRA` guard were removed, `os.path.isdir` would not be
179 # the thing hiding the bug: the entry would actually appear.
180 os.makedirs(os.path.join(foo_dir_extra, "lib", "pkgconfig"))
181 environ = {
182 "FOO_DIR_EXTRA": foo_dir_extra,
183 }
184 path = build_search_path(root, environ)
185 for entry in path:
186 self.assertNotIn(foo_dir_extra, entry)
188 def test_deduplicates_preserving_first_occurrence(self):
189 with tempfile.TemporaryDirectory() as root:
190 os.makedirs(os.path.join(root, "lib", "pkgconfig"))
191 # FOO_DIR happens to point at the build root itself, so
192 # <FOO_DIR>/lib/pkgconfig duplicates <build root>/lib/pkgconfig.
193 environ = {
194 "FOO_DIR": root,
195 }
196 path = build_search_path(root, environ)
197 self.assertEqual(path.count(os.path.join(root, "lib", "pkgconfig")), 1)
198 self.assertEqual(path[0], os.path.join(root, "lib", "pkgconfig"))
201@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
202class PkgConfigRunnerTestCase(unittest.TestCase):
203 """Tests for `PkgConfig`."""
205 def setUp(self):
206 self._tmpdir = tempfile.TemporaryDirectory()
207 self.d = self._tmpdir.name
208 self.addCleanup(self._tmpdir.cleanup)
210 def test_exists_and_modversion(self):
211 write_pc(self.d, "alpha", "Name: alpha\nDescription: x\nVersion: 1.2\nCflags:\nLibs:\n")
212 pc = PkgConfig([self.d], conda_prefix="/opt/conda")
213 self.assertTrue(pc.exists("alpha"))
214 self.assertFalse(pc.exists("missing"))
215 self.assertEqual(pc.modversion("alpha"), "1.2")
217 def test_variable_none_when_unset(self):
218 write_pc(self.d, "alpha", "Name: alpha\nDescription: x\nVersion: 1.2\nCflags:\nLibs:\n")
219 pc = PkgConfig([self.d], conda_prefix="/opt/conda")
220 self.assertIsNone(pc.variable("alpha", "lsst_build_requires"))
222 def test_conda_prefix_define_variable(self):
223 write_pc(
224 self.d,
225 "beta",
226 "Name: beta\nDescription: x\nVersion: 0\nCflags: -I${conda_prefix}/include/beta\nLibs:\n",
227 )
228 pc = PkgConfig([self.d], conda_prefix="/opt/conda")
229 self.assertEqual(pc.run("--cflags-only-I", "beta").split(), ["-I/opt/conda/include/beta"])
231 def test_run_failure_raises(self):
232 pc = PkgConfig([self.d], conda_prefix="/opt/conda")
233 with self.assertRaises(PkgConfigError) as cm:
234 pc.run("--cflags", "missing")
235 # The stderr of both pkgconf and pkg-config 0.29.2 for a missing
236 # module includes this sentence; assert on it so the exception
237 # message is confirmed to carry the actual stderr, not just the
238 # echoed arguments.
239 self.assertIn("was not found in the pkg-config search path", str(cm.exception))
240 self.assertIn(os.path.basename(pc.executable), str(cm.exception))
242 def test_no_conda_prefix_fails(self):
243 with self.assertRaises(PkgConfigError):
244 PkgConfig([self.d], conda_prefix=None)
246 def test_no_executable_on_path_fails(self):
247 with mock.patch.dict(os.environ, {"PATH": self.d}), self.assertRaises(PkgConfigError) as cm:
248 os.environ.pop("PKG_CONFIG", None)
249 PkgConfig([self.d], conda_prefix="/opt/conda")
250 self.assertIn("neither pkgconf nor pkg-config was found on PATH", str(cm.exception))
252 def test_requires_skips_blank_lines(self):
253 pc = PkgConfig([self.d], conda_prefix="/opt/conda")
254 with mock.patch.object(pc, "run", return_value="\nalpha >= 1.0\n\nbeta\n"):
255 self.assertEqual(pc.requires("top"), ["alpha", "beta"])
258class FindExecutableTestCase(unittest.TestCase):
259 """Tests for `find_executable`."""
261 def setUp(self):
262 self._tmpdir = tempfile.TemporaryDirectory()
263 self.addCleanup(self._tmpdir.cleanup)
264 self.first = os.path.join(self._tmpdir.name, "first")
265 self.second = os.path.join(self._tmpdir.name, "second")
266 os.makedirs(self.first)
267 os.makedirs(self.second)
269 def _stub(self, directory, name):
270 path = os.path.join(directory, name)
271 with open(path, "w") as f:
272 f.write("#!/bin/sh\n")
273 os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
274 return path
276 def _path(self, *directories):
277 return {"PATH": os.pathsep.join(directories)}
279 def test_pkgconf_is_preferred_within_a_directory(self):
280 pkgconf = self._stub(self.first, "pkgconf")
281 self._stub(self.first, "pkg-config")
282 self.assertEqual(find_executable(self._path(self.first)), pkgconf)
284 def test_pkg_config_alone_is_used(self):
285 pkg_config = self._stub(self.first, "pkg-config")
286 self.assertEqual(find_executable(self._path(self.first)), pkg_config)
288 def test_earlier_directory_wins(self):
289 # e.g. a conda pkg-config is used over a system pkgconf.
290 pkg_config = self._stub(self.first, "pkg-config")
291 self._stub(self.second, "pkgconf")
292 self.assertEqual(find_executable(self._path(self.first, self.second)), pkg_config)
294 def test_pkg_config_variable(self):
295 self._stub(self.first, "pkgconf")
296 chosen = self._stub(self.second, "my-pkg-config")
297 environ = dict(self._path(self.first, self.second), PKG_CONFIG="my-pkg-config")
298 self.assertEqual(find_executable(environ), chosen)
299 environ["PKG_CONFIG"] = chosen
300 self.assertEqual(find_executable(environ), chosen)
302 def test_missing_pkg_config_variable_fails(self):
303 self._stub(self.first, "pkgconf")
304 environ = dict(self._path(self.first), PKG_CONFIG="absent")
305 with self.assertRaises(PkgConfigError) as cm:
306 find_executable(environ)
307 self.assertIn("PKG_CONFIG=absent", str(cm.exception))
309 def test_nothing_found_fails(self):
310 with self.assertRaises(PkgConfigError):
311 find_executable(self._path(self.first))
314@unittest.skipUnless(_pkg_config_executables(), "no pkg-config implementation is available")
315class PresentTestCase(unittest.TestCase):
316 """Tests for `PkgConfig.present`, under every available pkg-config
317 implementation (pkg-config and pkgconf behave differently for a module
318 whose ``Requires`` are missing)."""
320 def setUp(self):
321 self._tmpdir = tempfile.TemporaryDirectory()
322 self.d = self._tmpdir.name
323 self.addCleanup(self._tmpdir.cleanup)
324 write_pc(
325 self.d,
326 "lsst_broken",
327 "Name: lsst_broken\nDescription: x\nVersion: 1.0\nRequires: lsst_gone\nCflags:\nLibs:\n",
328 )
329 write_pc(self.d, "lsst_fine", "Name: lsst_fine\nDescription: x\nVersion: 1.0\nCflags:\nLibs:\n")
331 def test_broken_is_present_but_does_not_exist(self):
332 for executable in _pkg_config_executables():
333 with self.subTest(executable=executable):
334 pc = PkgConfig([self.d], conda_prefix="/opt/conda", executable=executable)
335 self.assertFalse(pc.exists("lsst_broken"))
336 self.assertTrue(pc.present("lsst_broken"))
337 self.assertTrue(pc.present("lsst_fine"))
338 self.assertFalse(pc.present("lsst_absent"))
339 with self.assertRaises(PkgConfigError) as cm:
340 synthesize_cfg_module("broken", pc, "/opt/conda")
341 self.assertIn("lsst_gone", str(cm.exception))
343 def test_default_search_path_is_searched(self):
344 # PKG_CONFIG_LIBDIR replaces pkg-config's compiled-in default path.
345 with mock.patch.dict(os.environ, {"PKG_CONFIG_LIBDIR": self.d}):
346 for executable in _pkg_config_executables():
347 with self.subTest(executable=executable):
348 pc = PkgConfig([], conda_prefix="/opt/conda", executable=executable)
349 self.assertTrue(pc.exists("lsst_fine"))
350 self.assertTrue(pc.present("lsst_broken"))
351 self.assertFalse(pc.present("lsst_absent"))
353 def test_compiled_in_default_path_is_searched(self):
354 with mock.patch.dict(os.environ):
355 os.environ.pop("PKG_CONFIG_LIBDIR", None)
356 for executable in _pkg_config_executables():
357 with self.subTest(executable=executable):
358 pc_path = subprocess.run(
359 [executable, "--variable=pc_path", "pkg-config"], capture_output=True, text=True
360 ).stdout.strip()
361 found = [
362 os.path.basename(path)[: -len(".pc")]
363 for directory in pc_path.split(os.pathsep)
364 if directory
365 for path in sorted(glob.glob(os.path.join(directory, "*.pc")))
366 ]
367 if not found: 367 ↛ 368line 367 didn't jump to line 368 because the condition on line 367 was never true
368 self.skipTest(f"{executable} has no .pc files on its default path")
369 pc = PkgConfig([], conda_prefix="/opt/conda", executable=executable)
370 self.assertTrue(pc.present(found[0]))
373@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
374class ClosureTestCase(unittest.TestCase):
375 """Tests for `PkgConfig.closure` and `PkgConfig.requires`."""
377 def setUp(self):
378 self._tmpdir = tempfile.TemporaryDirectory()
379 self.d = self._tmpdir.name
380 self.addCleanup(self._tmpdir.cleanup)
381 # top -> mid -> leaf ; top -> leaf (leaf reachable by two paths,
382 # must appear only once in the closure) ; side is independent.
383 write_pc(self.d, "leaf", "Name: leaf\nDescription: x\nVersion: 1.0\nCflags:\nLibs:\n")
384 write_pc(
385 self.d,
386 "mid",
387 "Name: mid\nDescription: x\nVersion: 1.0\nRequires: leaf\nCflags:\nLibs:\n",
388 )
389 write_pc(
390 self.d,
391 "top",
392 "Name: top\nDescription: x\nVersion: 1.0\nRequires: mid, leaf\nCflags:\nLibs:\n",
393 )
394 write_pc(self.d, "side", "Name: side\nDescription: x\nVersion: 1.0\nCflags:\nLibs:\n")
395 # a -> b -> a is a cycle.
396 write_pc(self.d, "a", "Name: a\nDescription: x\nVersion: 1.0\nRequires: b\nCflags:\nLibs:\n")
397 write_pc(self.d, "b", "Name: b\nDescription: x\nVersion: 1.0\nRequires: a\nCflags:\nLibs:\n")
398 self.pc = PkgConfig([self.d], conda_prefix="/opt/conda")
400 def test_closure_order(self):
401 self.assertEqual(self.pc.closure(["top", "side"]), ["top", "mid", "leaf", "side"])
403 def test_cycle_detected(self):
404 # Not every implementation answers queries about a module on a
405 # cycle (see test_real_cycle_fails), so stub out requires().
406 graph = {"top": ["a"], "a": ["b"], "b": ["c", "a"], "c": []}
407 with (
408 mock.patch.object(self.pc, "requires", side_effect=graph.__getitem__),
409 self.assertRaises(CyclicDependencyError) as cm,
410 ):
411 self.pc.closure(["top"])
412 self.assertEqual(str(cm.exception), "a -> b -> a")
414 def test_real_cycle_fails(self):
415 # pkg-config 0.29 and pkgconf 1 and 3 report the requirements of a
416 # module on a cycle, so closure() finds the cycle; pkgconf 2 refuses
417 # every query about such a module. Either way it is an error.
418 with self.assertRaises(PkgConfigError) as cm:
419 self.pc.closure(["a"])
420 self.assertIn("a", str(cm.exception))
423@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
424class FlagQueryTestCase(unittest.TestCase):
425 """Tests for the ``*_only_*`` flag query methods on `PkgConfig`."""
427 def setUp(self):
428 self._tmpdir = tempfile.TemporaryDirectory()
429 self.d = self._tmpdir.name
430 self.addCleanup(self._tmpdir.cleanup)
431 write_pc(
432 self.d,
433 "leaf",
434 "Name: leaf\nDescription: x\nVersion: 1.0\nCflags: -I/inc/leaf\nLibs: -L/lib/leaf -lleaf\n",
435 )
436 write_pc(
437 self.d,
438 "top",
439 "Name: top\nDescription: x\nVersion: 1.0\nRequires: leaf\n"
440 "Cflags: -I/inc/top -DTOP\n"
441 "Libs: -L/lib/top -ltop -Wl,-rpath,/lib/top\n",
442 )
443 self.pc = PkgConfig([self.d], conda_prefix="/opt/conda")
445 def test_split_queries(self):
446 self.assertEqual(self.pc.cflags_only_I(["top"]), ["/inc/top", "/inc/leaf"])
447 self.assertEqual(self.pc.cflags_only_other(["top"]), ["-DTOP"])
448 self.assertEqual(self.pc.libs_only_L(["top"]), ["/lib/top", "/lib/leaf"])
449 self.assertEqual(self.pc.libs_only_l(["top"]), ["top", "leaf"])
450 self.assertEqual(self.pc.libs_only_other(["top"]), ["-Wl,-rpath,/lib/top"])
452 def test_bare_prefix_is_dropped(self):
453 # A bare -I or -L, e.g. from an empty variable, must not become ""
454 # (realpath("") is the cwd). A literal "-L -lbare" would not do
455 # here: pkgconf 3 reads it as the single argument "-L-lbare".
456 write_pc(
457 self.d,
458 "bare",
459 "empty=\nName: bare\nDescription: x\nVersion: 1.0\n"
460 "Cflags: -I/inc/bare -I${empty}\nLibs: -L/lib/bare -L${empty} -lbare\n",
461 )
462 self.assertEqual(self.pc.cflags_only_I(["bare"]), ["/inc/bare"])
463 self.assertEqual(self.pc.libs_only_L(["bare"]), ["/lib/bare"])
464 self.assertEqual(self.pc.libs_only_l(["bare"]), ["bare"])
466 def test_empty_modules_returns_empty_without_invoking(self):
467 self.assertEqual(self.pc.cflags_only_I([]), [])
468 self.assertEqual(self.pc.cflags_only_other([]), [])
469 self.assertEqual(self.pc.libs_only_L([]), [])
470 self.assertEqual(self.pc.libs_only_l([]), [])
471 self.assertEqual(self.pc.libs_only_other([]), [])
474class ResolveFixture:
475 """Mixin providing a small tree of ``.pc`` files for `resolve` tests.
477 ``lsst_prim`` requires ``lsst_dep`` and ``eigen3`` and lists
478 ``boost_test`` and ``pybind11`` as build requirements.
479 """
481 def setUp(self):
482 self._tmpdir = tempfile.TemporaryDirectory()
483 self.addCleanup(self._tmpdir.cleanup)
484 # Resolve the temporary directory itself so that the only
485 # difference between raw and realpath'd paths below is the
486 # deliberate `/../` detour, not e.g. a symlinked /tmp.
487 root = os.path.realpath(self._tmpdir.name)
488 pcdir = os.path.join(root, "pkgconfig")
489 self.conda = os.path.join(root, "conda")
490 self.prim_inc = os.path.join(root, "prim", "include")
491 # Written with a detour that pkg-config does not normalize.
492 self.dep_inc_raw = os.path.join(root, "dep", "..", "dep", "include")
493 self.dep_inc = os.path.join(root, "dep", "include")
494 self.prim_inc_file = os.path.join(root, "prim", "doc", "prim.inc")
495 self.dep_tag = os.path.join(root, "dep", "doc", "dep.tag")
496 self.prim_tag = os.path.join(root, "prim", "doc", "prim.tag")
497 for directory in (
498 pcdir,
499 os.path.join(self.conda, "include", "eigen3"),
500 self.prim_inc,
501 self.dep_inc,
502 ):
503 os.makedirs(directory)
505 write_pc(
506 pcdir,
507 "lsst_prim",
508 f"includedir={self.prim_inc}\n"
509 "lsst_build_requires=boost_test pybind11\n"
510 f"doxygen_tag={self.prim_tag}\n"
511 f"doxygen_include={self.prim_inc_file}\n"
512 "\n"
513 "Name: lsst_prim\nDescription: x\nVersion: 1.0\n"
514 "Requires: lsst_dep eigen3\n"
515 "Cflags: -I${includedir}\n"
516 "Libs: -lprim\n",
517 )
518 write_pc(
519 pcdir,
520 "lsst_dep",
521 f"includedir={self.dep_inc_raw}\n"
522 f"doxygen_tag={self.dep_tag}\n"
523 "lsst_test_libs=-lboost_unit_test_framework -ldep_test\n"
524 "\n"
525 "Name: lsst_dep\nDescription: x\nVersion: 2.0\n"
526 "Cflags: -I${includedir}\n"
527 "Libs: -ldep\n",
528 )
529 write_pc(
530 pcdir,
531 "eigen3",
532 f"Name: eigen3\nDescription: x\nVersion: 3.4\nCflags: -I{self.conda}/include/eigen3\nLibs:\n",
533 )
534 write_pc(
535 pcdir,
536 "boost_test",
537 "lsst_test_libs=-lboost_unit_test_framework\n"
538 "\n"
539 f"Name: boost_test\nDescription: x\nVersion: 1.86\nCflags: -I{self.conda}/include\nLibs:\n",
540 )
541 write_pc(
542 pcdir,
543 "pybind11",
544 "lsst_python_libs=-lpython_extra\n"
545 "\n"
546 f"Name: pybind11\nDescription: x\nVersion: 2.13\nCflags: -I{self.conda}/include\nLibs:\n",
547 )
548 write_pc(
549 pcdir,
550 "lsst_prim2",
551 "lsst_build_requires=nonexistent_mod\n"
552 "\n"
553 "Name: lsst_prim2\nDescription: x\nVersion: 1.0\nCflags:\nLibs:\n",
554 )
555 self.pcdir = pcdir
556 self.pc = PkgConfig([pcdir], conda_prefix=self.conda)
559@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
560class ResolveTestCase(ResolveFixture, unittest.TestCase):
561 """Tests for `resolve`."""
563 def test_modules_and_versions(self):
564 r = resolve("prim", self.pc, self.conda)
565 self.assertEqual(r.modules, ["lsst_prim", "lsst_dep", "eigen3", "boost_test", "pybind11"])
566 self.assertEqual(set(r.versions), {"prim", "dep", "eigen3", "boost_test", "pybind11"})
567 self.assertEqual(r.versions["dep"], "2.0")
568 self.assertEqual(r.versions["eigen3"], "3.4")
570 def test_include_routing(self):
571 r = resolve("prim", self.pc, self.conda)
572 # Guard: the detour really is there, so the assertion below fails
573 # unless realpath normalization is applied.
574 self.assertNotEqual(self.dep_inc_raw, os.path.realpath(self.dep_inc_raw))
575 self.assertEqual(r.cpppath, [os.path.realpath(self.prim_inc), os.path.realpath(self.dep_inc_raw)])
576 # <conda>/include is claimed by both boost_test and pybind11 but
577 # must appear exactly once.
578 self.assertEqual(
579 r.xcpppath,
580 [
581 os.path.realpath(os.path.join(self.conda, "include", "eigen3")),
582 os.path.realpath(os.path.join(self.conda, "include")),
583 ],
584 )
586 def test_conda_include_always_external(self):
587 # Even if an lsst_* module claims <conda>/include as its includedir
588 # (the container case), it must still route to xcpppath.
589 pcdir = os.path.join(os.path.dirname(self.conda), "pkgconfig")
590 write_pc(
591 pcdir,
592 "lsst_inst",
593 f"includedir={self.conda}/include\n"
594 "\n"
595 "Name: lsst_inst\nDescription: x\nVersion: 1.0\n"
596 "Cflags: -I${includedir}\nLibs: -linst\n",
597 )
598 r = resolve("inst", self.pc, self.conda)
599 self.assertEqual(r.cpppath, [])
600 self.assertEqual(r.xcpppath, [os.path.realpath(os.path.join(self.conda, "include"))])
602 def test_lib_categories(self):
603 r = resolve("prim", self.pc, self.conda)
604 self.assertEqual(r.libs["main"], ["prim", "dep"])
605 # boost_unit_test_framework is declared by both
606 # lsst_dep and boost_test, and appears once, in first-seen order.
607 self.assertEqual(r.libs["test"], ["boost_unit_test_framework", "dep_test"])
608 self.assertEqual(r.libs["python"], ["python_extra"])
610 def test_doxygen(self):
611 r = resolve("prim", self.pc, self.conda)
612 # The primary's own tag is excluded.
613 self.assertEqual(r.doxygen["tags"], [self.dep_tag])
614 self.assertEqual(r.doxygen["includes"], [self.prim_inc_file])
616 def test_missing_build_require_names_module(self):
617 with self.assertRaises(PkgConfigError) as cm:
618 resolve("prim2", self.pc, self.conda)
619 self.assertIn("nonexistent_mod", str(cm.exception))
621 def test_missing_primary_names_module(self):
622 with self.assertRaises(PkgConfigError) as cm:
623 resolve("absent", self.pc, self.conda)
624 self.assertIn("lsst_absent", str(cm.exception))
626 def test_without_build_requires(self):
627 r = resolve("prim", self.pc, self.conda, include_build_requires=False)
628 self.assertEqual(r.modules, ["lsst_prim", "lsst_dep", "eigen3"])
629 self.assertEqual(r.libs["python"], [])
630 # lsst_dep still contributes its test libraries.
631 self.assertEqual(r.libs["test"], ["boost_unit_test_framework", "dep_test"])
632 self.assertEqual(r.xcpppath, [os.path.realpath(os.path.join(self.conda, "include", "eigen3"))])
634 def test_missing_requires_of_primary_is_named(self):
635 write_pc(
636 self.pcdir,
637 "lsst_needy",
638 "Name: lsst_needy\nDescription: x\nVersion: 1.0\nRequires: lsst_gone\nCflags:\nLibs:\n",
639 )
640 with self.assertRaises(PkgConfigError) as cm:
641 resolve("needy", self.pc, self.conda)
642 self.assertIn("lsst_needy", str(cm.exception))
643 self.assertIn("lsst_gone", str(cm.exception))
645 def test_missing_requires_of_build_require_is_named(self):
646 write_pc(
647 self.pcdir,
648 "lsst_prim3",
649 "lsst_build_requires=needy_tool\n"
650 "\n"
651 "Name: lsst_prim3\nDescription: x\nVersion: 1.0\nCflags:\nLibs:\n",
652 )
653 write_pc(
654 self.pcdir,
655 "needy_tool",
656 "Name: needy_tool\nDescription: x\nVersion: 1.0\nRequires: gone_tool\nCflags:\nLibs:\n",
657 )
658 with self.assertRaises(PkgConfigError) as cm:
659 resolve("prim3", self.pc, self.conda)
660 self.assertIn("needy_tool", str(cm.exception))
661 self.assertIn("gone_tool", str(cm.exception))
663 def test_options_with_separate_arguments_are_kept_together(self):
664 write_pc(
665 self.pcdir,
666 "lsst_fw",
667 "Name: lsst_fw\nDescription: x\nVersion: 1.0\nRequires: lsst_fwdep\n"
668 "Cflags: -isystem /a -DA\nLibs: -framework Accelerate -framework CoreFoundation\n",
669 )
670 write_pc(
671 self.pcdir,
672 "lsst_fwdep",
673 "Name: lsst_fwdep\nDescription: x\nVersion: 1.0\n"
674 "Cflags: -isystem /b\nLibs: -framework Accelerate -Wl,-z,defs\n",
675 )
676 r = resolve("fw", self.pc, self.conda)
677 self.assertEqual(r.ccflags, [("-isystem", "/a"), "-DA", ("-isystem", "/b")])
678 self.assertEqual(
679 r.linkflags,
680 [
681 ("-framework", "Accelerate"),
682 ("-framework", "CoreFoundation"),
683 ("-framework", "Accelerate"),
684 "-Wl,-z,defs",
685 ],
686 )
687 env = make_cfg_env()
688 apply_to_env(env, r)
689 self.assertEqual(env.subst("$CCFLAGS"), "-isystem /a -DA -isystem /b")
690 self.assertEqual(
691 env.subst("$LINKFLAGS"), "-framework Accelerate -framework CoreFoundation -Wl,-z,defs"
692 )
694 def test_trailing_option_is_kept(self):
695 self.assertEqual(pkgconfig._group_flags(["-DA", "-isystem"]), ["-DA", "-isystem"])
697 def test_queries_are_cached(self):
698 resolve("prim", self.pc, self.conda)
699 with mock.patch.object(pkgconfig.subprocess, "run", wraps=subprocess.run) as run:
700 resolve("prim", self.pc, self.conda)
701 self.assertEqual(run.call_count, 0)
702 # lsst_dep was already queried as part of lsst_prim's closure,
703 # so only the queries over the new module set are run.
704 synthesize_cfg_module("dep", self.pc, self.conda)
705 queries = [call.args[0][2] for call in run.call_args_list]
706 self.assertTrue(queries)
707 for query in queries:
708 self.assertNotIn(query.split("=")[0], ("--modversion", "--variable", "--print-requires"))
711def make_cfg_env() -> SCons.Environment.Environment:
712 """Return an environment initialized the way `configure` initializes
713 one before running the ``.cfg`` path."""
714 env = SCons.Environment.Environment(tools=[])
715 env["CPPPATH"] = []
716 env["XCPPPATH"] = []
717 env["LIBPATH"] = []
718 env.libs = {"main": [], "python": [], "test": []}
719 env.doxygen = {"tags": [], "includes": []}
720 return env
723@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
724class SynthesizeTestCase(ResolveFixture, unittest.TestCase):
725 """Tests for `synthesize_cfg_module` and `SyntheticConfiguration`."""
727 def setUp(self):
728 super().setUp()
729 self.mod = synthesize_cfg_module("prim", self.pc, self.conda)
731 def test_module_shape(self):
732 mod = self.mod
733 self.assertEqual(mod.dependencies, {})
734 self.assertEqual(mod.config.name, "prim")
735 self.assertEqual(mod.config.version, self.pc.modversion("lsst_prim"))
736 # Stored pre-reversed, as PackageTree.configure reverses them.
737 self.assertEqual(mod.config.libs["main"], ["dep", "prim"])
738 # Build requirements of a dependency are excluded.
739 self.assertEqual(mod.config.libs["python"], [])
740 self.assertEqual(mod.config.libs["test"], ["dep_test", "boost_unit_test_framework"])
741 self.assertEqual(
742 mod.config.paths,
743 {
744 "CPPPATH": [os.path.realpath(self.prim_inc), os.path.realpath(self.dep_inc)],
745 "XCPPPATH": [os.path.realpath(os.path.join(self.conda, "include", "eigen3"))],
746 "LIBPATH": [],
747 },
748 )
749 # Unlike resolve(), the package's own tag file is included.
750 self.assertEqual(
751 mod.config.doxygen, {"tags": [self.prim_tag, self.dep_tag], "includes": [self.prim_inc_file]}
752 )
753 self.assertEqual(mod.config.provides, {"headers": (), "libs": ("prim", "dep")})
754 # The rest of the closure, which PackageTree still lists.
755 self.assertEqual(mod.provided, {"dep": "2.0", "eigen3": "3.4"})
757 def test_configure_applies_and_reversal_restores_order(self):
758 env = make_cfg_env()
759 env["CPPPATH"] = ["/already"]
760 # A library already contributed by another package is not repeated.
761 env.libs["main"].append("dep")
762 conf = types.SimpleNamespace(env=env)
763 self.assertTrue(self.mod.config.configure(conf, packages={}, build=False))
764 self.assertEqual(
765 env["CPPPATH"], [os.path.realpath(self.prim_inc), os.path.realpath(self.dep_inc), "/already"]
766 )
767 self.assertEqual(env["XCPPPATH"], [os.path.realpath(os.path.join(self.conda, "include", "eigen3"))])
768 self.assertEqual(
769 env.doxygen, {"tags": [self.prim_tag, self.dep_tag], "includes": [self.prim_inc_file]}
770 )
771 for target in env.libs: # what PackageTree.configure does
772 env.libs[target].reverse()
773 self.assertEqual(env.libs["main"], ["prim", "dep"])
774 self.assertEqual(env.libs["test"], ["boost_unit_test_framework", "dep_test"])
775 # The configuration's own lists are left untouched.
776 self.assertEqual(self.mod.config.libs["main"], ["dep", "prim"])
778 def test_configure_does_not_repeat_doxygen_files(self):
779 # Two synthesized closures sharing lsst_dep must not add its tag
780 # file twice.
781 env = make_cfg_env()
782 conf = types.SimpleNamespace(env=env)
783 self.assertTrue(self.mod.config.configure(conf, packages={}, build=False))
784 self.assertTrue(synthesize_cfg_module("dep", self.pc, self.conda).config.configure(conf, {}, False))
785 self.assertEqual(
786 env.doxygen, {"tags": [self.prim_tag, self.dep_tag], "includes": [self.prim_inc_file]}
787 )
789 def test_configure_adds_new_target(self):
790 env = make_cfg_env()
791 del env.libs["test"]
792 conf = types.SimpleNamespace(env=env)
793 self.assertTrue(self.mod.config.configure(conf, packages={}, build=False))
794 self.assertEqual(env.libs["test"], ["dep_test", "boost_unit_test_framework"])
795 # The environment gets its own copy of the library list.
796 self.assertIsNot(env.libs["test"], self.mod.config.libs["test"])
798 def test_configure_build_adds_includes_not_tags(self):
799 env = make_cfg_env()
800 conf = types.SimpleNamespace(env=env)
801 self.assertTrue(self.mod.config.configure(conf, packages={}, build=True))
802 self.assertEqual(env.doxygen, {"tags": [], "includes": [self.prim_inc_file]})
804 def test_configure_appends_flags(self):
805 write_pc(
806 self.pcdir,
807 "lsst_flagged",
808 "Name: lsst_flagged\nDescription: x\nVersion: 3.0\n"
809 "Cflags: -DFLAGGED\nLibs: -L/lib/flagged -lflagged -Wl,-z,defs\n",
810 )
811 mod = synthesize_cfg_module("flagged", self.pc, self.conda)
812 self.assertEqual(mod.config.version, "3.0")
813 env = make_cfg_env()
814 env["CCFLAGS"] = ["-DFLAGGED"]
815 conf = types.SimpleNamespace(env=env)
816 self.assertTrue(mod.config.configure(conf, packages={}, build=False))
817 self.assertEqual(env["CCFLAGS"], ["-DFLAGGED"])
818 self.assertEqual(env["LINKFLAGS"], ["-Wl,-z,defs"])
819 self.assertEqual(env["LIBPATH"], ["/lib/flagged"])
820 self.assertEqual(env.libs["main"], ["flagged"])
822 def test_configure_does_not_merge_multi_token_flags(self):
823 # Two dependencies each linking a framework must neither repeat it
824 # nor lose a -framework option to de-duplication.
825 for name, framework in (("fw1", "Accelerate"), ("fw2", "CoreFoundation")):
826 write_pc(
827 self.pcdir,
828 f"lsst_{name}",
829 f"Name: lsst_{name}\nDescription: x\nVersion: 1.0\n"
830 f"Cflags:\nLibs: -framework Accelerate -framework {framework}\n",
831 )
832 env = make_cfg_env()
833 conf = types.SimpleNamespace(env=env)
834 for name in ("fw1", "fw2"):
835 mod = synthesize_cfg_module(name, self.pc, self.conda)
836 self.assertTrue(mod.config.configure(conf, packages={}, build=False))
837 self.assertEqual(env.subst("$LINKFLAGS"), "-framework Accelerate -framework CoreFoundation")
839 def test_missing_module_raises(self):
840 with self.assertRaises(PkgConfigError):
841 synthesize_cfg_module("absent", self.pc, self.conda)
843 def test_broken_requires_is_present_and_named(self):
844 write_pc(
845 self.pcdir,
846 "lsst_broken",
847 "Name: lsst_broken\nDescription: x\nVersion: 1.0\nRequires: lsst_gone\nCflags:\nLibs:\n",
848 )
849 # A broken module is present but does not "exist" to pkg-config.
850 self.assertFalse(self.pc.exists("lsst_broken"))
851 self.assertTrue(self.pc.present("lsst_broken"))
852 self.assertFalse(self.pc.present("lsst_absent"))
853 with self.assertRaises(PkgConfigError) as cm:
854 synthesize_cfg_module("broken", self.pc, self.conda)
855 self.assertIn("lsst_gone", str(cm.exception))
858class TemplateTestCase(unittest.TestCase):
859 """Tests for template discovery and `.pc` generation."""
861 def test_paths(self):
862 self.assertEqual(template_path("/r", "afw"), "/r/lsst_afw.pc.in")
863 self.assertEqual(cfg_path("/r", "afw"), "/r/ups/afw.cfg")
864 self.assertEqual(output_path("/r", "afw"), "/r/lib/pkgconfig/lsst_afw.pc")
866 def test_both_formats_is_error(self):
867 with tempfile.TemporaryDirectory() as root:
868 os.makedirs(os.path.join(root, "ups"))
869 with open(template_path(root, "afw"), "w") as f:
870 f.write("Name: lsst_afw\n")
871 with open(cfg_path(root, "afw"), "w") as f:
872 f.write("")
873 with self.assertRaises(PkgConfigError) as cm:
874 check_single_format(root, "afw")
875 self.assertIn("lsst_afw.pc.in", str(cm.exception))
876 self.assertIn("afw.cfg", str(cm.exception))
878 def test_neither_format_is_fine(self):
879 with tempfile.TemporaryDirectory() as root:
880 # Neither file exists; should not raise.
881 check_single_format(root, "afw")
883 def test_only_template_is_fine(self):
884 with tempfile.TemporaryDirectory() as root:
885 with open(template_path(root, "afw"), "w") as f:
886 f.write("Name: lsst_afw\n")
887 check_single_format(root, "afw")
889 def test_only_cfg_is_fine(self):
890 with tempfile.TemporaryDirectory() as root:
891 os.makedirs(os.path.join(root, "ups"))
892 with open(cfg_path(root, "afw"), "w") as f:
893 f.write("")
894 check_single_format(root, "afw")
896 @unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
897 def test_write_substitutes_version_and_is_idempotent(self):
898 with tempfile.TemporaryDirectory() as root:
899 tmpl = os.path.join(root, "lsst_x.pc.in")
900 out = os.path.join(root, "lib", "pkgconfig", "lsst_x.pc")
901 with open(tmpl, "w") as f:
902 f.write("Name: lsst_x\nDescription: d\nVersion: @VERSION@\nCflags:\nLibs:\n")
904 self.assertTrue(write_pc_from_template(tmpl, out, "g1234+5"))
905 with open(out) as f:
906 self.assertIn("Version: g1234+5\n", f.read())
908 mtime_after_first_write = os.path.getmtime(out)
910 self.assertFalse(write_pc_from_template(tmpl, out, "g1234+5"))
911 self.assertEqual(os.path.getmtime(out), mtime_after_first_write)
913 # A new version rewrites the existing file.
914 self.assertTrue(write_pc_from_template(tmpl, out, "g5678"))
915 with open(out) as f:
916 self.assertIn("Version: g5678\n", f.read())
917 self.assertTrue(write_pc_from_template(tmpl, out, "g1234+5"))
919 # And pkg-config reads it back correctly.
920 self.assertEqual(
921 PkgConfig([os.path.dirname(out)], "/c").modversion("lsst_x"),
922 "g1234+5",
923 )
925 def test_unknown_version_is_written(self):
926 with tempfile.TemporaryDirectory() as root:
927 tmpl = os.path.join(root, "lsst_x.pc.in")
928 out = os.path.join(root, "lib", "pkgconfig", "lsst_x.pc")
929 with open(tmpl, "w") as f:
930 f.write("Name: lsst_x\nDescription: d\nVersion: @VERSION@\nCflags:\nLibs:\n")
932 self.assertTrue(write_pc_from_template(tmpl, out, "unknown"))
933 with open(out) as f:
934 self.assertIn("Version: unknown\n", f.read())
936 def test_missing_token_fails(self):
937 with tempfile.TemporaryDirectory() as root:
938 tmpl = os.path.join(root, "lsst_x.pc.in")
939 out = os.path.join(root, "lib", "pkgconfig", "lsst_x.pc")
940 with open(tmpl, "w") as f:
941 f.write("Name: lsst_x\nDescription: d\nVersion: 1\nCflags:\nLibs:\n")
943 with self.assertRaises(PkgConfigError) as cm:
944 write_pc_from_template(tmpl, out, "1")
945 self.assertIn(tmpl, str(cm.exception))
948@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
949class ShimTestCase(unittest.TestCase):
950 """Tests for `write_shims` and the console script `main`."""
952 def setUp(self):
953 self._tmpdir = tempfile.TemporaryDirectory()
954 self.addCleanup(self._tmpdir.cleanup)
955 self.target = os.path.join(self._tmpdir.name, "shims")
957 def _pkg_config(self, *args):
958 """Run the real pkg-config implementation with no
959 ``--define-variable``, so that a shim's own ``conda_prefix`` default
960 is exercised."""
961 env = dict(os.environ)
962 env["PKG_CONFIG_PATH"] = self.target
963 return subprocess.run(
964 [_EXECUTABLE, *args], env=env, capture_output=True, text=True, check=True
965 ).stdout
967 def _cflags(self, module):
968 return self._pkg_config("--cflags", module)
970 def _libs(self, module):
971 return self._pkg_config("--libs", module)
973 def _variable(self, module, name):
974 return self._pkg_config(f"--variable={name}", module).strip()
976 def test_static_shims_resolve_from_copy(self):
977 written = write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
978 for name in (
979 "boost",
980 "boost_test",
981 "boost_timer",
982 "boost_math",
983 "boost_regex",
984 "boost_filesystem",
985 "boost_system",
986 "boost_thread",
987 "boost_program_options",
988 "boost_serialization",
989 "minuit2",
990 "ndarray",
991 ):
992 self.assertIn(os.path.join(self.target, f"{name}.pc"), written)
994 self.assertEqual(self._cflags("minuit2").split(), ["-I" + self.target + "/../../include/Minuit2"])
995 # boost_test.pc itself has an empty Libs:, but it Requires: boost,
996 # and pkg-config propagates a required module's Libs, so the
997 # effective link line still carries boost's own -lpthread.
998 self.assertEqual(self._libs("boost_test").strip(), "-lpthread")
999 self.assertEqual(self._variable("boost_test", "lsst_test_libs"), "-lboost_unit_test_framework")
1000 self.assertEqual(self._libs("boost_math").split(), ["-lboost_math_c99", "-lpthread"])
1001 self.assertEqual(self._libs("boost").strip(), "-lpthread")
1003 # ndarray links both the double and single precision FFTW
1004 # libraries, as configs/fftw.cfg does.
1005 for name, libs in (("numpy", ""), ("eigen3", ""), ("fftw3", "-lfftw3"), ("fftw3f", "-lfftw3f")):
1006 write_pc(self.target, name, f"Name: {name}\nDescription: x\nVersion: 1\nCflags:\nLibs: {libs}\n")
1007 self.assertEqual(self._libs("ndarray").split(), ["-lpthread", "-lfftw3", "-lfftw3f"])
1009 @unittest.skipUnless(_python_has_numpy(), "the python on PATH cannot import numpy")
1010 def test_generated_numpy(self):
1011 written = write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
1012 self.assertIn(os.path.join(self.target, "numpy.pc"), written)
1013 inc = (
1014 subprocess.check_output(["python", "-c", "import numpy; print(numpy.get_include())"])
1015 .decode()
1016 .strip()
1017 )
1018 self.assertEqual(PkgConfig([self.target], "/c").cflags_only_I(["numpy"]), [inc])
1020 @unittest.skipUnless(shutil.which("ast_link"), "ast_link is not available on PATH")
1021 @unittest.skipUnless(os.environ.get("CONDA_PREFIX"), "CONDA_PREFIX is not set")
1022 def test_generated_starlink_ast(self):
1023 written = write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
1024 self.assertIn(os.path.join(self.target, "starlink_ast.pc"), written)
1025 conda_prefix = os.environ["CONDA_PREFIX"]
1026 self.assertEqual(
1027 PkgConfig([self.target], conda_prefix).cflags_only_I(["starlink_ast"]),
1028 [os.path.join(conda_prefix, "include", "star")],
1029 )
1031 def test_rewrite_leaves_unchanged_file_untouched(self):
1032 write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
1033 boost_pc = os.path.join(self.target, "boost.pc")
1034 mtime_after_first_write = os.path.getmtime(boost_pc)
1036 write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
1037 self.assertEqual(os.path.getmtime(boost_pc), mtime_after_first_write)
1039 def test_rewrite_replaces_changed_file(self):
1040 write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
1041 boost_pc = os.path.join(self.target, "boost.pc")
1042 with open(boost_pc, "w") as f:
1043 f.write("stale\n")
1044 write_shims(self.target, static_dir=_STATIC_SHIM_DIR)
1045 with open(boost_pc) as f, open(os.path.join(_STATIC_SHIM_DIR, "boost.pc")) as g:
1046 self.assertEqual(f.read(), g.read())
1048 def test_static_shims_are_installed_with_the_module(self):
1049 # Wherever sconsUtils is installed from, with or without
1050 # SCONSUTILS_DIR, the static shims are found next to the module.
1051 with mock.patch.dict(os.environ):
1052 os.environ.pop("SCONSUTILS_DIR", None)
1053 self.assertEqual(
1054 pkgconfig.static_shim_dir(),
1055 os.path.join(os.path.dirname(os.path.abspath(pkgconfig.__file__)), "pkgconfig_shims"),
1056 )
1057 written = write_shims(self.target)
1058 self.assertIn(os.path.join(self.target, "boost.pc"), written)
1060 def _write_shims_with_stubs(self, python_script, ast_link_script=None):
1061 """Run `write_shims` with only stub ``python`` and (optionally)
1062 ``ast_link`` scripts on ``PATH``, and return what it skipped."""
1063 stub_dir = os.path.join(self._tmpdir.name, "bin")
1064 os.makedirs(stub_dir)
1065 write_stub_python(stub_dir, python_script)
1066 if ast_link_script is not None:
1067 path = os.path.join(stub_dir, "ast_link")
1068 with open(path, "w") as f:
1069 f.write(ast_link_script + "\n")
1070 os.chmod(path, os.stat(path).st_mode | stat.S_IXUSR)
1071 skipped = []
1072 with mock.patch.dict(os.environ, {"PATH": stub_dir + os.pathsep + "/bin" + os.pathsep + "/usr/bin"}):
1073 written = write_shims(self.target, static_dir=None, skipped=skipped)
1074 return written, skipped
1076 def test_unexpected_python_output_is_skipped(self):
1077 written, skipped = self._write_shims_with_stubs("echo 1.0")
1078 self.assertNotIn(os.path.join(self.target, "numpy.pc"), written)
1079 self.assertIn("unexpected output from the python on PATH", skipped[0])
1081 def test_failing_ast_link_is_skipped(self):
1082 written, skipped = self._write_shims_with_stubs("exit 1", "exit 1")
1083 self.assertNotIn(os.path.join(self.target, "starlink_ast.pc"), written)
1084 self.assertIn("starlink_ast.pc", skipped[1])
1085 self.assertIn("failed", skipped[1])
1087 def test_stub_ast_link(self):
1088 written, skipped = self._write_shims_with_stubs("exit 1", "echo -last -lerfa")
1089 shim = os.path.join(self.target, "starlink_ast.pc")
1090 self.assertIn(shim, written)
1091 self.assertEqual(len(skipped), 1)
1092 pc = PkgConfig([self.target], "/opt/conda")
1093 self.assertEqual(pc.cflags_only_I(["starlink_ast"]), ["/opt/conda/include/star"])
1094 self.assertEqual(pc.libs_only_l(["starlink_ast"]), ["ast", "erfa"])
1096 def test_no_static_dir_copies_nothing(self):
1097 # If the static shims are missing from the installation and no
1098 # static_dir is passed explicitly, nothing is copied.
1099 with mock.patch.object(pkgconfig, "static_shim_dir", return_value=None):
1100 written = write_shims(self.target, static_dir=None)
1101 self.assertFalse(os.path.exists(os.path.join(self.target, "boost.pc")))
1102 # numpy is still generated if it can be, since it does not depend
1103 # on static_dir.
1104 if _python_has_numpy(): 1104 ↛ 1107line 1104 didn't jump to line 1107 because the condition on line 1104 was always true
1105 self.assertIn(os.path.join(self.target, "numpy.pc"), written)
1106 else:
1107 self.assertNotIn(os.path.join(self.target, "numpy.pc"), written)
1109 def test_skipped_generated_shims_are_reported(self):
1110 # A python that cannot import numpy, and no ast_link, on PATH.
1111 stub_dir = os.path.join(self._tmpdir.name, "bin")
1112 os.makedirs(stub_dir)
1113 write_stub_python(stub_dir, "exit 1")
1114 skipped = []
1115 with mock.patch.dict(os.environ, {"PATH": stub_dir}):
1116 written = write_shims(self.target, static_dir=_STATIC_SHIM_DIR, skipped=skipped)
1117 self.assertNotIn(os.path.join(self.target, "numpy.pc"), written)
1118 self.assertNotIn(os.path.join(self.target, "starlink_ast.pc"), written)
1119 self.assertEqual(len(skipped), 2)
1120 self.assertIn("numpy.pc", skipped[0])
1121 self.assertIn("numpy is not importable", skipped[0])
1122 self.assertIn("starlink_ast.pc", skipped[1])
1123 self.assertIn("ast_link was not found", skipped[1])
1125 def test_console_script(self):
1126 # As after a pip install: no SCONSUTILS_DIR, and a python that
1127 # cannot import numpy and no ast_link on PATH.
1128 stub_dir = os.path.join(self._tmpdir.name, "bin")
1129 os.makedirs(stub_dir)
1130 write_stub_python(stub_dir, "exit 1")
1131 with mock.patch.dict(os.environ, {"PATH": stub_dir}):
1132 os.environ.pop("SCONSUTILS_DIR", None)
1133 with (
1134 contextlib.redirect_stdout(io.StringIO()) as stdout,
1135 contextlib.redirect_stderr(io.StringIO()) as stderr,
1136 ):
1137 self.assertEqual(main([self.target]), 0)
1138 self.assertTrue(os.path.exists(os.path.join(self.target, "boost.pc")))
1139 self.assertEqual(stdout.getvalue(), "")
1140 # Skipped shims are not an error, but are reported.
1141 self.assertIn("Not writing pkg-config shim numpy.pc: numpy is not importable", stderr.getvalue())
1142 self.assertIn("Not writing pkg-config shim starlink_ast.pc", stderr.getvalue())
1144 def test_console_script_without_static_shims_fails(self):
1145 with (
1146 mock.patch.object(pkgconfig, "static_shim_dir", return_value=None),
1147 contextlib.redirect_stderr(io.StringIO()) as stderr,
1148 ):
1149 self.assertEqual(main([self.target]), 1)
1150 self.assertIn("static pkg-config shims are not installed", stderr.getvalue())
1151 self.assertFalse(os.path.exists(self.target))
1154def make_resolved() -> ResolvedDependencies:
1155 """Return a small `ResolvedDependencies` for environment tests."""
1156 return ResolvedDependencies(
1157 modules=["lsst_m"],
1158 cpppath=["/a"],
1159 xcpppath=["/b"],
1160 ccflags=["-DX"],
1161 libpath=["/l"],
1162 linkflags=["-Wl,-z"],
1163 libs={"main": ["m"], "python": [], "test": ["t"]},
1164 doxygen={"tags": [], "includes": []},
1165 versions={"m": "1"},
1166 )
1169class ApplyToEnvTestCase(unittest.TestCase):
1170 """Tests for `apply_to_env`."""
1172 def test_apply(self):
1173 env = SCons.Environment.Environment(tools=[])
1174 env["CPPPATH"] = ["/already"]
1175 env["XCPPPATH"] = []
1176 env["LIBPATH"] = []
1177 resolved = make_resolved()
1178 apply_to_env(env, resolved)
1179 self.assertEqual(env["CPPPATH"], ["/a", "/already"])
1180 self.assertEqual(env["XCPPPATH"], ["/b"])
1181 self.assertEqual(env["LIBPATH"], ["/l"])
1182 self.assertEqual(env["CCFLAGS"], ["-DX"])
1183 self.assertEqual(env["LINKFLAGS"], ["-Wl,-z"])
1184 self.assertEqual(env.libs, {"main": ["m"], "python": [], "test": ["t"]})
1185 self.assertEqual(env.doxygen, {"tags": [], "includes": []})
1186 # The environment gets its own copies of the library lists.
1187 env.libs["main"].append("extra")
1188 self.assertEqual(resolved.libs["main"], ["m"])
1191class PkgConfigDependenciesTestCase(unittest.TestCase):
1192 """Tests for `PkgConfigDependencies`."""
1194 def test_versions(self):
1195 resolved = make_resolved()
1196 d = PkgConfigDependencies("afw", resolved)
1197 self.assertEqual(d.name, "afw")
1198 self.assertIs(d.resolved, resolved)
1199 self.assertEqual(d.versions, {"m": "1"})
1201 def test_versions_exclude_package_itself(self):
1202 # As with PackageTree.versions, the package being built is not one
1203 # of its own dependencies.
1204 resolved = make_resolved()
1205 resolved.versions = {"m": "1", "base": "2", "eigen3": "3.4"}
1206 d = PkgConfigDependencies("m", resolved)
1207 self.assertEqual(d.versions, {"base": "2", "eigen3": "3.4"})
1208 self.assertEqual(resolved.versions, {"m": "1", "base": "2", "eigen3": "3.4"})
1211@unittest.skipUnless(_EXECUTABLE, "neither pkgconf nor pkg-config is available on PATH")
1212class PackageTreeFallbackTestCase(unittest.TestCase):
1213 """Tests for the pkg-config fallback of
1214 `lsst.sconsUtils.dependencies.PackageTree`."""
1216 def setUp(self):
1217 self._tmpdir = tempfile.TemporaryDirectory()
1218 self.addCleanup(self._tmpdir.cleanup)
1219 tmp = os.path.realpath(self._tmpdir.name)
1220 self.root = os.path.join(tmp, "root")
1221 self.cfgdir = os.path.join(tmp, "ups")
1222 self.pcdir = os.path.join(tmp, "pkgconfig")
1223 self.conda = os.path.join(tmp, "conda")
1224 self.numpy_inc = os.path.join(tmp, "numpy", "include")
1225 stub_dir = os.path.join(tmp, "bin")
1226 for directory in (self.root, self.cfgdir, self.pcdir, self.conda, self.numpy_inc, stub_dir):
1227 os.makedirs(directory)
1228 # A converted package whose closure reaches numpy, which only has
1229 # a configure-time generated shim.
1230 write_pc(
1231 self.pcdir,
1232 "lsst_conv",
1233 "Name: lsst_conv\nDescription: x\nVersion: 1.0\nRequires: numpy\nCflags:\nLibs: -lconv\n",
1234 )
1235 # Stand in for a python that can import numpy, so this test does
1236 # not need numpy itself.
1237 write_stub_python(stub_dir, f"echo 1.99; echo {self.numpy_inc}")
1238 environ = {
1239 "PATH": stub_dir + os.pathsep + os.environ.get("PATH", ""),
1240 "PKG_CONFIG_PATH": self.pcdir,
1241 "CONDA_PREFIX": self.conda,
1242 }
1243 stack = contextlib.ExitStack()
1244 self.addCleanup(stack.close)
1245 stack.enter_context(mock.patch.dict(os.environ, environ))
1246 stack.enter_context(
1247 mock.patch.object(
1248 dependencies.SCons.Script, "Dir", lambda _: types.SimpleNamespace(abspath=self.root)
1249 )
1250 )
1251 stack.enter_context(mock.patch.object(state.env, "cfgPath", [self.cfgdir], create=True))
1252 stack.enter_context(mock.patch.object(state.log, "traceback", False))
1253 self.stdout = stack.enter_context(contextlib.redirect_stdout(io.StringIO()))
1254 self.stderr = stack.enter_context(contextlib.redirect_stderr(io.StringIO()))
1256 def _make_tree(self):
1257 """Return a `PackageTree` with no packages loaded yet."""
1258 tree = dependencies.PackageTree("prim", noCfgFile=True)
1259 tree._current = set()
1260 return tree
1262 def test_fallback_writes_generated_shims(self):
1263 tree = self._make_tree()
1264 module = tree._tryImport("conv")
1265 self.assertIsNotNone(module)
1266 self.assertTrue(os.path.exists(os.path.join(self.root, GENERATED_SHIM_SUBDIR, "numpy.pc")))
1267 self.assertEqual(module.config.paths["XCPPPATH"], [self.numpy_inc])
1268 self.assertEqual(module.config.libs["main"], ["conv"])
1269 self.assertEqual(module.config.version, "1.0")
1270 # The pkg-config executable is logged once, however many packages
1271 # fall back to pkg-config.
1272 tree._tryImport("conv")
1273 self.assertEqual(self.stdout.getvalue().count("Using pkg-config at"), 1)
1275 def test_fallback_without_runner(self):
1276 os.environ.pop("CONDA_PREFIX")
1277 tree = self._make_tree()
1278 self.assertIsNone(tree._tryImport("conv"))
1279 self.assertIsNone(tree._tryImport("conv"))
1280 # The reason is logged once, and construction is not retried.
1281 self.assertEqual(self.stdout.getvalue().count("Not looking for pkg-config modules"), 1)
1282 self.assertIn("CONDA_PREFIX is not set", self.stdout.getvalue())
1284 def test_fallback_shim_write_failure_fails(self):
1285 with (
1286 mock.patch.object(dependencies, "_writeShims", side_effect=OSError("disk full")),
1287 self.assertRaises(SystemExit),
1288 ):
1289 self._make_tree()._tryImport("conv")
1290 self.assertIn("disk full", self.stderr.getvalue())
1292 def test_fallback_broken_module_fails(self):
1293 write_pc(
1294 self.pcdir,
1295 "lsst_broken",
1296 "Name: lsst_broken\nDescription: x\nVersion: 1.0\nRequires: lsst_gone\nCflags:\nLibs:\n",
1297 )
1298 with self.assertRaises(SystemExit):
1299 self._make_tree()._tryImport("broken")
1300 self.assertIn("lsst_gone", self.stderr.getvalue())
1302 def test_skipped_shims_are_logged(self):
1303 def write_shims(directory, skipped):
1304 skipped.append("Not writing pkg-config shim numpy.pc: no numpy")
1306 with mock.patch.object(dependencies.pkgconfig, "write_shims", side_effect=write_shims):
1307 dependencies._writeShims(self.root)
1308 self.assertIn("Not writing pkg-config shim numpy.pc: no numpy.", self.stdout.getvalue())
1310 def test_failed_configuration_check_fails(self):
1311 tree = self._make_tree()
1312 tree.primary = None
1313 tree.packages["bad"] = types.SimpleNamespace(
1314 config=types.SimpleNamespace(configure=lambda conf, packages, build: False)
1315 )
1316 env = mock.Mock(libs={})
1317 with self.assertRaises(SystemExit):
1318 tree.configure(env)
1319 self.assertIn("bad was found but did not pass configuration checks", self.stderr.getvalue())
1321 def test_closure_of_fallback_is_listed(self):
1322 tree = self._make_tree()
1323 tree.primary = types.SimpleNamespace(config=types.SimpleNamespace(name="prim"))
1324 # An optional package not found on its own, but in the closure.
1325 tree.packages["numpy"] = None
1326 self.assertTrue(tree._recurse("conv"))
1327 self.assertIn("numpy", tree)
1328 self.assertEqual(tree["numpy"].config.version, "1.99")
1329 self.assertEqual(tree.versions, {"numpy": "1.99", "conv": "1.0"})
1330 # numpy is configured as part of conv, not on its own.
1331 self.assertEqual(list(tree.packages), ["numpy", "conv"])
1332 self.assertIsNone(tree.packages["numpy"])
1334 def test_absent_optional_package_writes_no_shims(self):
1335 self.assertIsNone(self._make_tree()._tryImport("absent"))
1336 self.assertFalse(os.path.exists(os.path.join(self.root, GENERATED_SHIM_SUBDIR)))
1338 def test_clean_and_help_do_not_resolve(self):
1339 # A present but broken module would fail to resolve.
1340 write_pc(
1341 self.pcdir,
1342 "lsst_broken",
1343 "Name: lsst_broken\nDescription: x\nVersion: 1.0\nRequires: lsst_gone\nCflags:\nLibs:\n",
1344 )
1345 for option in ("clean", "help"):
1346 with (
1347 self.subTest(option=option),
1348 mock.patch.object(state.env, "GetOption", lambda name, option=option: name == option),
1349 ):
1350 tree = self._make_tree()
1351 module = tree._tryImport("broken")
1352 self.assertEqual(module.config.name, "broken")
1353 self.assertEqual(module.dependencies, {})
1354 tree.packages["broken"] = module
1355 self.assertEqual(tree.versions, {"broken": "unknown"})
1356 self.assertFalse(os.path.exists(os.path.join(self.root, GENERATED_SHIM_SUBDIR)))
1357 self.assertIsNone(tree._tryImport("absent"))
1359 def test_fallback_not_used_for_primary(self):
1360 write_pc(self.pcdir, "lsst_prim", "Name: lsst_prim\nDescription: x\nVersion: 1.0\nCflags:\nLibs:\n")
1361 with self.assertRaises(SystemExit):
1362 dependencies.PackageTree("prim")
1363 self.assertIn("Failed to load primary package configuration for prim", self.stderr.getvalue())
1364 self.assertFalse(os.path.exists(os.path.join(self.root, GENERATED_SHIM_SUBDIR)))
1365 # As a dependency, the same module is used.
1366 self.assertIsNotNone(self._make_tree()._tryImport("prim"))
1369class ConfigurePkgConfigTestCase(unittest.TestCase):
1370 """Tests for `lsst.sconsUtils.dependencies._configurePkgConfig`."""
1372 def test_resolution_failure_fails(self):
1373 with tempfile.TemporaryDirectory() as root:
1374 with open(template_path(root, "absent"), "w") as f:
1375 f.write("Name: lsst_absent\nDescription: x\nVersion: @VERSION@\nRequires: lsst_gone\n")
1376 env = mock.MagicMock(GetOption=lambda name: None)
1377 env.__getitem__.side_effect = {"version": "1.0"}.__getitem__
1378 with (
1379 mock.patch.dict(os.environ, {"CONDA_PREFIX": root}),
1380 mock.patch.object(state, "env", env),
1381 mock.patch.object(state.log, "traceback", False),
1382 contextlib.redirect_stdout(io.StringIO()),
1383 contextlib.redirect_stderr(io.StringIO()) as stderr,
1384 self.assertRaises(SystemExit),
1385 ):
1386 dependencies._configurePkgConfig(root, "absent")
1387 self.assertTrue(os.path.exists(output_path(root, "absent")))
1388 # lsst_absent itself is written, but its requirement is missing.
1389 self.assertIn("lsst_absent", stderr.getvalue())
1392class VersionModuleTestCase(unittest.TestCase):
1393 """Tests for the ``__dependency_versions__`` written by
1394 `~lsst.sconsUtils.builders.VersionModule`."""
1396 def test_dependency_versions(self):
1397 for versions, expected in (
1398 ({"base": "1.0", "gone": None}, "{\n 'base': '1.0',\n 'gone': None,\n}\n"),
1399 # A pkg-config Version field is free text.
1400 ({"odd": 'a"b\\c'}, "{\n 'odd': 'a\"b\\\\c',\n}\n"),
1401 ({}, "{}\n"),
1402 ):
1403 with self.subTest(versions=versions), tempfile.TemporaryDirectory() as d:
1404 env = SCons.Environment.Environment(tools=[])
1405 env.dependencies = types.SimpleNamespace(versions=versions)
1406 output = os.path.join(d, "version.py")
1407 node = env.VersionModule(output, versionString="git")[0]
1408 with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
1409 node.get_builder().action.execfunction(target=[node], source=[], env=env)
1410 with open(output) as f:
1411 contents = f.read()
1412 self.assertIn("__dependency_versions__: dict[str, str | None] = " + expected, contents)
1413 namespace = {}
1414 exec(contents, namespace)
1415 self.assertEqual(namespace["__dependency_versions__"], versions)
1418class RemovesGeneratedPcTestCase(unittest.TestCase):
1419 """Tests for when ``scons --clean`` removes the generated ``.pc``."""
1421 @staticmethod
1422 def _env(**options):
1423 return types.SimpleNamespace(GetOption=lambda name: options.get(name))
1425 def test_conditions(self):
1426 removes = dependencies._removesGeneratedPc
1427 self.assertTrue(removes(self._env(clean=True), []))
1428 self.assertFalse(removes(self._env(clean=True), ["install"]))
1429 self.assertFalse(removes(self._env(clean=True, no_exec=True), []))
1430 self.assertFalse(removes(self._env(help=True), []))
1431 self.assertFalse(removes(self._env(), []))
1434class RemoveGeneratedPcTestCase(unittest.TestCase):
1435 """Tests for `remove_generated_pc`."""
1437 def setUp(self):
1438 self._tmpdir = tempfile.TemporaryDirectory()
1439 self.addCleanup(self._tmpdir.cleanup)
1440 self.root = self._tmpdir.name
1441 self.output = output_path(self.root, "afw")
1442 self.pcdir = os.path.dirname(self.output)
1444 def test_removes_file_and_empty_directory(self):
1445 os.makedirs(self.pcdir)
1446 with open(self.output, "w") as f:
1447 f.write("x")
1448 self.assertTrue(remove_generated_pc(self.root, "afw"))
1449 self.assertFalse(os.path.exists(self.output))
1450 self.assertFalse(os.path.exists(self.pcdir))
1451 # lib/ itself is left alone.
1452 self.assertTrue(os.path.isdir(os.path.join(self.root, "lib")))
1454 def test_keeps_non_empty_directory(self):
1455 os.makedirs(self.pcdir)
1456 with open(self.output, "w") as f:
1457 f.write("x")
1458 other = os.path.join(self.pcdir, "other.pc")
1459 with open(other, "w") as f:
1460 f.write("y")
1461 self.assertTrue(remove_generated_pc(self.root, "afw"))
1462 self.assertFalse(os.path.exists(self.output))
1463 self.assertTrue(os.path.exists(other))
1465 def test_missing_file(self):
1466 self.assertFalse(remove_generated_pc(self.root, "afw"))
1467 os.makedirs(self.pcdir)
1468 self.assertFalse(remove_generated_pc(self.root, "afw"))
1469 # An empty directory not holding our file is left alone.
1470 self.assertTrue(os.path.isdir(self.pcdir))
1473if __name__ == "__main__":
1474 unittest.main()