From cd21ab0f1762bc722f7cdb5cb99b0f89486e52fa Mon Sep 17 00:00:00 2001 From: James Garner Date: Fri, 6 Sep 2024 14:37:28 +1200 Subject: [PATCH] Cover both failure paths when running snap commands --- tests/unit/test_snap.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_snap.py b/tests/unit/test_snap.py index 500b41c5..6bea76b8 100644 --- a/tests/unit/test_snap.py +++ b/tests/unit/test_snap.py @@ -810,7 +810,7 @@ def test_can_ensure_states(self, mock_subprocess): self.assertTrue(baz.present) @patch("charms.operator_libs_linux.v2.snap.subprocess.check_output") - def test_raises_snap_not_found_error(self, mock_subprocess): + def test_raises_snap_error_on_failed_subprocess(self, mock_subprocess: MagicMock): def raise_error(cmd, **kwargs): # If we can't find the snap, we should raise a CalledProcessError. # @@ -824,6 +824,22 @@ def raise_error(cmd, **kwargs): self.assertEqual("", ctx.exception.name) self.assertIn("Failed to install or refresh snap(s): nothere", ctx.exception.message) + def test_raises_snap_error_on_snap_not_found(self): + """A cache failure will also ultimately result in a SnapError.""" + + class NotFoundCache: + cache = None + + def __getitem__(self, name: str) -> snap.Snap: + raise snap.SnapNotFoundError() + + with patch.object(snap, "_Cache", new=NotFoundCache()): + with self.assertRaises(snap.SnapError) as ctx: + snap.add("nothere") + repr(ctx.exception) # ensure custom __repr__ doesn't error + self.assertEqual("", ctx.exception.name) + self.assertIn("Failed to install or refresh snap(s): nothere", ctx.exception.message) + def test_snap_get(self): def fake_snap(command: str, optargs: Optional[Iterable[str]] = None) -> str: assert command == "get"