Coverage for python/lsst/sconsUtils/scripts.py: 59%
256 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"""Convenience functions to do the work of standard LSST SConstruct/SConscript
23files.
24"""
26import glob
27import os.path
28import re
29import shlex
30import shutil
31import warnings
32from stat import ST_MODE
34from SCons.Script import BUILD_TARGETS, Dir, GetOption, Glob, SConscript
36from . import dependencies, state, tests, utils
38DEFAULT_TARGETS = ("lib", "python", "shebang", "tests", "examples", "doc")
41class BasicSConstruct:
42 """A scope-only class for SConstruct-replacement convenience functions.
44 The boilerplate for a standard LSST SConstruct file is replaced by two
45 static methods: ``initialize()`` and ``finish()``. The former configures
46 dependencies, sets up package-dependent environment variables, and calls
47 any SConscript files found in subdirectories, while the latter sets up
48 installation paths, default targets, and explicit dependencies.
50 Calling ``BasicSConstruct`` as a function invokes its ``__new__`` method,
51 which calls both `~lsst.sconsUtils.BasicSConstruct.initialize` and
52 `~lsst.sconsUtils.BasicSConstruct.finish`, and should be used when the
53 SConstruct file doesn't need to do anything other than what they provide.
54 When called this way it returns the `~lsst.sconsUtils.env` Environment
55 object rather than a `~lsst.sconsUtils.scripts.BasicSConstruct` instance
56 (which would be useless).
57 """
59 _initializing = False
61 def __new__(
62 cls,
63 packageName,
64 versionString=None,
65 eupsProduct=None,
66 eupsProductPath=None,
67 cleanExt=None,
68 defaultTargets=DEFAULT_TARGETS,
69 subDirList=None,
70 ignoreRegex=None,
71 versionModuleName="python/lsst/%s/version.py",
72 noCfgFile=False,
73 sconscriptOrder=None,
74 disableCc=False,
75 ):
76 cls.initialize(
77 packageName,
78 versionString,
79 eupsProduct,
80 eupsProductPath,
81 cleanExt,
82 versionModuleName,
83 noCfgFile=noCfgFile,
84 sconscriptOrder=sconscriptOrder,
85 disableCc=disableCc,
86 )
87 cls.finish(defaultTargets, subDirList, ignoreRegex)
88 return state.env
90 @classmethod
91 def initialize(
92 cls,
93 packageName,
94 versionString=None,
95 eupsProduct=None,
96 eupsProductPath=None,
97 cleanExt=None,
98 versionModuleName="python/lsst/%s/version.py",
99 noCfgFile=False,
100 sconscriptOrder=None,
101 disableCc=False,
102 ):
103 """Convenience function to replace standard SConstruct boilerplate
104 (step 1).
106 This function:
108 - Calls all SConscript files found in subdirectories.
109 - Configures dependencies.
110 - Sets how the ``--clean`` option works.
112 Parameters
113 ----------
114 packageName : `str`
115 Name of the package being built; must correspond to a .cfg
116 file in ``ups/``.
117 versionString : `str`, optional
118 Version-control system string to be parsed for version information
119 (``$HeadURL$`` for SVN). Defaults to "git" if not set or `None`.
120 eupsProduct : `str`, optional
121 Name of the EUPS product being built. Defaults to and is almost
122 always the name of the package.
123 eupsProductPath : `str`, optional
124 An alternate directory where the package should be installed.
125 cleanExt : `list`, optional
126 Whitespace delimited sequence of globs for files to remove with
127 ``--clean``.
128 versionModuleName : `str`, optional
129 If non-None, builds a ``version.py`` module as this file; ``'%s'``
130 is replaced with the name of the package.
131 noCfgFile : `bool`, optional
132 If True, this package has no .cfg file
133 sconscriptOrder : `list`, optional
134 A sequence of directory names that set the order for processing
135 SConscript files discovered in nested directories. Full
136 directories need not be specified, but paths must begin at the
137 root. For example, ``["lib", "python"]`` will ensure that
138 ``lib/SConscript`` is run before both ``python/foo/SConscript``
139 and ``python/bar/SConscript``. The default order should work for
140 most LSST SCons builds, as it provides the correct ordering for
141 the ``lib``, ``python``, ``tests``, ``examples``, and ``doc``
142 targets. If this argument is provided, it must include the subset
143 of that list that is valid for the package, in that order.
144 disableCC : `bool`, optional
145 Should the C++ compiler check be disabled? Disabling this checks
146 allows a faster startup and permits building on systems that don't
147 meet the requirements for the C++ compiler (e.g., for
148 pure-python packages).
150 Returns
151 -------
152 env : `lsst.sconsUtils.env`
153 A SCons Environment object.
154 """
155 if not disableCc: 155 ↛ 158line 155 didn't jump to line 158 because the condition on line 155 was always true
156 state._configureCommon()
157 state._saveState()
158 if cls._initializing: 158 ↛ 159line 158 didn't jump to line 159 because the condition on line 158 was never true
159 state.log.fail("Recursion detected; an SConscript file should not call BasicSConstruct.")
160 cls._initializing = True
161 dependencies.configure(packageName, versionString, eupsProduct, eupsProductPath, noCfgFile)
162 state.env.BuildETags()
163 if cleanExt is None: 163 ↛ 165line 163 didn't jump to line 165 because the condition on line 163 was always true
164 cleanExt = r"*~ core core.[1-9]* *.so *.os *.o *.pyc *.pkgc"
165 state.env.CleanTree(cleanExt, "__pycache__ .pytest_cache *.dist-info")
166 if versionModuleName is not None:
167 try:
168 versionModuleName = versionModuleName % "/".join(packageName.split("_"))
169 except TypeError:
170 pass
171 state.targets["version"] = state.env.VersionModule(versionModuleName)
172 # Always attempt to write python package info into the python
173 # directory.
174 if os.path.exists("python"):
175 state.targets["pkginfo"] = state.env.PackageInfo("python")
176 # Python script generation does no harm since it will only do anything
177 # if there is a scripts entry in pyproject.toml.
178 state.targets["scripts"] = state.env.PythonScripts()
179 scripts = []
180 for root, dirs, files in os.walk("."):
181 if "SConstruct" in files and root != ".": 181 ↛ 182line 181 didn't jump to line 182 because the condition on line 181 was never true
182 dirs[:] = []
183 continue
184 dirs[:] = [d for d in dirs if not d.startswith(".")]
185 dirs.sort() # os.walk order is not specified, but we want builds to be deterministic
186 if "SConscript" in files:
187 scripts.append(os.path.join(root, "SConscript"))
188 if sconscriptOrder is None: 188 ↛ 192line 188 didn't jump to line 192 because the condition on line 188 was always true
189 sconscriptOrder = DEFAULT_TARGETS
191 # directory for shebang target is bin.src
192 sconscriptOrder = [t if t != "shebang" else "bin.src" for t in sconscriptOrder]
194 def key(path):
195 for i, item in enumerate(sconscriptOrder): 195 ↛ 198line 195 didn't jump to line 198 because the loop on line 195 didn't complete
196 if path.lstrip("./").startswith(item):
197 return i
198 return len(sconscriptOrder)
200 scripts.sort(key=key)
201 for script in scripts:
202 state.log.info(f"Using SConscript at {script}")
203 SConscript(script)
204 cls._initializing = False
205 return state.env
207 @staticmethod
208 def finish(defaultTargets=DEFAULT_TARGETS, subDirList=None, ignoreRegex=None):
209 """Convenience function to replace standard SConstruct boilerplate
210 (step 2).
212 This function:
214 - Sets up installation paths.
215 - Tells SCons to only do MD5 checks when timestamps have changed.
216 - Sets the "include", "lib", "python", and "tests" targets as the
217 defaults to be built when scons is run with no target arguments.
219 Parameters
220 ----------
221 subDirList : `list`
222 An explicit list of subdirectories that should be installed.
223 By default, all non-hidden subdirectories will be installed.
224 defaultTargets : `list`
225 A sequence of targets (see `lsst.sconsUtils.state.targets`)
226 that should be built when scons is run with no arguments.
227 ignoreRegex : `str`
228 Regular expression that matches files that should not be installed.
230 Returns
231 -------
232 env : `lsst.sconsUtils.env`
233 A SCons Environment.
234 """
235 if ignoreRegex is None: 235 ↛ 237line 235 didn't jump to line 237 because the condition on line 235 was always true
236 ignoreRegex = r"(~$|\.pyc$|^\.svn$|\.o|\.os$)"
237 if subDirList is None: 237 ↛ 242line 237 didn't jump to line 242 because the condition on line 237 was always true
238 subDirList = []
239 for path in os.listdir("."):
240 if os.path.isdir(path) and not path.startswith("."):
241 subDirList.append(path)
242 if "bin.src" in subDirList and "shebang" in state.targets and state.targets["shebang"]: 242 ↛ 244line 242 didn't jump to line 244 because the condition on line 242 was never true
243 # shebang makes a directory that should be installed
244 subDirList += ["bin"]
245 install = state.env.InstallLSST(state.env["prefix"], list(subDirList), ignoreRegex=ignoreRegex)
246 for name, target in state.targets.items():
247 state.env.Requires(install, target)
248 state.env.Alias(name, target)
249 state.env.Requires(state.targets["python"], state.targets["version"])
250 declarer = state.env.Declare()
251 state.env.Requires(declarer, install) # Ensure declaration fires after installation available
253 # shebang should be in the list if bin.src exists but the location
254 # matters so we can not append it afterwards.
255 state.env.Default(
256 [t for t in defaultTargets if os.path.exists(t) or (t == "shebang" and os.path.exists("bin.src"))]
257 )
258 if "version" in state.targets: 258 ↛ 261line 258 didn't jump to line 261 because the condition on line 258 was always true
259 state.env.Default(state.targets["version"])
260 state.env.Requires(state.targets["tests"], state.targets["version"])
261 if "pkginfo" in state.targets: 261 ↛ 265line 261 didn't jump to line 265 because the condition on line 261 was always true
262 state.env.Default(state.targets["pkginfo"])
263 state.env.Requires(state.targets["pkginfo"], state.targets["python"])
264 state.env.Requires(state.targets["tests"], state.targets["pkginfo"])
265 if "scripts" in state.targets: 265 ↛ 269line 265 didn't jump to line 269 because the condition on line 265 was always true
266 state.env.Default(state.targets["scripts"])
267 state.env.Requires(state.targets["tests"], state.targets["scripts"])
269 state.env.Decider("MD5-timestamp") # if timestamps haven't changed, don't do MD5 checks
270 #
271 # Check if any of the tests failed by looking for *.failed files.
272 # Perform this test just before scons exits
273 #
274 # N.b. the test is written in sh not python as then we can use @ to
275 # suppress output
276 #
277 if "tests" in [str(t) for t in BUILD_TARGETS]:
278 testsDir = shlex.quote(os.path.join(os.getcwd(), "tests", ".tests"))
279 checkTestStatus_command = state.env.Command(
280 "checkTestStatus",
281 [],
282 f"""
283 @ if [ -d {testsDir} ]; then \
284 nfail=`find {testsDir} -name "*.failed" | wc -l | sed -e 's/ //g'`; \
285 if [ $$nfail -gt 0 ]; then \
286 echo "Failed test output:" >&2; \
287 for f in `find {testsDir} -name "*.failed"`; do \
288 case "$$f" in \
289 *.xml.failed) \
290 echo "Global pytest output is in $$f" >&2; \
291 ;; \
292 *.failed) \
293 cat $$f >&2; \
294 ;; \
295 esac; \
296 done; \
297 echo "The following tests failed:" >&2;\
298 find {testsDir} -name "*.failed" >&2; \
299 echo "$$nfail tests failed" >&2; exit 1; \
300 fi; \
301 fi; \
302 """,
303 )
305 state.env.Depends(checkTestStatus_command, BUILD_TARGETS) # this is why the check runs last
306 BUILD_TARGETS.extend(checkTestStatus_command)
307 state.env.AlwaysBuild(checkTestStatus_command)
310class BasicSConscript:
311 """A scope-only class for SConscript-replacement convenience functions.
313 All methods of `~lsst.sconsUtils.scripts.BasicSConscript` are static. All
314 of these functions update the `~lsst.sconsUtils.state.targets` dictionary
315 of targets used to set default targets and fix build dependencies; if you
316 build anything without using BasicSConscript methods, be sure to manually
317 add it to the `~lsst.sconsUtils.state.state.targets` `dict`.
318 """
320 @staticmethod
321 def lib(libName=None, src=None, libs="self", noBuildList=None):
322 """Convenience function to replace standard lib/SConscript boilerplate.
324 With no arguments, this will build a shared library with the same name
325 as the package. This uses
326 `lsst.sconsUtils.env.SourcesForSharedLibrary` to support the
327 ``optFiles``/``noOptFiles`` command-line variables.
329 Parameters
330 ----------
331 libName : `str`
332 Name of the shared libray to be built (defaults to
333 ``env["packageName"]``).
334 src : `str` or `~SCons.Script.Glob`
335 Source to compile into the library. Defaults to a 4-directory
336 deep glob of all ``*.cc`` files in ``#src``.
337 libs : `str` or `list`
338 Libraries to link against, either as a string argument to be
339 passed to `lsst.sconsUtils.env.getLibs` or a sequence of actual
340 libraries to pass in.
341 noBuildList : `list`
342 List of source files to exclude from building.
344 Returns
345 -------
346 result : ???
347 ???
348 """
349 if libName is None: 349 ↛ 351line 349 didn't jump to line 351 because the condition on line 349 was always true
350 libName = state.env["packageName"]
351 if src is None: 351 ↛ 353line 351 didn't jump to line 353 because the condition on line 351 was always true
352 src = Glob("#src/*.cc") + Glob("#src/*/*.cc") + Glob("#src/*/*/*.cc") + Glob("#src/*/*/*/*.cc")
353 if noBuildList is not None: 353 ↛ 354line 353 didn't jump to line 354 because the condition on line 353 was never true
354 src = [node for node in src if os.path.basename(str(node)) not in noBuildList]
355 src = state.env.SourcesForSharedLibrary(src)
356 if isinstance(libs, str): 356 ↛ 358line 356 didn't jump to line 358 because the condition on line 356 was always true
357 libs = state.env.getLibs(libs)
358 elif libs is None:
359 libs = []
360 result = state.env.SharedLibrary(libName, src, LIBS=libs)
361 state.targets["lib"].extend(result)
362 return result
364 @staticmethod
365 def shebang(src=None):
366 """Handles shebang rewriting.
368 With no arguments looks in ``bin.src/`` and copies to ``bin/``
369 If `~lsst.sconsUtils.utils.needShebangRewrite()` is `False` the
370 shebang will not be modified.
372 Only Python files requiring a shebang rewrite should be placed
373 in ``bin.src/``. Do not place executable binaries in this directory.
375 Parameters
376 ----------
377 src : `str` or `~SCons.Script.Glob`, optional
378 Glob to use to search for files.
379 """
380 # check if Python is called on the first line with this expression
381 # This comes from distutils copy_scripts
382 FIRST_LINE_RE = re.compile(r"^#!.*python[0-9.]*([ \t].*)?$")
383 doRewrite = utils.needShebangRewrite()
385 def rewrite_shebang(target, source, env):
386 """Copy source to target, rewriting the shebang"""
387 # Currently just use this python
388 usepython = utils.whichPython()
389 for targ, src in zip(target, source, strict=True):
390 with open(str(src)) as srcfd:
391 with open(str(targ), "w") as outfd:
392 first_line = srcfd.readline()
393 # Always match the first line so we can warn people
394 # if an attempt is being made to rewrite a file that
395 # should not be rewritten
396 match = FIRST_LINE_RE.match(first_line)
397 if match and doRewrite:
398 post_interp = match.group(1) or ""
399 # Paths can be long so ensure that flake8 won't
400 # complain
401 outfd.write(f"#!{usepython}{post_interp} # noqa\n")
402 else:
403 if not match:
404 state.log.warn(
405 f"Could not rewrite shebang of {src}. Please check"
406 " file or move it to bin directory."
407 )
408 outfd.write(first_line)
409 for line in srcfd.readlines():
410 outfd.write(line)
411 # Ensure the bin/ file is executable
412 oldmode = os.stat(str(targ))[ST_MODE] & 0o7777
413 newmode = (oldmode | 0o555) & 0o7777
414 if newmode != oldmode:
415 state.log.info(f"changing mode of {str(targ)} from {oldmode} to {newmode}")
416 os.chmod(str(targ), newmode)
418 if src is None:
419 # Ask the file system rather than SCons. Glob() reports every
420 # entry SCons knows about in a directory, including nodes that no
421 # file corresponds to, and only a file can be rewritten. Sort
422 # for a deterministic build.
423 src = sorted(glob.glob(os.path.join(Dir("#bin.src").abspath, "*")))
424 for s in src:
425 filename = os.path.basename(str(s))
426 # Do not try to rewrite files starting with non-letters
427 if filename != "SConscript" and re.match("[A-Za-z]", filename):
428 result = state.env.Command(
429 target=os.path.join(Dir("#bin").abspath, filename), source=s, action=rewrite_shebang
430 )
431 state.targets["shebang"].extend(result)
433 @staticmethod
434 def python(module=None, src=None, extra=(), libs="main python"):
435 """Convenience function to replace standard ``python/*/SConscript``
436 boilerplate.
438 With no arguments, this will build a pybind11 module with the name
439 determined according to our current pseudo-convention: last part of
440 ``env["packageName"]`` (split by underscores), with an underscore
441 prepended. All .cc files in the same directory will be linked into a
442 single module.
444 Parameters
445 ----------
446 module : `str`, optional
447 Name of the module to build (does not include the file extension).
448 Defaults to ``"_" + env["packageName"].split("_")[-1]``.
449 src : `list`, optional
450 A list of source files to build the module from; defaults to all
451 .cc files in the directory.
452 extra : `list`, optional
453 A list of additional source files to add to ``src``; should only
454 be used if ``src`` is defaulted.
455 libs : `str` or `list`, optional
456 Libraries to link against, either as a string argument to be
457 passed to `lsst.sconsUtils.env.getLibs` or a sequence of actual
458 libraries to pass in.
460 Returns
461 -------
462 result : `lsst.sconsUtils.env.Pybind11LoadableModule`
463 A Pybind11LoadableModule instance.
464 """
465 if module is None: 465 ↛ 467line 465 didn't jump to line 467 because the condition on line 465 was always true
466 module = "_" + state.env["packageName"].split("_")[-1]
467 if src is None: 467 ↛ 469line 467 didn't jump to line 469 because the condition on line 467 was always true
468 src = state.env.Glob("*.cc")
469 src.extend(extra)
470 if isinstance(libs, str): 470 ↛ 472line 470 didn't jump to line 472 because the condition on line 470 was always true
471 libs = state.env.getLibs(libs)
472 elif libs is None:
473 libs = []
474 result = state.env.Pybind11LoadableModule(module, src, LIBS=libs)
475 state.targets["python"].append(result)
476 return result
478 @staticmethod
479 def pybind11(nameList=(), libs="main python", extraSrc=None, addUnderscore=True):
480 """Convenience function to replace standard ``python/*/SConscript``
481 boilerplate.
483 .. note:: Deprecated
485 Use `lsst.sconsUtils.scripts.BasicSConscript.python` for new code
486 with all source compiled into a single module. Will be removed
487 once all LSST code has been converted to use the new approach.
489 Parameters
490 ----------
491 nameList : `collections.abc.Sequence`, optional
492 Sequence of pybind11 modules to be built (does not include the
493 file extensions).
494 libs : `str` or `list`, optional
495 Libraries to link against, either as a string argument to be
496 passed to `lsst.sconsUtils.env.getLibs` or a sequence of actual
497 libraries to pass in.
498 extraSrc : `dict`, optional
499 A dictionary of additional source files that go into the modules.
500 Each key should be an entry in nameList, and each value should be
501 a list of additional C++ source files.
502 addUnderscore : `bool`, optional
503 Add an underscore to each library name (if the source file name
504 does not already start with underscore)? If False the library name
505 is always the same as the source file name
506 **DEPRECATED**: always use `False` for new code.
508 Returns
509 -------
510 result : `lsst.sconsUtils.env.Pybind11LoadableModule`
511 A Pybind11LoadableModule instance.
512 """
513 warnings.warn(
514 "sconsUtils.scripts.pybind11() is deprecated; please use scripts.python() instead",
515 DeprecationWarning,
516 stacklevel=2,
517 )
518 srcList = extraSrc
519 if srcList is None:
520 srcList = {name: [] for name in nameList}
521 for name in nameList:
522 srcList[name].append(name + ".cc")
523 if isinstance(libs, str):
524 libs = state.env.getLibs(libs)
525 elif libs is None:
526 libs = []
527 result = []
528 for name in nameList:
529 # TODO remove this block and the `addUnderscore` argument and
530 # always use pyLibName = name; but we can't do that until all our
531 # pybind11 SConscript files have been converted
532 if addUnderscore:
533 if name.startswith("_"):
534 pyLibName = name
535 else:
536 pyLibName = "_" + name
537 else:
538 pyLibName = name
539 result.extend(state.env.Pybind11LoadableModule(pyLibName, srcList[name], LIBS=libs))
540 state.targets["python"].extend(result)
541 return result
543 @staticmethod
544 def doc(config="doxygen.conf.in", projectName=None, projectNumber=None, **kwargs):
545 """Convenience function to replace standard doc/SConscript
546 boilerplate.
548 With no arguments, this will generate a Doxygen config file and run
549 Doxygen with `lsst.sconsUtils.env.Doxygen`, using the projectName
550 and projectNumber from ``env["packageName"]`` and ``env["version"]``,
551 respectively.
553 This essentially just forwards all arguments (which should be passed as
554 keyword arguments) to `lsst.sconsUtils.env.Doxygen`.
556 Parameters
557 ----------
558 config : `str`, optional
559 Configuration .in file to use.
560 projectName : `str`, optional
561 Project name.
562 projectNumber : `str`, optional
563 Project version number.
564 kwargs
566 Returns
567 -------
568 result : ???
569 ???
570 """
571 if not shutil.which("doxygen"):
572 state.log.warn("doxygen executable not found; skipping documentation build.")
573 return []
574 if projectName is None:
575 projectName = ".".join(["lsst"] + state.env["packageName"].split("_"))
576 if projectNumber is None:
577 projectNumber = state.env["version"]
578 result = state.env.Doxygen(
579 config,
580 projectName=projectName,
581 projectNumber=projectNumber,
582 includes=state.env.doxygen["includes"],
583 useTags=state.env.doxygen["tags"],
584 makeTag=(state.env["packageName"] + ".tag"),
585 **kwargs,
586 )
587 state.targets["doc"].extend(result)
588 return result
590 @staticmethod
591 def tests(
592 pyList=None,
593 ccList=None,
594 ignoreList=None,
595 noBuildList=None,
596 pySingles=None,
597 args=None,
598 ):
599 """Convenience function to replace standard tests/SConscript
600 boilerplate.
602 With no arguments, will attempt to figure out which files should be
603 run as tests and which are support code.
605 Python tests will be marked as dependent on the entire ``#python``
606 directory. This should ensure tests are always run when their
607 results might have changed, but may result in them being re-run
608 more often than necessary.
610 Parameters
611 ----------
612 pyList : `list`, optional
613 A sequence of Python tests to run (including .py extensions).
614 Defaults to a ``*.py`` glob of the tests directory.
615 An empty list will enable automated test discovery.
616 ccList : `list`, optional
617 A sequence of C++ unit tests to run (including .cc extensions).
618 Defaults to a ``*.cc`` glob of the tests directory.
619 ignoreList : `list`, optional
620 List of ignored tests to be passed to
621 `lsst.sconsUtils.tests.Control` (note that ignored tests will be
622 built, but not run).
623 noBuildList : `list`, optional
624 List of tests that should not even be built.
625 pySingles : `list`, optional
626 A sequence of Python tests to run (including .py extensions)
627 as independent single tests. By default this list is empty
628 and all tests are run in a single pytest call.
629 Items specified here will not appear in the default pyList
630 and should not start with ``test_`` (such that they will not
631 be auto-discoverable by pytest).
632 args : `dict`, optional
633 A dictionary of program arguments for tests, passed directly
634 to `lsst.sconsUtils.tests.Control`.
636 Returns
637 -------
638 result : ???
639 ???
640 """
641 if GetOption("no_tests"): 641 ↛ 642line 641 didn't jump to line 642 because the condition on line 641 was never true
642 return []
643 if noBuildList is None: 643 ↛ 645line 643 didn't jump to line 645 because the condition on line 643 was always true
644 noBuildList = []
645 if pySingles is None: 645 ↛ 647line 645 didn't jump to line 647 because the condition on line 645 was always true
646 pySingles = []
647 if pyList is None: 647 ↛ 653line 647 didn't jump to line 653 because the condition on line 647 was always true
648 pyList = [node for node in Glob("*.py") if os.path.basename(str(node)) not in noBuildList]
649 # if we got no matches, reset to None so we do not enabled
650 # auto test detection in pytest
651 if not pyList: 651 ↛ 652line 651 didn't jump to line 652 because the condition on line 651 was never true
652 pyList = None
653 if ccList is None: 653 ↛ 655line 653 didn't jump to line 655 because the condition on line 653 was always true
654 ccList = [node for node in Glob("*.cc") if os.path.basename(str(node)) not in noBuildList]
655 if ignoreList is None: 655 ↛ 658line 655 didn't jump to line 658 because the condition on line 655 was always true
656 ignoreList = []
658 def s(ll):
659 if ll is None: 659 ↛ 660line 659 didn't jump to line 660 because the condition on line 659 was never true
660 return ["None"]
661 return [str(i) for i in ll]
663 state.log.info(f"Python tests: {s(pyList)}")
664 state.log.info(f"C++ tests: {s(ccList)}")
665 state.log.info(f"Files that will not be built: {noBuildList}")
666 state.log.info(f"Ignored tests: {ignoreList}")
667 control = tests.Control(state.env, ignoreList=ignoreList, args=args, verbose=True)
668 for ccTest in ccList: 668 ↛ 669line 668 didn't jump to line 669 because the loop on line 668 never started
669 state.env.Program(ccTest, LIBS=state.env.getLibs("main test"))
671 # Warn about insisting that a test in pySingles starts with test_ and
672 # therefore might be automatically discovered by pytest. These files
673 # should not be discovered automatically.
674 for node in pySingles: 674 ↛ 675line 674 didn't jump to line 675 because the loop on line 674 never started
675 if str(node).startswith("test_"):
676 state.log.warn(
677 f"Warning: {node} should be run independently but can be automatically discovered"
678 )
680 # Ensure that python tests listed in pySingles are not included in
681 # pyList.
682 if pyList is not None: 682 ↛ 685line 682 didn't jump to line 685 because the condition on line 682 was always true
683 pyList = [str(node) for node in pyList if str(node) not in pySingles]
685 ccList = [control.run(str(node)) for node in ccList]
686 pySingles = [control.run(str(node)) for node in pySingles]
688 # If we tried to discover .py files and found none, do not then
689 # try to use auto test discovery.
690 if pyList is not None: 690 ↛ 693line 690 didn't jump to line 693 because the condition on line 690 was always true
691 pyList = [control.runPythonTests(pyList)]
692 else:
693 pyList = []
694 pyList.extend(control.runPythonLinter())
696 # Run all pySingles sequentially before other tests. This ensures
697 # that there are no race conditions collecting coverage databases.
698 if pySingles: 698 ↛ 699line 698 didn't jump to line 699 because the condition on line 698 was never true
699 for i in range(len(pySingles) - 1):
700 state.env.Depends(pySingles[i + 1], pySingles[i])
701 for pyTest in pyList:
702 state.env.Depends(pyTest, pySingles[-1])
704 pyList.extend(pySingles)
705 for pyTest in pyList:
706 state.env.Depends(pyTest, ccList)
707 state.env.Depends(pyTest, state.targets["python"])
708 state.env.Depends(pyTest, state.targets["shebang"])
709 result = ccList + pyList
710 state.targets["tests"].extend(result)
711 return result
713 @staticmethod
714 def examples(ccList=None):
715 """Convenience function to replace standard examples/SConscript
716 boilerplate.
718 Parameters
719 ----------
720 ccList : `list`, optional
721 A sequence of C++ examples to build (including .cc extensions).
722 Defaults to a ``*.cc`` glob of the examples directory.
724 Returns
725 -------
726 result : ???
727 ???
728 """
729 if ccList is None: 729 ↛ 731line 729 didn't jump to line 731 because the condition on line 729 was always true
730 ccList = Glob("*.cc")
731 state.log.info(f"C++ examples: {ccList}")
732 results = []
733 for src in ccList:
734 results.extend(state.env.Program(src, LIBS=state.env.getLibs("main")))
735 for result in results:
736 state.env.Depends(result, state.targets["lib"])
737 state.targets["examples"].extend(results)
738 return results