Coverage for tests/test_cliPluginLoader.py: 30%
75 statements
« prev ^ index » next coverage.py v7.5.0, created at 2024-05-03 02:48 -0700
« prev ^ index » next coverage.py v7.5.0, created at 2024-05-03 02:48 -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 software is dual licensed under the GNU General Public License and also
10# under a 3-clause BSD license. Recipients may choose which of these licenses
11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt,
12# respectively. If you choose the GPL option then the following text applies
13# (but note that there is still no warranty even if you opt for BSD instead):
14#
15# This program is free software: you can redistribute it and/or modify
16# it under the terms of the GNU General Public License as published by
17# the Free Software Foundation, either version 3 of the License, or
18# (at your option) any later version.
19#
20# This program is distributed in the hope that it will be useful,
21# but WITHOUT ANY WARRANTY; without even the implied warranty of
22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23# GNU General Public License for more details.
24#
25# You should have received a copy of the GNU General Public License
26# along with this program. If not, see <http://www.gnu.org/licenses/>.
28"""Unit tests for the daf_butler CLI plugin loader.
29"""
31import os
32import unittest
33from collections import defaultdict
34from contextlib import contextmanager
35from unittest.mock import patch
37import click
38import yaml
39from lsst.daf.butler.cli import butler, cmd
40from lsst.daf.butler.cli.utils import LogCliRunner, command_test_env
43@click.command()
44def command_test():
45 """Run command test."""
46 click.echo(message="test command")
49@contextmanager
50def duplicate_command_test_env(runner):
51 """Context manager that creates (and then cleans up) an environment that
52 declares a plugin command named 'create', which will conflict with the
53 daf_butler 'create' command.
55 Parameters
56 ----------
57 runner : click.testing.CliRunner
58 The test runner to use to create the isolated filesystem.
59 """
60 with runner.isolated_filesystem():
61 with open("resources.yaml", "w") as f:
62 f.write(yaml.dump({"cmd": {"import": "test_cliPluginLoader", "commands": ["create"]}}))
63 with patch.dict("os.environ", {"DAF_BUTLER_PLUGINS": os.path.realpath(f.name)}):
64 yield
67class FailedLoadTest(unittest.TestCase):
68 """Test failed plugin loading."""
70 def setUp(self):
71 self.runner = LogCliRunner()
73 def test_unimportablePlugin(self):
74 with command_test_env(self.runner, "test_cliPluginLoader", "non-existant-command-function"):
75 with self.assertLogs() as cm:
76 result = self.runner.invoke(butler.cli, "--help")
77 self.assertEqual(result.exit_code, 0, f"output: {result.output!r} exception: {result.exception}")
78 expectedErrMsg = (
79 "Could not import plugin from test_cliPluginLoader.non_existant_command_function, skipping."
80 )
81 self.assertIn(expectedErrMsg, " ".join(cm.output))
83 def test_unimportableLocalPackage(self):
84 class FailCLI(butler.LoaderCLI):
85 localCmdPkg = "lsst.daf.butler.cli.cmds" # should not be an importable location
87 @click.command(cls=FailCLI)
88 def cli():
89 pass
91 with self.assertLogs() as cm:
92 result = self.runner.invoke(cli)
93 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
94 expectedErrMsg = f"Could not import plugin from {FailCLI.localCmdPkg}, skipping."
95 self.assertIn(expectedErrMsg, " ".join(cm.output))
98class PluginLoaderTest(unittest.TestCase):
99 """Test the command-line plugin loader."""
101 def setUp(self):
102 self.runner = LogCliRunner()
104 def test_loadAndExecutePluginCommand(self):
105 """Test that a plugin command can be loaded and executed."""
106 with command_test_env(self.runner, "test_cliPluginLoader", "command-test"):
107 result = self.runner.invoke(butler.cli, "command-test")
108 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
109 self.assertEqual(result.stdout, "test command\n")
111 def test_loadAndExecuteLocalCommand(self):
112 """Test that a command in daf_butler can be loaded and executed."""
113 with self.runner.isolated_filesystem():
114 result = self.runner.invoke(butler.cli, ["create", "test_repo"])
115 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
116 self.assertTrue(os.path.exists("test_repo"))
118 def test_loadTopHelp(self):
119 """Test that an expected command is produced by 'butler --help'"""
120 with command_test_env(self.runner, "test_cliPluginLoader", "command-test"):
121 result = self.runner.invoke(butler.cli, "--help")
122 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
123 self.assertIn("command-test", result.stdout)
125 def test_getLocalCommands(self):
126 """Test getting the daf_butler CLI commands."""
127 localCommands = butler.ButlerCLI().getLocalCommands()
128 # the number of local commands should equal the number of functions
129 # in cmd.__all__
130 self.assertEqual(len(localCommands), len(cmd.__all__))
132 def test_mergeCommandLists(self):
133 """Verify dicts of command to list-of-source-package get merged
134 properly.
135 """
136 first = defaultdict(list, {"a": [1]})
137 second = defaultdict(list, {"b": [2]})
138 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1], "b": [2]})
139 first = defaultdict(list, {"a": [1]})
140 second = defaultdict(list, {"a": [2]})
141 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1, 2]})
143 def test_listCommands_duplicate(self):
144 """Test executing a command in a situation where duplicate commands are
145 present and verify it fails to run.
146 """
147 self.maxDiff = None
148 with duplicate_command_test_env(self.runner):
149 result = self.runner.invoke(butler.cli, ["create", "test_repo"])
150 self.assertEqual(result.exit_code, 1, f"output: {result.output} exception: {result.exception}")
151 self.assertEqual(
152 result.output,
153 "Error: Command 'create' "
154 "exists in packages lsst.daf.butler.cli.cmd, test_cliPluginLoader. "
155 "Duplicate commands are not supported, aborting.\n",
156 )
159if __name__ == "__main__":
160 unittest.main()