Mike Frysinger | fcdd942 | 2022-12-28 10:59:06 -0500 | [diff] [blame^] | 1 | # Copyright 2022 The ChromiumOS Authors |
| 2 | # Use of this source code is governed by a BSD-style license that can be |
| 3 | # found in the LICENSE file. |
| 4 | |
| 5 | """Test the cros_losetup module.""" |
| 6 | |
| 7 | import json |
| 8 | |
| 9 | import pytest |
| 10 | |
| 11 | from chromite.lib import image_lib |
| 12 | from chromite.lib import osutils |
| 13 | from chromite.scripts import cros_losetup |
| 14 | |
| 15 | |
| 16 | @pytest.fixture(autouse=True) |
| 17 | def is_root_fixture(monkeypatch): |
| 18 | """We don't want the code re-execing itself using sudo.""" |
| 19 | monkeypatch.setattr(osutils, "IsRootUser", lambda: True) |
| 20 | |
| 21 | |
| 22 | @pytest.fixture(autouse=True) |
| 23 | def stub_image_lib(monkeypatch): |
| 24 | """Make sure these APIs aren't used by default.""" |
| 25 | |
| 26 | def fail(path): |
| 27 | raise RuntimeError("test is missing a mock") |
| 28 | |
| 29 | monkeypatch.setattr(image_lib.LoopbackPartitions, "detach_loopback", fail) |
| 30 | monkeypatch.setattr(image_lib.LoopbackPartitions, "attach_image", fail) |
| 31 | |
| 32 | |
| 33 | def test_parser(): |
| 34 | """Basic tests for the parser interface.""" |
| 35 | parser = cros_losetup.get_parser() |
| 36 | |
| 37 | # Missing subcommand. |
| 38 | with pytest.raises(SystemExit): |
| 39 | parser.parse_args([]) |
| 40 | |
| 41 | # Unknown subcommand. |
| 42 | with pytest.raises(SystemExit): |
| 43 | parser.parse_args(["asdfadsf"]) |
| 44 | |
| 45 | # Missing path. |
| 46 | with pytest.raises(SystemExit): |
| 47 | parser.parse_args(["attach"]) |
| 48 | with pytest.raises(SystemExit): |
| 49 | parser.parse_args(["detach"]) |
| 50 | |
| 51 | # Valid commands. |
| 52 | parser.parse_args(["attach", "disk.bin"]) |
| 53 | parser.parse_args(["detach", "/dev/loop0"]) |
| 54 | |
| 55 | |
| 56 | def test_attach(monkeypatch, capsys): |
| 57 | """Verify attaching runs lower APIs.""" |
| 58 | monkeypatch.setattr( |
| 59 | image_lib.LoopbackPartitions, "attach_image", lambda x: "/dev/loop0" |
| 60 | ) |
| 61 | assert cros_losetup.main(["attach", "disk.bin"]) == 0 |
| 62 | |
| 63 | # Stdout should be JSON. |
| 64 | captured = capsys.readouterr() |
| 65 | data = json.loads(captured.out) |
| 66 | assert "path" in data |
| 67 | assert data["path"] == "/dev/loop0" |
| 68 | |
| 69 | |
| 70 | def test_detach_success(monkeypatch): |
| 71 | """Verify detaching runs lower APIs.""" |
| 72 | monkeypatch.setattr( |
| 73 | image_lib.LoopbackPartitions, "detach_loopback", lambda x: True |
| 74 | ) |
| 75 | assert cros_losetup.main(["detach", "/dev/loop0"]) == 0 |
| 76 | |
| 77 | |
| 78 | def test_detach_failure(monkeypatch): |
| 79 | """Verify detaching runs lower APIs.""" |
| 80 | monkeypatch.setattr( |
| 81 | image_lib.LoopbackPartitions, "detach_loopback", lambda x: False |
| 82 | ) |
| 83 | assert cros_losetup.main(["detach", "/dev/loop0"]) == 1 |