From 7ed95cdf4825702e14f94e4c8cb42894fc2a8dee Mon Sep 17 00:00:00 2001 From: Toby Jennings Date: Mon, 16 Dec 2024 11:15:54 -0600 Subject: [PATCH] chore(test): Add test for coverage --- python/lsst/ctrl/mpexec/cli/cmd/commands.py | 3 ++- tests/test_cliScript.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/python/lsst/ctrl/mpexec/cli/cmd/commands.py b/python/lsst/ctrl/mpexec/cli/cmd/commands.py index bf49f7ad..6ca498a9 100644 --- a/python/lsst/ctrl/mpexec/cli/cmd/commands.py +++ b/python/lsst/ctrl/mpexec/cli/cmd/commands.py @@ -29,6 +29,7 @@ from collections.abc import Iterator, Sequence from contextlib import contextmanager from functools import partial +from importlib import import_module from tempfile import NamedTemporaryFile from typing import Any @@ -146,7 +147,7 @@ def coverage_context(kwargs: dict[str, Any]) -> Iterator[None]: return # Lazily import coverage only when we might need it try: - import coverage + coverage = import_module("coverage") except ModuleNotFoundError: raise click.ClickException("coverage was requested but the coverage package is not installed.") with NamedTemporaryFile("w") as rcfile: diff --git a/tests/test_cliScript.py b/tests/test_cliScript.py index f05c4771..e6c92637 100644 --- a/tests/test_cliScript.py +++ b/tests/test_cliScript.py @@ -28,10 +28,12 @@ import os import tempfile import unittest +import unittest.mock import click import lsst.utils.tests from lsst.ctrl.mpexec.cli import opt, script +from lsst.ctrl.mpexec.cli.cmd.commands import coverage_context from lsst.ctrl.mpexec.cli.pipetask import cli as pipetaskCli from lsst.ctrl.mpexec.showInfo import ShowInfo from lsst.daf.butler.cli.utils import LogCliRunner, clickResultMsg @@ -203,6 +205,25 @@ def cli(**kwargs): self.assertNotEqual(result.exit_code, 0) +class CoverageTestCase(unittest.TestCase): + """Test coverage context manager.""" + + @unittest.mock.patch.dict("sys.modules", coverage=unittest.mock.MagicMock()) + def testWithCoverage(self): + """Test that the coverage context manager runs when invoked.""" + with coverage_context({"coverage": True}): + self.assertTrue(True) + + @unittest.mock.patch("lsst.ctrl.mpexec.cli.cmd.commands.import_module", side_effect=ModuleNotFoundError()) + def testWithMissingCoverage(self, mock_import): + """Test that the coverage context manager complains when coverage is + not available. + """ + with self.assertRaises(click.exceptions.ClickException): + with coverage_context({"coverage": True}): + pass + + if __name__ == "__main__": lsst.utils.tests.init() unittest.main()