Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unit testcases #716

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
262 changes: 262 additions & 0 deletions ansible_collections/juniper/device/tests/test_command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
import pytest
from unittest.mock import MagicMock, patch
from lxml import etree
import sys
import json
from ansible_collections.juniper.device.plugins.modules.command import main

from ansible_collections.juniper.device.plugins.module_utils import configuration as cfg
from ansible_collections.juniper.device.plugins.module_utils import juniper_junos_common

# Mock the necessary functions and classes
@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
def test_command_text(mock_junos_module):
# Set up the mock module instance
mock_instance = mock_junos_module.return_value
mock_instance.params = {
'commands': ['show version'],
'formats': ['text'],
'return_output': True
}
mock_instance.etree = etree
mock_instance.pyez_exception = MagicMock()
mock_instance.logger = MagicMock()
mock_instance.conn_type = "local"
mock_instance.dev = MagicMock()

# Create a mock response that mimics the expected structure
mock_response = etree.Element("rpc-reply")
mock_response.text = "Output text"
mock_instance.dev.rpc.return_value = mock_response

# Run the main function
with patch("sys.exit") as mock_exit:
main()

# Assertions to check if the main function behaves as expected
mock_instance.fail_json.assert_not_called()
mock_instance.exit_json.assert_called_once_with(
command='show version',
format='text',
msg='The command executed successfully.',
changed=False,
failed=False,
stdout='Output text',
stdout_lines=['Output text']
)


@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
def test_command_xml(mock_junos_module):
# Set up the mock module instance
mock_instance = mock_junos_module.return_value
mock_instance.params = {
'commands': ['show configuration'],
'formats': ['xml'],
'return_output': True
}
mock_instance.etree = etree
mock_instance.pyez_exception = MagicMock()
mock_instance.logger = MagicMock()
mock_instance.conn_type = "local"
mock_instance.dev = MagicMock()

# Mock the parse_ignore_warning_option method to return None
mock_instance.parse_ignore_warning_option.return_value = None

# Create a mock XML response
mock_xml_response = etree.Element("rpc-reply")
sub_element = etree.SubElement(mock_xml_response, "configuration-information")
sub_element.text = "Sample configuration information"
mock_instance.dev.rpc.return_value = mock_xml_response

# Create the same Element object used in the test
command_element = etree.Element("command", format="xml")

with patch.object(etree, 'Element', return_value=command_element):
# Run the main function
with patch("sys.exit") as mock_exit:
main()

# Prepare expected XML output
expected_xml_output = etree.tostring(mock_xml_response, pretty_print=True, encoding='unicode')

# Assertions to check if the main function behaves as expected
mock_instance.fail_json.assert_not_called()
mock_instance.exit_json.assert_called_once_with(
command='show configuration',
format='xml',
msg='The command executed successfully.',
changed=False,
failed=False,
stdout=expected_xml_output,
stdout_lines=expected_xml_output.splitlines(),
parsed_output=mock_instance.jxmlease.parse_etree(mock_xml_response)
)
mock_instance.dev.rpc.assert_called_once_with(
command_element,
ignore_warning=None,
normalize=True
)


# Mock the necessary functions and classes
@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
def test_multiple_commands_text(mock_junos_module):
# Set up the mock module instance
mock_instance = mock_junos_module.return_value
mock_instance.params = {
'commands': ['show version', 'show interfaces'],
'formats': ['text', 'text'],
'return_output': True
}
mock_instance.etree = etree
mock_instance.pyez_exception = MagicMock()
mock_instance.logger = MagicMock()
mock_instance.conn_type = "local"
mock_instance.dev = MagicMock()

# Create mock responses for text format
mock_response_version = etree.Element("rpc-reply")
mock_response_version.text = "Junos version information"
mock_response_interfaces = etree.Element("rpc-reply")
mock_response_interfaces.text = "Interface information"

def mock_rpc(rpc, ignore_warning=None, normalize=True):
if rpc.text == 'show version':
return mock_response_version
elif rpc.text == 'show interfaces':
return mock_response_interfaces

