Some examples of mock testing for network automation.
#network #automation #python
Set the environment variable
monkeypatch.setenv('USERNAME', 'TestingUser')
Patch dh.device Object
dh = DeviceHelper("sw01", cat9k24)
do_nothing = lambda: None
cli = lambda x: {y: f"Fake response for {y}" for y in x}
# Function call __enter__ gets patched/replaced with do_nothing func so there is no error
monkeypatch.setattr(dh.device, "__enter__", do_nothing)
monkeypatch.setattr(dh.device, "__exit__", do_nothing)
monkeypatch.setattr(dh.device, 'cli', cli)
result = dh.awesome_workflow()
assert result == expected_result
Use mocker (pytest-mock) to patch the Device methods:
dh = DeviceHelper("sw01", cat9k24)
mocks = [
mocker.patch.object(dh.device, 'connect'),
mocker.patch.object(dh.device, 'close'),
mocker.patch.object(dh.device, 'cli')
]
assert dh.awesome_workflow() == {}
mocks[0].assert_called_once
mocks[1].assert_called_once
assert mocks[2].call_count == 3
Use mocker (pytest-mock) to create a Mock object to replace the dh.device object
device_mock = mocker.MagicMock()
#set return values for the mock object
device_mock.__enter__.return_value = device_mock
device_mock.__exit__.return_value = None
device_mock.cli.side_effect = cli_responses
dh = DeviceHelper("sw01", cat9k24)
dh.device = device_mock # Device object is replaced with a Device Mock
result = dh.awesome_workflow()
class FakeDevice(BaseDevice):
cli_responses = {
"show user": "No user",
"show a": "a",
"show b": "b",
"show c": "c",
"do xyz": "did xyz",
}
def connect(self) -> None:
self.connection = True
def close(self) -> None:
self.connection = False
def _exec_cli(self, commands: Sequence[str]) -> Dict[str, str]:
return self.cli_responses