Coverage for python/lsst/sconsUtils/tests.py: 46%
225 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 19:18 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-26 19:18 +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"""Control which tests run, and how."""
24__all__ = ("Control",)
26import glob
27import os
28import shlex
29import sys
31import SCons.Script
33from . import state, utils
36class Control:
37 """A class to control and run unit tests.
39 This class is unchanged from previous versions of sconsUtils, but it will
40 now generally be called via
41 `lsst.sconsUtils.scripts.BasicSConscript.tests`.
43 Parameters
44 ----------
45 env : `SCons.Environment`
46 An SCons Environment (almost always `lsst.sconsUtils.env`).
47 ignoreList : `list`, optional
48 A list of tests that should NOT be run --- useful in conjunction
49 with glob patterns. If a file is listed as "@fileName", the @ is
50 stripped and we don't bother to check if fileName exists (useful for
51 machine-generated files).
52 expectedFailures : `dict`, optional
53 A dictionary; the keys are tests that are known to fail; the values
54 are strings to print.
55 args : `dict`, optional
56 A dictionary with testnames as keys, and argument strings as values.
57 As scons always runs from the top-level directory, tests has to fiddle
58 with paths. If an argument is a file this is done automatically; if
59 it's e.g., just a basename then you have to tell tests that it's
60 really (part of a) filename by prefixing the name by ``file:``.
61 tmpDir : `str`, optional
62 The location of the test outputs.
63 verbose : `bool`, optional
64 How chatty you want the test code to be.
66 Notes
67 -----
68 Sample usage:
70 .. code-block:: python
72 tests = lsst.tests.Control(
73 env,
74 args={
75 "MaskIO_1" : "data/871034p_1_MI_msk.fits",
76 "MaskedImage_1" : "file:data/871034p_1_MI foo",
77 },
78 ignoreList=["Measure_1"],
79 expectedFailures={"BBox_1": "Problem with single-pixel BBox"}
80 )
82 This class is unchanged from previous versions of sconsUtils, but it will
83 now generally be called via
84 `lsst.sconsUtils.scripts.BasicSConscript.tests`.
85 """
87 _IGNORE = "IGNORE"
88 _EXPECT_FAILURE = "EXPECT_FAILURE"
90 def __init__(
91 self, env, ignoreList=None, expectedFailures=None, args=None, tmpDir=".tests", verbose=False
92 ):
93 # Need to define our own Astropy cache directories.
94 # Unfortunately we can not simply set XDG_CACHE_HOME
95 # to $HOME/.astropy. Do not forward $HOME or the XDG_CONFIG_HOME
96 # environment variables since those may affect test outcomes.
97 xdgCacheVar = "XDG_CACHE_HOME"
98 if xdgCacheVar not in os.environ: 98 ↛ 99line 98 didn't jump to line 99 because the condition on line 98 was never true
99 if "~" in os.path.expanduser("~"):
100 state.log.warn(f"Neither $HOME nor ${xdgCacheVar} defined. No Astropy cache enabled.")
101 else:
102 # We need a directory for the cache and that directory
103 # has to have an "astropy" directory inside it. We can
104 # use ~/.astropy or ~/.lsst or a tmp directory but choose
105 # ~/.lsst initially.
106 cacheDir = os.path.expanduser("~/.lsst")
107 astropyCacheDir = os.path.join(cacheDir, "astropy")
108 if not os.path.exists(astropyCacheDir):
109 os.makedirs(astropyCacheDir, exist_ok=True) # Race condition is okay
110 os.environ[xdgCacheVar] = cacheDir
111 else:
112 if not os.path.exists(os.path.expanduser(os.path.join(os.environ[xdgCacheVar], "astropy"))): 112 ↛ 113line 112 didn't jump to line 113 because the condition on line 112 was never true
113 state.log.warn(
114 f"{xdgCacheVar} is set but will not be used for "
115 "astropy due to lack of astropy directory within it"
116 )
118 # Forward additional environment to the tests.
119 for envvar in [xdgCacheVar]:
120 if envvar in os.environ: 120 ↛ 119line 120 didn't jump to line 119 because the condition on line 120 was always true
121 env.AppendENVPath(envvar, os.environ[envvar])
123 # We can't use the AppendENVPath call above as that mangles anything
124 # with ':' separators.
125 if "PYTHONWARNINGS" in os.environ: 125 ↛ 126line 125 didn't jump to line 126 because the condition on line 125 was never true
126 env["ENV"]["PYTHONWARNINGS"] = os.environ["PYTHONWARNINGS"]
128 self._env = env
130 self._tmpDir = tmpDir
131 self._cwd = os.path.abspath(os.path.curdir)
133 # Calculate the absolute path for temp dir if it is relative.
134 # This assumes the temp dir is relative to where the tests SConscript
135 # file is located. SCons will know how to handle this itself but
136 # some options require the code to know where to write things.
137 if os.path.isabs(self._tmpDir): 137 ↛ 138line 137 didn't jump to line 138 because the condition on line 137 was never true
138 self._tmpDirAbs = self._tmpDir
139 else:
140 self._tmpDirAbs = os.path.join(self._cwd, self._tmpDir)
142 self._verbose = verbose
144 self._info = {} # information about processing targets
145 if ignoreList: 145 ↛ 146line 145 didn't jump to line 146 because the condition on line 145 was never true
146 for f in ignoreList:
147 if f.startswith("@"): # @dfilename => don't complain if filename doesn't exist
148 f = f[1:]
149 else:
150 if not os.path.exists(f):
151 state.log.warn(f"You're ignoring a non-existent file, {f}")
152 self._info[f] = (self._IGNORE, None)
154 if expectedFailures: 154 ↛ 155line 154 didn't jump to line 155 because the condition on line 154 was never true
155 for f in expectedFailures:
156 self._info[f] = (self._EXPECT_FAILURE, expectedFailures[f])
158 if args: 158 ↛ 159line 158 didn't jump to line 159 because the condition on line 158 was never true
159 self._args = args # arguments for tests
160 else:
161 self._args = {}
163 self.runExamples = True # should I run the examples?
164 try:
165 # file is user read/write/executable
166 self.runExamples = (os.stat(self._tmpDir).st_mode & 0o700) != 0
167 except OSError:
168 pass
170 if not self.runExamples: 170 ↛ 171line 170 didn't jump to line 171 because the condition on line 170 was never true
171 print(f'Not running examples; "chmod 755 {self._tmpDir}" to run them again', file=sys.stderr)
173 def args(self, test):
174 """Arguments to use for this test.
176 Parameters
177 ----------
178 test : `str`
179 Test file to be run.
181 Returns
182 -------
183 args : `str`
184 The arguments as a single string. An empty string is returned
185 if no arguments were specified in the constructor.
186 """
187 try:
188 return self._args[test]
189 except KeyError:
190 return ""
192 def ignore(self, test):
193 """Should the test be ignored.
195 Parameters
196 ----------
197 test : `str`
198 The test target name.
200 Returns
201 -------
202 ignore : `bool`
203 Whether the test should be ignored or not.
204 """
205 if not test.endswith(".py") and len(self._env.Glob(test)) == 0: # we don't know how to build it 205 ↛ 206line 205 didn't jump to line 206 because the condition on line 205 was never true
206 return True
208 ignoreFile = test in self._info and self._info[test][0] == self._IGNORE
210 if self._verbose and ignoreFile: 210 ↛ 211line 210 didn't jump to line 211 because the condition on line 210 was never true
211 print("Skipping", test, file=sys.stderr)
213 return ignoreFile
215 def messages(self, test):
216 """Return the messages to be used in case of success/failure.
218 Parameters
219 ----------
220 test : `str`
221 The test target.
223 Returns
224 -------
225 messages : `tuple`
226 A `tuple` containing four strings: whether the test should pass
227 (as a value "true" or "false") and the associated message, and
228 whether the test should fail and the associated message.
229 """
231 if test in self._info and self._info[test][0] == self._EXPECT_FAILURE:
232 msg = self._info[test][1]
233 return (
234 "false",
235 f"Passed, but should have failed: {msg}",
236 "true",
237 f"Failed as expected: {msg}",
238 )
239 else:
240 return ("true", "passed", "false", "failed")
242 def run(self, fileGlob):
243 """Create a test target for each file matching the supplied glob.
245 Parameters
246 ----------
247 fileGlob : `str` or `SCons.Environment.Base.Glob`
248 File matching glob.
250 Returns
251 -------
252 targets :
253 Test target for each matching file.
254 """
256 if not isinstance(fileGlob, str): # env.Glob() returns an scons Node
257 fileGlob = str(fileGlob)
258 targets = []
259 if not self.runExamples:
260 return targets
262 # Determine any library load path values that we have to prepend
263 # to the command.
264 libpathstr = utils.libraryLoaderEnvironment()
266 for f in glob.glob(fileGlob):
267 interpreter = "" # interpreter to run test, if needed
269 if f.endswith(".cc"): # look for executable
270 f = os.path.splitext(f)[0]
271 else:
272 interpreter = "pytest"
273 interpreter += (
274 ' -Wd -W "ignore:unclosed database in <sqlite3.Connection object at:ResourceWarning"'
275 )
276 interpreter += " -p no:unraisableexception"
277 interpreter += " --durations=5 --junit-xml=${TARGET}.xml"
278 interpreter += f" --junit-prefix={self.junitPrefix()}"
279 interpreter += " --log-level=DEBUG"
280 interpreter += self._getPytestCoverageCommand()
282 if self.ignore(f):
283 continue
285 target = os.path.join(self._tmpDir, f)
287 args = []
288 for a in self.args(f).split(" "):
289 # if a is a file, make it an absolute name as scons runs from
290 # the root directory
291 filePrefix = "file:"
292 if a.startswith(filePrefix): # they explicitly said that this was a file
293 a = os.path.join(self._cwd, a[len(filePrefix) :])
294 else:
295 try: # see if it's a file
296 os.stat(a)
297 a = os.path.join(self._cwd, a)
298 except OSError:
299 pass
301 args += [a]
303 (should_pass, passedMsg, should_fail, failedMsg) = self.messages(f)
305 expandedArgs = " ".join(args)
306 result = self._env.Command(
307 target,
308 f,
309 f"""
310 @rm -f ${{TARGET}}.failed;
311 @printf "%s" 'running ${{SOURCES}}... ';
312 @echo $SOURCES {expandedArgs} > $TARGET; echo >> $TARGET;
313 @if {libpathstr} {interpreter} $SOURCES {expandedArgs} >> $TARGET 2>&1; then \
314 if ! {should_pass}; then mv $TARGET ${{TARGET}}.failed; fi; \
315 echo "{passedMsg}"; \
316 else \
317 if ! {should_fail}; then mv $TARGET ${{TARGET}}.failed; fi; \
318 echo "{failedMsg}"; \
319 fi;
320 """,
321 )
323 targets.extend(result)
325 self._env.Alias(os.path.basename(target), target)
327 self._env.Clean(target, self._tmpDir)
329 return targets
331 def runPythonLinter(self):
332 """Add a target for running the python linter.
334 Returns
335 -------
336 target : `list`
337 Returns a list containing a single target. Can be empty
338 if no suitable linter configuration was found.
339 """
340 linter: str | None = None
341 lint_options = ""
342 root = SCons.Script.Dir("#").abspath
344 # Never want linters to look in this directory.
345 exclude_dirs = ["tests/.tests"]
347 pyproject = os.path.join(root, "pyproject.toml")
348 if os.path.exists(pyproject): 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true
349 try:
350 import tomllib
351 except ImportError:
352 import tomli as tomllib
354 with open(pyproject) as fh:
355 try:
356 parsed = tomllib.loads(fh.read())
357 except Exception:
358 pass
359 else:
360 if "tool" in parsed and "ruff" in parsed["tool"]:
361 linter = "ruff"
362 lint_options = "check"
364 # Ruff can complain about noqa in shebang line
365 # added by sconsUtils to bin/ scripts. Need to ignore.
366 exclude_dirs.append("bin")
368 if linter is None: 368 ↛ 387line 368 didn't jump to line 387 because the condition on line 368 was always true
369 flake8_cfg = os.path.join(root, "setup.cfg")
370 if os.path.exists(os.path.join(root, ".flake8")): 370 ↛ 371line 370 didn't jump to line 371 because the condition on line 370 was never true
371 linter = "flake8"
372 elif os.path.exists(flake8_cfg): 372 ↛ 375line 372 didn't jump to line 375 because the condition on line 372 was never true
373 # Could search for [flake8] in file but parsing might
374 # be safer.
375 import configparser
377 config = configparser.ConfigParser()
378 try:
379 config.read(flake8_cfg)
380 except Exception:
381 # No valid flake8 config item possible.
382 pass
383 else:
384 if "flake8" in config:
385 linter = "flake8"
387 if linter is None: 387 ↛ 391line 387 didn't jump to line 391 because the condition on line 387 was always true
388 print(f"No Python linter configuration detected at path {root}.")
389 return []
391 target = os.path.join(self._tmpDir, f"linter-{linter}.log")
392 print(f"Detected configuration for python linter {linter}")
394 # Remove target so that we always trigger the linter (which should
395 # be fast). Use a glob since it is possible that someone may switch
396 # from flake8 to ruff and this can lead to confusing output if the
397 # previous flake8 run failed.
398 for path in glob.glob(os.path.join(self._tmpDir, "linter-*.log*")):
399 os.unlink(path)
401 # Specify exclude directories. Append to any existing lint options.
402 lint_options += f" --extend-exclude={','.join(exclude_dirs)}"
404 cmd = f"""
405 @printf "%s\\n" 'Running python linter {linter}...';
406 @rm -f ${{TARGET}} ${{TARGET}}.failed;
407 @({linter} {lint_options} . > ${{TARGET}}); \
408 export rc="$?"; \
409 if [ "$$rc" -eq 0 ]; then \
410 echo "Python linting completed successfully"; \
411 else \
412 echo "Python linting failed with error"; \
413 mv ${{TARGET}} ${{TARGET}}.failed; \
414 fi;
415 """
417 result = self._env.Command(target, None, cmd)
419 return [result]
421 def runPythonTests(self, pyList):
422 """Add a single target for testing all python files.
424 Parameters
425 ----------
426 pyList : `list`
427 A list of nodes corresponding to python test files. The
428 IgnoreList is respected when scanning for entries. If pyList
429 is `None`, or an empty list, it uses automated test discovery
430 within pytest. This differs from the behavior of
431 `lsst.sconsUtils.BasicSconscript.tests`
432 where a distinction is made.
434 Returns
435 -------
436 target : `list`
437 Returns a list containing a single target.
438 """
440 if pyList is None: 440 ↛ 441line 440 didn't jump to line 441 because the condition on line 440 was never true
441 pyList = []
443 # Determine any library load path values that we have to prepend
444 # to the command.
445 libpathstr = utils.libraryLoaderEnvironment()
447 # Get list of python files with the path included.
448 pythonTestFiles = []
449 for fileGlob in pyList:
450 if not isinstance(fileGlob, str): # env.Glob() returns an scons Node 450 ↛ 451line 450 didn't jump to line 451 because the condition on line 450 was never true
451 fileGlob = str(fileGlob)
452 for f in glob.glob(fileGlob):
453 if self.ignore(f): 453 ↛ 454line 453 didn't jump to line 454 because the condition on line 453 was never true
454 continue
455 pythonTestFiles.append(os.path.join(self._cwd, f))
457 # Now set up the python testing target
458 # We always want to run this with the tests target.
459 # We have decided to use pytest caching so that on reruns we only
460 # run failed tests.
461 lfnfOpt = "none" if "install" in SCons.Script.COMMAND_LINE_TARGETS else "all"
462 interpreter = f"pytest --lf --lfnf={lfnfOpt}"
463 interpreter += ' -Wd -W "ignore:unclosed database in <sqlite3.Connection object at:ResourceWarning"'
464 interpreter += " -p no:unraisableexception"
465 interpreter += " --durations=5 --junit-xml=${TARGET} --session2file=${TARGET}.out"
466 interpreter += f" --junit-prefix={self.junitPrefix()}"
467 interpreter += " --log-level=DEBUG"
468 interpreter += self._getPytestCoverageCommand()
469 # Avoids target install overwrite the real coverage
470 if lfnfOpt == "none": 470 ↛ 471line 470 didn't jump to line 471 because the condition on line 470 was never true
471 interpreter += " --no-cov"
473 # Ignore doxygen build directories since they can confuse pytest
474 # test collection
475 interpreter += " --ignore=doc/html --ignore=doc/xml"
477 # Ignore the C++ directories since they will never have python
478 # code and doing this will speed up test collection
479 interpreter += " --ignore=src --ignore=include --ignore=lib"
481 # Ignore the eups directory
482 interpreter += " --ignore=ups"
484 # We currently have a race condition in test collection when
485 # examples has C++ code. Removing it from the scan will get us through
486 # until we can fix the problem properly. Rely on GitHub PRs to
487 # do the flake8 check.
488 interpreter += " --ignore=examples"
490 # Also include temporary files made by compilers.
491 # These can come from examples directories that include C++.
492 interpreter += " --ignore-glob='*.tmp'"
494 target = os.path.join(self._tmpDir, "pytest-{}.xml".format(self._env["eupsProduct"]))
496 # Work out how many jobs scons has been configured to use
497 # and use that number with pytest. This could cause trouble
498 # if there are lots of binary tests to run and lots of singles.
499 njobs = self._env.GetOption("num_jobs")
500 print("Running pytest with {} process{}".format(njobs, "" if njobs == 1 else "es"))
501 if njobs > 1: 501 ↛ 511line 501 didn't jump to line 511 because the condition on line 501 was never true
502 # We unambiguously specify the Python interpreter to be used to
503 # execute tests. This ensures that all pytest-xdist worker
504 # processes refer to the same Python as the xdist controller, and
505 # hence avoids pollution of ``sys.path`` that can happen when we
506 # call the same interpreter by different paths (for example, if
507 # the controller process calls ``miniconda/bin/python``, and the
508 # workers call ``current/bin/python``, the workers will end up
509 # with site-packages directories corresponding to both locations
510 # on ``sys.path``, even if the one is a symlink to the other).
511 executable = os.path.realpath(sys.executable)
513 # if there is a space in the executable path we have to use the
514 # original method and hope things work okay. This will be rare but
515 # without this a space in the path is impossible because of how
516 # xdist currently parses the tx option
517 interpreter = interpreter + " --max-worker-restart=0"
518 if " " not in executable:
519 interpreter = interpreter + f" -d --tx={njobs}*popen//python={executable}"
520 else:
521 interpreter = interpreter + f" -n {njobs}"
523 # Remove target so that we always trigger pytest
524 if os.path.exists(target): 524 ↛ 525line 524 didn't jump to line 525 because the condition on line 524 was never true
525 os.unlink(target)
527 if not pythonTestFiles: 527 ↛ 528line 527 didn't jump to line 528 because the condition on line 527 was never true
528 print("pytest: automated test discovery mode enabled.")
529 else:
530 nfiles = len(pythonTestFiles)
531 print("pytest: running on {} Python test file{}.".format(nfiles, "" if nfiles == 1 else "s"))
533 # If we ran all the test, then copy the previous test
534 # execution products to `.all' files so we can retrieve later.
535 # If we skip the test (exit code 5), retrieve those `.all' files.
536 cmd = ""
537 if lfnfOpt == "all": 537 ↛ 539line 537 didn't jump to line 539 because the condition on line 537 was always true
538 cmd += "@rm -f ${{TARGET}} ${{TARGET}}.failed;"
539 cmd += """
540 @printf "%s\\n" 'running global pytest... ';
541 @({2} {0} {1}); \
542 export rc="$?"; \
543 if [ "$$rc" -eq 0 ]; then \
544 echo "Global pytest run completed successfully"; \
545 cp ${{TARGET}} ${{TARGET}}.all || true; \
546 cp ${{TARGET}}.out ${{TARGET}}.out.all || true; \
547 elif [ "$$rc" -eq 5 ]; then \
548 echo "Global pytest run completed successfully - no tests ran"; \
549 mv ${{TARGET}}.all ${{TARGET}} || true; \
550 mv ${{TARGET}}.out.all ${{TARGET}}.out || true; \
551 else \
552 echo "Global pytest run: failed with $$rc"; \
553 mv ${{TARGET}}.out ${{TARGET}}.failed; \
554 fi;
555 """
556 testfiles = shlex.join(pythonTestFiles)
557 result = self._env.Command(target, None, cmd.format(interpreter, testfiles, libpathstr))
559 self._env.Alias(os.path.basename(target), target)
560 self._env.Clean(target, self._tmpDir)
562 return [result]
564 def junitPrefix(self):
565 """Calculate the prefix to use for the JUnit output.
567 Returns
568 -------
569 prefix : `str`
570 Prefix string to use.
572 Notes
573 -----
574 Will use the EUPS product being built and the value of the
575 ``LSST_JUNIT_PREFIX`` environment variable if that is set.
576 """
577 controlVar = "LSST_JUNIT_PREFIX"
578 prefix = self._env["eupsProduct"]
580 if controlVar in os.environ: 580 ↛ 581line 580 didn't jump to line 581 because the condition on line 580 was never true
581 prefix += f".{os.environ[controlVar]}"
583 return prefix
585 def _getPytestCoverageCommand(self):
586 """Form the additional arguments required to enable coverage testing.
588 Coverage output files are written using ``${TARGET}`` as a base.
590 Returns
591 -------
592 options : `str`
593 String defining the coverage-specific arguments to give to the
594 pytest command.
595 """
597 options = ""
599 # Basis for deriving file names
600 # We use the magic target from SCons.
601 prefix = "${TARGET}"
603 # Only report coverage for files in the build tree.
604 # If --cov is used full coverage will be reported for all installed
605 # code as well, but that is probably a distraction as for this
606 # test run we are only interested in coverage of this package.
607 # Specify explicit subdirectories to prevent coverage from getting
608 # confused by URIs ending in .py that look like relative paths.
609 options += " --cov=python --cov=tests"
611 # Always enabled branch coverage and terminal summary
612 options += " --cov-branch --cov-report=term "
614 covfile = "{}-cov-{}.xml".format(prefix, self._env["eupsProduct"])
616 # We should specify the output directory explicitly unless the prefix
617 # indicates that we are using the SCons target
618 if covfile.startswith("${TARGET}"): 618 ↛ 621line 618 didn't jump to line 621 because the condition on line 618 was always true
619 covpath = covfile
620 else:
621 covpath = os.path.join(self._tmpDirAbs, covfile)
622 options += f" --cov-report=xml:'{covpath}'"
624 # Use the prefix for the HTML output directory
625 htmlfile = f":'{prefix}-htmlcov'"
626 options += f" --cov-report=html{htmlfile}"
628 return options