| 1 |
import unittest |
| 2 |
from pathlib import Path |
| 3 |
from unittest.mock import patch |
| 4 |
|
| 5 |
import in_toto.in_toto_match_products as cli |
| 6 |
from in_toto.models.metadata import Metadata |
| 7 |
|
| 8 |
|
| 9 |
class TestInTotoMatchProducts(unittest.TestCase): |
| 10 |
"""Basic tests for in_toto_match_products cli. |
| 11 |
|
| 12 |
Only tests cli <-> api interaction, api itself is tested in runlib. |
| 13 |
""" |
| 14 |
|
| 15 |
link = str( |
| 16 |
Path(__file__).parent / "demo_files" / "write-code.776a00e2.link" |
| 17 |
) |
| 18 |
|
| 19 |
def test_check_args(self): |
| 20 |
"""Assert api args for cli args.""" |
| 21 |
|
| 22 |
args = [ |
| 23 |
"--link", |
| 24 |
self.link, |
| 25 |
"--paths", |
| 26 |
"foo", |
| 27 |
"bar", |
| 28 |
"--exclude", |
| 29 |
"f*", |
| 30 |
"b*", |
| 31 |
"--lstrip-paths", |
| 32 |
"f", |
| 33 |
"b", |
| 34 |
] |
| 35 |
expected_arg = Metadata.load(self.link).signed |
| 36 |
expected_kwargs = { |
| 37 |
"paths": ["foo", "bar"], |
| 38 |
"exclude_patterns": ["f*", "b*"], |
| 39 |
"lstrip_paths": ["f", "b"], |
| 40 |
} |
| 41 |
|
| 42 |
# Mock sys.argv in cli tool to mock cli invocation, and mock api |
| 43 |
# function to only check how it is called, w/o executing. |
| 44 |
with patch.object(cli.sys, "argv", ["<cmd>"] + args), patch.object( |
| 45 |
cli, "match_products", return_value=(set(),) * 3 |
| 46 |
) as api, self.assertRaises(SystemExit): |
| 47 |
cli.main() |
| 48 |
|
| 49 |
api.assert_called_with(expected_arg, **expected_kwargs) |
| 50 |
|
| 51 |
def test_check_exit(self): |
| 52 |
"""Assert cli exit codes for api return values.""" |
| 53 |
test_data = [ |
| 54 |
((set(), set(), set()), 0), |
| 55 |
(({"foo"}, set(), set()), 1), |
| 56 |
((set(), {"foo"}, set()), 1), |
| 57 |
((set(), set(), {"foo"}), 1), |
| 58 |
] |
| 59 |
|
| 60 |
# Mock sys.argv in cli tool to mock cli invocation, and mock api |
| 61 |
# function to control return values, w/o executing. |
| 62 |
for api_return_value, cli_return_code in test_data: |
| 63 |
with patch.object( |
| 64 |
cli.sys, "argv", ["<cmd>", "-l", self.link] |
| 65 |
), patch.object( |
| 66 |
cli, "match_products", return_value=api_return_value |
| 67 |
), self.assertRaises( |
| 68 |
SystemExit |
| 69 |
) as error_ctx: |
| 70 |
cli.main() |
| 71 |
|
| 72 |
self.assertEqual( |
| 73 |
error_ctx.exception.code, |
| 74 |
cli_return_code, |
| 75 |
f"api returned: {api_return_value}", |
| 76 |
) |
| 77 |
|
| 78 |
|
| 79 |
if __name__ == "__main__": |
| 80 |
unittest.main() |