Coverage for tests/test_cliPluginLoader.py: 27%
75 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-28 10:10 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-28 10:10 +0000
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 """Run command test."""
40 click.echo(message="test command")
43@contextmanager
44def duplicate_command_test_env(runner):
45 """Context manager that creates (and then cleans up) an environment that
46 declares a plugin command named 'create', which will conflict with the
47 daf_butler 'create' command.
49 Parameters
50 ----------
51 runner : click.testing.CliRunner
52 The test runner to use to create the isolated filesystem.
53 """
54 with runner.isolated_filesystem():
55 with open("resources.yaml", "w") as f:
56 f.write(yaml.dump({"cmd": {"import": "test_cliPluginLoader", "commands": ["create"]}}))
57 with patch.dict("os.environ", {"DAF_BUTLER_PLUGINS": os.path.realpath(f.name)}):
58 yield
61class FailedLoadTest(unittest.TestCase):
62 """Test failed plugin loading."""
64 def setUp(self):
65 self.runner = LogCliRunner()
67 def test_unimportablePlugin(self):
68 with command_test_env(self.runner, "test_cliPluginLoader", "non-existant-command-function"):
69 with self.assertLogs() as cm:
70 result = self.runner.invoke(butler.cli, "--help")
71 self.assertEqual(result.exit_code, 0, f"output: {result.output!r} exception: {result.exception}")
72 expectedErrMsg = (
73 "Could not import plugin from test_cliPluginLoader.non_existant_command_function, skipping."
74 )
75 self.assertIn(expectedErrMsg, " ".join(cm.output))
77 def test_unimportableLocalPackage(self):
78 class FailCLI(butler.LoaderCLI):
79 localCmdPkg = "lsst.daf.butler.cli.cmds" # should not be an importable location
81 @click.command(cls=FailCLI)
82 def cli():
83 pass
85 with self.assertLogs() as cm:
86 result = self.runner.invoke(cli)
87 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
88 expectedErrMsg = f"Could not import plugin from {FailCLI.localCmdPkg}, skipping."
89 self.assertIn(expectedErrMsg, " ".join(cm.output))
92class PluginLoaderTest(unittest.TestCase):
93 """Test the command-line plugin loader."""
95 def setUp(self):
96 self.runner = LogCliRunner()
98 def test_loadAndExecutePluginCommand(self):
99 """Test that a plugin command can be loaded and executed."""
100 with command_test_env(self.runner, "test_cliPluginLoader", "command-test"):
101 result = self.runner.invoke(butler.cli, "command-test")
102 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
103 self.assertEqual(result.stdout, "test command\n")
105 def test_loadAndExecuteLocalCommand(self):
106 """Test that a command in daf_butler can be loaded and executed."""
107 with self.runner.isolated_filesystem():
108 result = self.runner.invoke(butler.cli, ["create", "test_repo"])
109 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
110 self.assertTrue(os.path.exists("test_repo"))
112 def test_loadTopHelp(self):
113 """Test that an expected command is produced by 'butler --help'"""
114 with command_test_env(self.runner, "test_cliPluginLoader", "command-test"):
115 result = self.runner.invoke(butler.cli, "--help")
116 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
117 self.assertIn("command-test", result.stdout)
119 def test_getLocalCommands(self):
120 """Test getting the daf_butler CLI commands."""
121 localCommands = butler.ButlerCLI().getLocalCommands()
122 # the number of local commands should equal the number of functions
123 # in cmd.__all__
124 self.assertEqual(len(localCommands), len(cmd.__all__))
126 def test_mergeCommandLists(self):
127 """Verify dicts of command to list-of-source-package get merged
128 properly.
129 """
130 first = defaultdict(list, {"a": [1]})
131 second = defaultdict(list, {"b": [2]})
132 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1], "b": [2]})
133 first = defaultdict(list, {"a": [1]})
134 second = defaultdict(list, {"a": [2]})
135 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1, 2]})
137 def test_listCommands_duplicate(self):
138 """Test executing a command in a situation where duplicate commands are
139 present and verify it fails to run.
140 """
141 self.maxDiff = None
142 with duplicate_command_test_env(self.runner):
143 result = self.runner.invoke(butler.cli, ["create", "test_repo"])
144 self.assertEqual(result.exit_code, 1, f"output: {result.output} exception: {result.exception}")
145 self.assertEqual(
146 result.output,
147 "Error: Command 'create' "
148 "exists in packages lsst.daf.butler.cli.cmd, test_cliPluginLoader. "
149 "Duplicate commands are not supported, aborting.\n",
150 )
153if __name__ == "__main__":
154 unittest.main()