mock_instance.dev.rpc.side_effect = mock_rpc

with patch("sys.exit") as mock_exit:
main()

# Prepare expected outputs
expected_version_output = mock_response_version.text
expected_interfaces_output = mock_response_interfaces.text

# Assertions to check if the main function behaves as expected
mock_instance.fail_json.assert_not_called()
mock_instance.exit_json.assert_called_once_with(
results=[
{
'command': 'show version',
'format': 'text',
'msg': 'The command executed successfully.',
'changed': False,
'failed': False,
'stdout': expected_version_output,
'stdout_lines': expected_version_output.splitlines()
},
{
'command': 'show interfaces',
'format': 'text',
'msg': 'The command executed successfully.',
'changed': False,
'failed': False,
'stdout': expected_interfaces_output,
'stdout_lines': expected_interfaces_output.splitlines()
}
],
changed=False,
failed=False
)
assert mock_instance.dev.rpc.call_count == 2

# Mock the necessary functions and classes
@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
def test_command_dest(mock_junos_module):
# Set up the mock module instance
mock_instance = mock_junos_module.return_value
mock_instance.params = {
'commands': ['show version'],
'formats': ['text'],
'return_output': True,
'dest': '/tmp/show_version_output.txt'
}
mock_instance.etree = etree
mock_instance.pyez_exception = MagicMock()
mock_instance.logger = MagicMock()
mock_instance.conn_type = "local"
mock_instance.dev = MagicMock()

# Create a mock response that mimics the expected structure
mock_response = etree.Element("rpc-reply")
mock_response.text = "Output text"
mock_instance.dev.rpc.return_value = mock_response

# Mock the save_text_output method to ensure it is called with the correct parameters
with patch.object(mock_instance, 'save_text_output') as mock_save_text_output:
# Run the main function
with patch("sys.exit") as mock_exit:
main()

# Assertions to check if the main function behaves as expected
mock_instance.fail_json.assert_not_called()
mock_instance.exit_json.assert_called_once_with(
command='show version',
format='text',
msg='The command executed successfully.',
changed=False,
failed=False,
stdout='Output text',
stdout_lines=['Output text']
)
mock_save_text_output.assert_called_once_with(
'show version', 'text', 'Output text'
)

### Updated Unit Test for `dest_dir` Parameter

@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
def test_command_dest_dir(mock_junos_module):
# Set up the mock module instance
mock_instance = mock_junos_module.return_value
mock_instance.params = {
'commands': ['show version'],
'formats': ['text'],
'return_output': True,
'dest_dir': '/tmp'
}
mock_instance.etree = etree
mock_instance.pyez_exception = MagicMock()
mock_instance.logger = MagicMock()
mock_instance.conn_type = "local"
mock_instance.dev = MagicMock()

# Create a mock response that mimics the expected structure
mock_response = etree.Element("rpc-reply")
mock_response.text = "Output text"
mock_instance.dev.rpc.return_value = mock_response

# Mock the save_text_output method to ensure it is called with the correct parameters
with patch.object(mock_instance, 'save_text_output') as mock_save_text_output:
# Run the main function
with patch("sys.exit") as mock_exit:
main()

# Assertions to check if the main function behaves as expected
mock_instance.fail_json.assert_not_called()
mock_instance.exit_json.assert_called_once_with(
command='show version',
format='text',
msg='The command executed successfully.',
changed=False,
failed=False,
stdout='Output text',
stdout_lines=['Output text']
)
mock_save_text_output.assert_called_once_with(
'show version', 'text', 'Output text'
)

if __name__ == "__main__":
pytest.main([__file__])

61 changes: 61 additions & 0 deletions ansible_collections/juniper/device/tests/test_facts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import pytest
from unittest.mock import MagicMock, patch
from ansible_collections.juniper.device.plugins.module_utils import juniper_junos_common
from ansible_collections.juniper.device.plugins.modules.facts import get_facts_dict, main
import json

