|
| 1 | +"""Query CLI output of a device.""" |
| 2 | + |
| 3 | +from typing import Callable, Dict, Any |
| 4 | + |
| 5 | +import pytest |
| 6 | +from nornir.core.task import MultiResult, Result |
| 7 | +from nornir_netmiko import netmiko_send_command |
| 8 | + |
| 9 | +from nuts.helpers.result import ( |
| 10 | + AbstractHostResultExtractor, |
| 11 | + NutsResult, |
| 12 | +) |
| 13 | +from nuts.context import NornirNutsContext |
| 14 | + |
| 15 | +EXAMPLE = """ |
| 16 | +- test_class: TestNetmikoCLI |
| 17 | + test_module: example_custom_netmiko_cli_test.netmiko_cli |
| 18 | + test_execution: |
| 19 | + command_string: show call-home |
| 20 | + use_timing: False |
| 21 | + test_data: |
| 22 | + - host: switch01 |
| 23 | + contains: "call home feature : disable" |
| 24 | + not_contains: "enable" |
| 25 | +""" |
| 26 | + |
| 27 | + |
| 28 | +class CLIExtractor(AbstractHostResultExtractor): |
| 29 | + def single_transform(self, single_result: MultiResult) -> Dict[str, Dict[str, Any]]: |
| 30 | + cli_result = self._simple_extract(single_result) |
| 31 | + return cli_result |
| 32 | + |
| 33 | + |
| 34 | +class CLIContext(NornirNutsContext): |
| 35 | + def nuts_task(self) -> Callable[..., Result]: |
| 36 | + return netmiko_send_command |
| 37 | + |
| 38 | + def nuts_extractor(self) -> CLIExtractor: |
| 39 | + return CLIExtractor(self) |
| 40 | + |
| 41 | + |
| 42 | +CONTEXT = CLIContext |
| 43 | + |
| 44 | + |
| 45 | +class TestNetmikoCLI: |
| 46 | + @pytest.mark.nuts("contains") |
| 47 | + def test_contains_in_result( |
| 48 | + self, nuts_ctx, single_result: NutsResult, contains: Any |
| 49 | + ) -> None: |
| 50 | + cmd = nuts_ctx.nuts_parameters.get("test_execution", {}).get( |
| 51 | + "command_string", None |
| 52 | + ) |
| 53 | + result = single_result.result |
| 54 | + assert contains in result, f"'{contains}' NOT found in '{cmd}' output" |
| 55 | + |
| 56 | + @pytest.mark.nuts("not_contains") |
| 57 | + def test_not_contains_in_result( |
| 58 | + self, nuts_ctx, single_result: NutsResult, not_contains: Any |
| 59 | + ) -> None: |
| 60 | + cmd = nuts_ctx.nuts_parameters.get("test_execution", {}).get( |
| 61 | + "command_string", None |
| 62 | + ) |
| 63 | + result = single_result.result |
| 64 | + assert not_contains in result, f"'{not_contains}' FOUND in '{cmd}' output" |
0 commit comments