Coverage for tests/test_cliPluginLoader.py: 27%
75 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-06 02:34 -0700
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-06 02:34 -0700
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://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 <http://www.gnu.org/licenses/>.
22"""Unit tests for the daf_butler CLI plugin loader.
23"""
25import os
26import unittest
27from collections import defaultdict
28from contextlib import contextmanager
29from unittest.mock import patch
31import click
32import yaml
33from lsst.daf.butler.cli import butler, cmd
34from lsst.daf.butler.cli.utils import LogCliRunner, command_test_env
37@click.command()
38def command_test():
39 click.echo(message="test command")
42@contextmanager
43def duplicate_command_test_env(runner):
44 """A context manager that creates (and then cleans up) an environment that
45 declares a plugin command named 'create', which will conflict with the
46 daf_butler 'create' command.
48 Parameters
49 ----------
50 runner : click.testing.CliRunner
51 The test runner to use to create the isolated filesystem.
52 """
53 with runner.isolated_filesystem():
54 with open("resources.yaml", "w") as f:
55 f.write(yaml.dump({"cmd": {"import": "test_cliPluginLoader", "commands": ["create"]}}))
56 with patch.dict("os.environ", {"DAF_BUTLER_PLUGINS": os.path.realpath(f.name)}):
57 yield
60class FailedLoadTest(unittest.TestCase):
61 def setUp(self):
62 self.runner = LogCliRunner()
64 def test_unimportablePlugin(self):
65 with command_test_env(self.runner, "test_cliPluginLoader", "non-existant-command-function"):
66 with self.assertLogs() as cm:
67 result = self.runner.invoke(butler.cli, "--help")
68 self.assertEqual(result.exit_code, 0, f"output: {result.output!r} exception: {result.exception}")
69 expectedErrMsg = (
70 "Could not import plugin from test_cliPluginLoader.non_existant_command_function, skipping."
71 )
72 self.assertIn(expectedErrMsg, " ".join(cm.output))
74 def test_unimportableLocalPackage(self):
75 class FailCLI(butler.LoaderCLI):
76 localCmdPkg = "lsst.daf.butler.cli.cmds" # should not be an importable location
78 @click.command(cls=FailCLI)
79 def cli():
80 pass
82 with self.assertLogs() as cm:
83 result = self.runner.invoke(cli)
84 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
85 expectedErrMsg = f"Could not import plugin from {FailCLI.localCmdPkg}, skipping."
86 self.assertIn(expectedErrMsg, " ".join(cm.output))
89class PluginLoaderTest(unittest.TestCase):
90 def setUp(self):
91 self.runner = LogCliRunner()
93 def test_loadAndExecutePluginCommand(self):
94 """Test that a plugin command can be loaded and executed."""
95 with command_test_env(self.runner, "test_cliPluginLoader", "command-test"):
96 result = self.runner.invoke(butler.cli, "command-test")
97 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
98 self.assertEqual(result.stdout, "test command\n")
100 def test_loadAndExecuteLocalCommand(self):
101 """Test that a command in daf_butler can be loaded and executed."""
102 with self.runner.isolated_filesystem():
103 result = self.runner.invoke(butler.cli, ["create", "test_repo"])
104 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
105 self.assertTrue(os.path.exists("test_repo"))
107 def test_loadTopHelp(self):
108 """Test that an expected command is produced by 'butler --help'"""
109 with command_test_env(self.runner, "test_cliPluginLoader", "command-test"):
110 result = self.runner.invoke(butler.cli, "--help")
111 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
112 self.assertIn("command-test", result.stdout)
114 def test_getLocalCommands(self):
115 """Test getting the daf_butler CLI commands."""
116 localCommands = butler.ButlerCLI().getLocalCommands()
117 # the number of local commands should equal the number of functions
118 # in cmd.__all__
119 self.assertEqual(len(localCommands), len(cmd.__all__))
121 def test_mergeCommandLists(self):
122 """Verify dicts of command to list-of-source-package get merged
123 properly."""
124 first = defaultdict(list, {"a": [1]})
125 second = defaultdict(list, {"b": [2]})
126 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1], "b": [2]})
127 first = defaultdict(list, {"a": [1]})
128 second = defaultdict(list, {"a": [2]})
129 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1, 2]})
131 def test_listCommands_duplicate(self):
132 """Test executing a command in a situation where duplicate commands are
133 present and verify it fails to run.
134 """
135 self.maxDiff = None
136 with duplicate_command_test_env(self.runner):
137 result = self.runner.invoke(butler.cli, ["create", "test_repo"])
138 self.assertEqual(result.exit_code, 1, f"output: {result.output} exception: {result.exception}")
139 self.assertEqual(
140 result.output,
141 "Error: Command 'create' "
142 "exists in packages lsst.daf.butler.cli.cmd, test_cliPluginLoader. "
143 "Duplicate commands are not supported, aborting.\n",
144 )
147if __name__ == "__main__":
148 unittest.main()