@pytest.fixture
def mock_junos_module():
mock_module = MagicMock()
mock_module.conn_type = "local"
mock_module.dev = MagicMock()
mock_module.dev.facts = {
"hostname": "router1",
"version": "18.1R3",
"2RE": True,
"version_info": MagicMock(),
"junos_info": {
"re0": {"object": MagicMock()},
"re1": {"object": MagicMock()},
}
}
mock_module.dev.re_name = "re0"
mock_module.dev.master = "re0"
return mock_module

def test_get_facts_dict(mock_junos_module):
facts = get_facts_dict(mock_junos_module)
assert facts["hostname"] == "router1"
assert facts["version"] == "18.1R3"
assert facts["has_2RE"] is True
assert "2RE" not in facts
assert isinstance(facts["version_info"], dict)
assert isinstance(facts["junos_info"]["re0"]["object"], dict)
assert isinstance(facts["junos_info"]["re1"]["object"], dict)
assert facts["re_name"] == "re0"
assert facts["master_state"] == "re0"

@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
def test_facts(mock_junos_module):
mock_instance = mock_junos_module.return_value
mock_instance.params.get.return_value = "/tmp"
mock_instance.etree = MagicMock()
mock_instance.dev = MagicMock()
mock_instance.dev.facts = {"hostname": "router1"}
mock_instance.dev.rpc.get_chassis_inventory.return_value = "<inventory>data</inventory>"
mock_instance.get_facts.return_value = {"hostname": "router1"}
mock_instance.get_configuration.side_effect = [("<config_data>", "<config_parsed>")]

with patch("builtins.open", new_callable=MagicMock):
with patch("sys.exit") as mock_exit:
main()
mock_instance.exit_json.assert_called_once_with(
changed=False,
failed=False,
ansible_facts={"junos": mock_instance.get_facts.return_value},
facts=mock_instance.get_facts.return_value
)

if __name__ == "__main__":
pytest.main([__file__])
59 changes: 59 additions & 0 deletions ansible_collections/juniper/device/tests/test_file_copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import pytest
from unittest.mock import MagicMock, patch
from ansible_collections.juniper.device.plugins.module_utils import configuration as cfg
from ansible_collections.juniper.device.plugins.module_utils import juniper_junos_common
from ansible_collections.juniper.device.plugins.modules.file_copy import main

@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
def test_file_copy_put(mock_junos_module):
mock_instance = mock_junos_module.return_value
mock_instance.params = {
"local_dir": "/local",
"remote_dir": "/remote",
"file": "testfile.txt",
"action": "put"
}

mock_instance.scp_file_copy_put.return_value = ("File copied successfully", True)

with patch("sys.exit") as mock_exit:
main()

mock_instance.scp_file_copy_put.assert_called_once_with(
"/local/testfile.txt", "/remote/testfile.txt"
)
mock_instance.exit_json.assert_called_once_with(
msg="File copied successfully",
changed=True,
failed=False
)

@patch("ansible_collections.juniper.device.plugins.module_utils.juniper_junos_common.JuniperJunosModule")
@patch("ansible_collections.juniper.device.plugins.module_utils.configuration.MIN_JXMLEASE_VERSION", new="1.0.0")
def test_file_copy_get(mock_junos_module):
mock_instance = mock_junos_module.return_value
mock_instance.params = {
"local_dir": "/local",
"remote_dir": "/remote",
"file": "testfile.txt",
"action": "get"
}

mock_instance.scp_file_copy_get.return_value = ("File copied successfully", True)

with patch("sys.exit") as mock_exit:
main()

mock_instance.scp_file_copy_get.assert_called_once_with(
"/remote/testfile.txt", "/local/testfile.txt"
)
mock_instance.exit_json.assert_called_once_with(
msg="File copied successfully",
changed=True,
failed=False
)

if __name__ == "__main__":
pytest.main([__file__])

Loading