Coverage for tests/test_cliPluginLoader.py : 31%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
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 click
26import click.testing
27from collections import defaultdict
28from contextlib import contextmanager
29import os
30import unittest
31from unittest.mock import patch
32import yaml
34from lsst.daf.butler.cli import butler, cmd
37@click.command()
38def command_test():
39 click.echo("test command")
42@contextmanager
43def command_test_env(runner, commandName):
44 """A context manager that creates (and then cleans up) an environment that
45 provides a plugin command named 'command-test'.
47 Parameters
48 ----------
49 runner : click.testing.CliRunner
50 The test runner to use to create the isolated filesystem.
51 """
52 with runner.isolated_filesystem():
53 with open("resources.yaml", "w") as f:
54 f.write(yaml.dump({"cmd": {"import": "test_cliPluginLoader", "commands": [commandName]}}))
55 # Add a colon to the end of the path on the next line, this tests the
56 # case where the lookup in LoaderCLI._getPluginList generates an empty
57 # string in one of the list entries and verifies that the empty string
58 # is properly stripped out.
59 with patch.dict("os.environ", {"DAF_BUTLER_PLUGINS": f"{os.path.realpath(f.name)}:"}):
60 yield
63@contextmanager
64def duplicate_command_test_env(runner):
65 """A context manager that creates (and then cleans up) an environment that
66 declares a plugin command named 'create', which will conflict with the
67 daf_butler 'create' command.
69 Parameters
70 ----------
71 runner : click.testing.CliRunner
72 The test runner to use to create the isolated filesystem.
73 """
74 with runner.isolated_filesystem():
75 with open("resources.yaml", "w") as f:
76 f.write(yaml.dump({"cmd": {"import": "test_cliPluginLoader", "commands": ["create"]}}))
77 with patch.dict("os.environ", {"DAF_BUTLER_PLUGINS": os.path.realpath(f.name)}):
78 yield
81class FailedLoadTest(unittest.TestCase):
83 def test_unimportablePlugin(self):
84 runner = click.testing.CliRunner()
85 with command_test_env(runner, "non-existant-command-function"):
86 with self.assertLogs() as cm:
87 result = runner.invoke(butler.cli, "--help")
88 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
89 expectedErrMsg = "Could not import plugin from " \
90 "test_cliPluginLoader.non_existant_command_function, skipping."
91 self.assertIn(expectedErrMsg, cm.output[0])
94class PluginLoaderTest(unittest.TestCase):
96 def test_loadAndExecutePluginCommand(self):
97 """Test that a plugin command can be loaded and executed."""
98 runner = click.testing.CliRunner()
99 with command_test_env(runner, "command-test"):
100 result = runner.invoke(butler.cli, "command-test")
101 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
102 self.assertEqual(result.stdout, "test command\n")
104 def test_loadAndExecuteLocalCommand(self):
105 """Test that a command in daf_butler can be loaded and executed."""
106 runner = click.testing.CliRunner()
107 with runner.isolated_filesystem():
108 result = 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 runner = click.testing.CliRunner()
115 with command_test_env(runner, "command-test"):
116 result = runner.invoke(butler.cli, "--help")
117 self.assertEqual(result.exit_code, 0, f"output: {result.output} exception: {result.exception}")
118 self.assertIn("command-test", result.stdout)
120 def test_getLocalCommands(self):
121 """Test getting the daf_butler CLI commands."""
122 localCommands = butler.LoaderCLI._getLocalCommands()
123 # the number of local commands should equal the number of functions
124 # in cmd.__all__
125 self.assertEqual(len(localCommands), len(cmd.__all__))
126 for command, pkg in localCommands.items():
127 self.assertEqual(pkg, ["lsst.daf.butler.cli.cmd"])
129 def test_mergeCommandLists(self):
130 """Verify dicts of command to list-of-source-package get merged
131 properly."""
132 first = defaultdict(list, {"a": [1]})
133 second = defaultdict(list, {"b": [2]})
134 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1], "b": [2]})
135 first = defaultdict(list, {"a": [1]})
136 second = defaultdict(list, {"a": [2]})
137 self.assertEqual(butler.LoaderCLI._mergeCommandLists(first, second), {"a": [1, 2]})
139 def test_listCommands_duplicate(self):
140 """Test executing a command in a situation where duplicate commands are
141 present and verify it fails to run.
142 """
143 self.maxDiff = None
144 runner = click.testing.CliRunner()
145 with duplicate_command_test_env(runner):
146 result = runner.invoke(butler.cli, ["create", "test_repo"])
147 self.assertEqual(result.exit_code, 1, f"output: {result.output} exception: {result.exception}")
148 self.assertEqual(result.output, "Error: Command 'create' "
149 "exists in packages lsst.daf.butler.cli.cmd, test_cliPluginLoader. "
150 "Duplicate commands are not supported, aborting.\n")
153if __name__ == "__main__": 153 ↛ 154line 153 didn't jump to line 154, because the condition on line 153 was never true
154 unittest.main()