Ejemplo n.º 1
0
def test_network_cli_close(conn):
    conn._terminal = MagicMock()
    conn._ssh_shell = MagicMock()
    conn._ssh_type_conn = MagicMock()
    conn._connected = True

    conn.close()

    assert conn._connected is False
    assert conn._terminal.on_close_shell.called is True
    assert conn._ssh_shell is None
    assert conn._ssh_type_conn is None
Ejemplo n.º 2
0
    def test_libssh_close(self):
        pc = PlayContext()
        conn = connection_loader.get("ansible.netcommon.libssh", pc,
                                     "/dev/null")
        conn.ssh = MagicMock()
        conn.sftp = MagicMock()
        conn.chan = MagicMock()

        conn.close()

        conn.sftp.close.assert_called()
        conn.chan.close.assert_called()
        conn.sftp.close.assert_called()
Ejemplo n.º 3
0
    def test_netconf__connect(self, mock_netconf_loader):
        pc = PlayContext()
        conn = connection_loader.get("netconf", pc, "/dev/null")

        mock_manager = MagicMock()
        mock_manager.session_id = "123456789"
        netconf.manager.connect = MagicMock(return_value=mock_manager)

        rc, out, err = conn._connect()

        self.assertEqual(0, rc)
        self.assertEqual(b"123456789", out)
        self.assertEqual(b"", err)
        self.assertTrue(conn._connected)
Ejemplo n.º 4
0
    def test_netconf__connect(self, mock_netconf_loader):
        pc = PlayContext()
        conn = connection_loader.get('netconf', pc, '/dev/null')

        mock_manager = MagicMock()
        mock_manager.session_id = '123456789'
        netconf.manager.connect = MagicMock(return_value=mock_manager)

        rc, out, err = conn._connect()

        self.assertEqual(0, rc)
        self.assertEqual(b'123456789', out)
        self.assertEqual(b'', err)
        self.assertTrue(conn._connected)
Ejemplo n.º 5
0
    def test_libssh_put_file(self, mocked_super, mock_exists):
        pc = PlayContext()
        conn = connection_loader.get("ansible.netcommon.libssh", pc,
                                     "/dev/null")

        mock_sftp = MagicMock()
        attr = {"sftp.return_value": mock_sftp}
        mock_ssh = MagicMock(**attr)
        conn.ssh = mock_ssh

        file_path = "test_libssh.py"
        conn.put_file(in_path=file_path, out_path=file_path)
        mock_sftp.put.assert_called_with(to_bytes(file_path),
                                         to_bytes(file_path))
Ejemplo n.º 6
0
    def test_network_cli_close_libssh(self, mocked_super):
        pc = PlayContext()
        pc.network_os = "ios"
        conn = connection_loader.get("network_cli", pc, "/dev/null")
        conn._ssh_type = "libssh"

        terminal = MagicMock(supports_multiplexing=False)
        conn._terminal = terminal
        conn._ssh_shell = MagicMock()
        conn._paramiko_conn = MagicMock()
        conn._connected = True
        conn.close()
        self.assertTrue(terminal.on_close_shell.called)
        self.assertIsNone(conn._ssh_shell)
        self.assertIsNone(conn._ssh_type_conn)
Ejemplo n.º 7
0
 def test_fn_run_fail_command(self):
     """Confirm clean fail with rc 1"""
     self._plugin._connection.socket_path = None
     self._plugin._low_level_execute_command = MagicMock()
     self._plugin._low_level_execute_command.return_value = {
         "rc": 1,
         "stdout": None,
         "stdout_lines": None,
         "stderr": None,
     }
     self._plugin._task.args = {
         "command": "ls",
         "parser": {
             "name": "a.b.c"
         },
     }
     task_vars = {"inventory_hostname": "mockdevice"}
     result = self._plugin.run(task_vars=task_vars)
     expected = {
         "failed": True,
         "msg": None,
         "stdout": None,
         "stdout_lines": None,
     }
     self.assertEqual(result, expected)
Ejemplo n.º 8
0
    def test_libssh_connect(self, mocked_super, mock_session):
        pc = PlayContext()
        pc.remote_addr = "localhost"
        pc.password = "******"
        pc.port = 8080
        pc.timeout = 60
        pc.remote_user = "******"

        conn = connection_loader.get(
            "ansible.netcommon.libssh", pc, "/dev/null"
        )

        conn.ssh = mock_session
        mock_connect = MagicMock()
        conn.ssh.connect = mock_connect
        conn._connect()
        conn.ssh.connect.assert_called_with(
            host="localhost",
            host_key_checking=False,
            look_for_keys=True,
            password="******",
            port=8080,
            timeout=60,
            user="******",
        )
Ejemplo n.º 9
0
 def setUp(self):
     task = MagicMock(Task)
     play_context = MagicMock()
     play_context.check_mode = False
     connection = MagicMock()
     fake_loader = DictDataLoader({})
     templar = Templar(loader=fake_loader)
     self._plugin = ActionModule(
         task=task,
         connection=connection,
         play_context=play_context,
         loader=fake_loader,
         templar=templar,
         shared_loader_obj=None,
     )
     self._plugin._task.action = "update_fact"
Ejemplo n.º 10
0
    def test_netconf_exec_command(self):
        pc = PlayContext()
        conn = connection_loader.get("netconf", pc, "/dev/null")

        conn._connected = True

        mock_reply = MagicMock(name="reply")
        type(mock_reply).data_xml = PropertyMock(return_value="<test/>")

        mock_manager = MagicMock(name="self._manager")
        mock_manager.rpc.return_value = mock_reply
        conn._manager = mock_manager

        out = conn.exec_command("<test/>")

        self.assertEqual("<test/>", out)
Ejemplo n.º 11
0
    def test_netconf_exec_command(self):
        pc = PlayContext()
        conn = connection_loader.get('netconf', pc, '/dev/null')

        conn._connected = True

        mock_reply = MagicMock(name='reply')
        type(mock_reply).data_xml = PropertyMock(return_value='<test/>')

        mock_manager = MagicMock(name='self._manager')
        mock_manager.rpc.return_value = mock_reply
        conn._manager = mock_manager

        out = conn.exec_command('<test/>')

        self.assertEqual('<test/>', out)
Ejemplo n.º 12
0
    def test_cli_config_generate_diff(self):
        self.conn.get_capabilities.return_value = (
            '{"device_operations": {"supports_generate_diff": true}}'
        )
        diff = MagicMock()
        diff.get.side_effect = ["set interface eth0 ip address dhcp", None]
        self.conn.get_diff.return_value = diff
        set_module_args({"config": "set interface eth0 ip address dhcp"})
        self.execute_module(
            changed=True, commands=["set interface eth0 ip address dhcp"]
        )
        self.conn.edit_config.assert_called_once_with(
            candidate=["set interface eth0 ip address dhcp"],
            commit=True,
            replace=None,
            comment=None,
        )

        diff.get.side_effect = [None, "new banner"]
        self.conn.get_diff.return_value = diff
        set_module_args({"config": "set banner\nnew banner"})
        self.execute_module(changed=True)
        self.conn.edit_banner.assert_called_once_with(
            candidate='"new banner"', commit=True
        )
Ejemplo n.º 13
0
    def test_fn_run_pass_missing_parser_constants(self, mock_rpc):
        """Check full module run using parser w/o
        DEFAULT_TEMPLATE_EXTENSION or PROVIDE_TEMPLATE_CONTENTS
        defined in the parser
        """
        mock_out = self._load_fixture("nxos_show_version.txt")

        class CliParser(CliParserBase):
            def parse(self, *_args, **kwargs):
                return {"parsed": mock_out}

        self._plugin._load_parser = MagicMock()
        self._plugin._load_parser.return_value = CliParser(None, None, None)

        mock_out = self._load_fixture("nxos_show_version.txt")
        mock_rpc.return_value = mock_out

        self._plugin._connection.socket_path = (
            tempfile.NamedTemporaryFile().name)
        template_path = os.path.join(os.path.dirname(__file__), "fixtures",
                                     "nxos_empty_parser.yaml")
        self._plugin._task.args = {
            "command": "show version",
            "parser": {
                "name": "ansible.netcommon.native",
                "template_path": template_path,
            },
        }
        task_vars = {"inventory_hostname": "mockdevice"}
        result = self._plugin.run(task_vars=task_vars)
        self.assertEqual(result["stdout"], mock_out)
        self.assertEqual(result["stdout_lines"], mock_out.splitlines())
        self.assertEqual(result["parsed"], mock_out)
Ejemplo n.º 14
0
    def test_fn_run_pass_missing_parser_in_parser(self, mock_rpc):
        """Check full module run using parser w/o
        a parser function defined in the parser
        defined in the parser
        """
        mock_out = self._load_fixture("nxos_show_version.txt")

        class CliParser(CliParserBase):
            pass

        self._plugin._load_parser = MagicMock()
        self._plugin._load_parser.return_value = CliParser(None, None, None)

        mock_out = self._load_fixture("nxos_show_version.txt")
        mock_rpc.return_value = mock_out

        self._plugin._connection.socket_path = (
            tempfile.NamedTemporaryFile().name)
        template_path = os.path.join(os.path.dirname(__file__), "fixtures",
                                     "nxos_empty_parser.yaml")
        self._plugin._task.args = {
            "command": "show version",
            "parser": {
                "name": "ansible.netcommon.native",
                "template_path": template_path,
            },
        }
        task_vars = {"inventory_hostname": "mockdevice"}
        with self.assertRaises(Exception) as error:
            self._plugin.run(task_vars=task_vars)
        self.assertIn("Unhandled", str(error.exception))
Ejemplo n.º 15
0
def test_network_cli__connect(conn, become_method, become_pass):
    conn.ssh = MagicMock()
    conn.receive = MagicMock()
    conn._terminal = MagicMock()
    conn._ssh_type_conn = MagicMock()

    if become_method:
        conn._play_context.become = True
        conn._play_context.become_method = become_method
        conn._play_context.become_pass = become_pass

    conn._connect()
    assert conn._ssh_type_conn._connect.called is True
    assert conn._terminal.on_open_shell.called is True
    if become_method:
        conn._terminal.on_become.assert_called_with(passwd=become_pass)
    else:
        assert conn._terminal.on_become.called is False
def test_backup_options(plugin, backup_dir, backup_file, role_path):
    plugin._task.args = {}
    content = "This is the backup content"

    # This doesn't need to be conditional, but doing so tests the equivalent
    # `if backup_options:` in the action plugin itself.
    if backup_dir or backup_file:
        plugin._task.args["backup_options"] = {
            "dir_path": backup_dir,
            "filename": backup_file,
        }

    # Test with role_path
    if role_path:
        plugin._task._role = MagicMock(Role)
        plugin._task._role._role_path = role_path

    result = {"__backup__": content}
    task_vars = dict(inventory_hostname="example.com")

    try:
        # result is updated in place, nothing is returned
        plugin._handle_backup_option(result, task_vars)
        assert not result.get("failed")

        with open(result["backup_path"]) as backup_file_obj:
            assert backup_file_obj.read() == content

        if backup_dir:
            backup_path = backup_dir
        elif role_path:
            backup_path = os.path.join(role_path, "backup")
        else:
            backup_path = "backup"

        if backup_file:
            backup_path = os.path.join(backup_path, backup_file)
        else:
            backup_path = os.path.join(
                backup_path,
                "example.com_config.{0}@{1}".format(result["date"],
                                                    result["time"]),
            )

        # check that expected and returned backup paths match
        assert os.path.samefile(backup_path, result["backup_path"])

        if backup_file:
            # check for idempotency
            result = {"__backup__": content}
            plugin._handle_backup_option(result, task_vars)
            assert not result.get("failed")
            assert result["changed"] is False

    finally:
        if os.path.exists(result["backup_path"]):
            os.remove(result["backup_path"])
    def test_cli_config_backup_returns__backup__(self, run_mock):
        self.conn.get_capabilities = MagicMock(return_value="{}")

        args = dict(backup=True)
        set_module_args(args)

        run_mock.return_value = {}

        result = self.execute_module()
        self.assertIn("__backup__", result)
Ejemplo n.º 18
0
    def test_network_cli__connect(self, mocked_super, mocked_terminal_loader):
        pc = PlayContext()
        pc.network_os = "ios"
        conn = connection_loader.get("network_cli", pc, "/dev/null")

        conn.ssh = MagicMock()
        conn.receive = MagicMock()

        conn._connect()
        self.assertTrue(conn._terminal.on_open_shell.called)
        self.assertFalse(conn._terminal.on_become.called)

        conn._play_context.become = True
        conn._play_context.become_method = "enable"
        conn._play_context.become_pass = "******"
        conn._connected = False

        conn._connect()
        conn._terminal.on_become.assert_called_with(passwd="password")
Ejemplo n.º 19
0
def test_network_cli_send(conn, response):
    conn.set_options(
        direct={
            "terminal_stderr_re": [{
                "pattern": "^ERROR"
            }],
            "terminal_stdout_re": [{
                "pattern": "device#"
            }],
        })
    mock__shell = MagicMock()

    conn._terminal = MagicMock()
    conn._ssh_shell = mock__shell
    conn._connected = True

    mock__shell.recv.side_effect = [response, None]
    conn.send(b"command")

    mock__shell.sendall.assert_called_with(b"command\r")
    assert to_text(conn._command_response) == "command response"
Ejemplo n.º 20
0
    def test_network_cli_send(self, mocked_connect, mocked_terminal_re):

        pc = PlayContext()
        pc.network_os = "ios"
        pc.remote_addr = "localhost"
        conn = connection_loader.get(
            "ansible.netcommon.network_cli", pc, "/dev/null"
        )

        mock__terminal = MagicMock()
        mocked_terminal_re.side_effect = [
            [re.compile(b"^ERROR")],
            [re.compile(b"device#")],
        ]
        conn._terminal = mock__terminal

        mock__shell = MagicMock()
        conn._ssh_shell = mock__shell

        response = b"""device#command
        command response

        device#
        """

        mock__shell.recv.side_effect = [response, None]
        conn.send(b"command")

        mock__shell.sendall.assert_called_with(b"command\r")
        self.assertEqual(to_text(conn._command_response), "command response")

        mock__shell.reset_mock()
        mock__shell.recv.side_effect = [b"ERROR: error message device#"]
        mocked_terminal_re.side_effect = [
            [re.compile(b"^ERROR")],
            [re.compile(b"device#")],
        ]
        with self.assertRaises(AnsibleConnectionFailure) as exc:
            conn.send(b"command")
        self.assertEqual(str(exc.exception), "ERROR: error message device#")
Ejemplo n.º 21
0
    def test_netconf_exec_command_invalid_request(self):
        pc = PlayContext()
        conn = connection_loader.get('netconf', pc, '/dev/null')

        conn._connected = True

        mock_manager = MagicMock(name='self._manager')
        conn._manager = mock_manager

        netconf.to_ele.return_value = None

        out = conn.exec_command('test string')

        self.assertEqual('unable to parse request', out)
Ejemplo n.º 22
0
    def test_netconf_exec_command_invalid_request(self):
        pc = PlayContext()
        conn = connection_loader.get("netconf", pc, "/dev/null")

        conn._connected = True

        mock_manager = MagicMock(name="self._manager")
        conn._manager = mock_manager

        netconf.to_ele.return_value = None

        out = conn.exec_command("test string")

        self.assertEqual("unable to parse request", out)
Ejemplo n.º 23
0
    def test_libssh_fetch_file(self, mocked_super, mock_session):
        pc = PlayContext()
        pc.remote_addr = "localhost"
        conn = connection_loader.get("ansible.netcommon.libssh", pc,
                                     "/dev/null")

        conn.ssh = mock_session
        mock_connect = MagicMock()
        conn.ssh.connect = mock_connect

        file_path = "test_libssh.py"
        conn.fetch_file(in_path=file_path, out_path=file_path)
        conn.sftp.get.assert_called_with(to_bytes(file_path),
                                         to_bytes(file_path))
Ejemplo n.º 24
0
 def test_fn_run_command_lx_rc0(self):
     """Check run command for non network"""
     response = "abc"
     self._plugin._connection.socket_path = None
     self._plugin._low_level_execute_command = MagicMock()
     self._plugin._low_level_execute_command.return_value = {
         "rc": 0,
         "stdout": response,
         "stdout_lines": response,
     }
     self._plugin._task.args = {"command": "ls"}
     self._plugin._run_command()
     self.assertEqual(self._plugin._result["stdout"], response)
     self.assertEqual(self._plugin._result["stdout_lines"], response)
Ejemplo n.º 25
0
def test_network_cli_exec_command(conn, command):
    mock_send = MagicMock(return_value=b"command response")
    conn.send = mock_send
    conn._ssh_shell = MagicMock()
    conn._ssh_type_conn = MagicMock()

    out = conn.exec_command(command)

    mock_send.assert_called_with(command=b"command")
    assert out == b"command response"
Ejemplo n.º 26
0
 def test_fn_update_template_path_mock_find_needle(self):
     """ Check the creation of the template_path
     mock the find needle fn so the template doesn't
     need to be in the default template folder
     """
     template_path = os.path.join(
         os.path.dirname(__file__), "fixtures", "nxos_show_version.yaml"
     )
     self._plugin._find_needle = MagicMock()
     self._plugin._find_needle.return_value = template_path
     self._plugin._task.args = {
         "parser": {"command": "show version", "os": "nxos"}
     }
     self._plugin._update_template_path("yaml")
     self.assertEqual(
         self._plugin._task.args["parser"]["template_path"], template_path
     )
def plugin():
    task = MagicMock(Task)
    task.action = "network"
    task._role = None
    connection = MagicMock()
    play_context = MagicMock()
    play_context.check_mode = False
    fake_loader = DictDataLoader({})
    templar = Templar(loader=fake_loader)

    plugin = action_loader.get(
        "ansible.netcommon.network",
        task=task,
        connection=connection,
        play_context=play_context,
        loader=fake_loader,
        templar=templar,
        shared_loader_obj=None,
    )
    return plugin
Ejemplo n.º 28
0
    def test_libssh_exec_command(self, mocked_super):
        pc = PlayContext()
        conn = connection_loader.get("ansible.netcommon.libssh", pc,
                                     "/dev/null")
        with self.assertRaises(AnsibleError):
            conn.exec_command(cmd="ls", in_data=True)

        mock_chan = MagicMock()
        mock_chan.request_shell = MagicMock()
        mock_chan.exec_command = MagicMock()
        mock_chan.exec_command.return_value = MagicMock(returncode=0,
                                                        stdout="echo hello",
                                                        stderr="")

        attr = {"new_channel.return_value": mock_chan}
        mock_ssh = MagicMock(**attr)
        conn.ssh = mock_ssh

        rc, out, err = conn.exec_command(cmd="echo hello")

        self.assertEqual((rc, out, err), (0, "echo hello", ""))
Ejemplo n.º 29
0
    def test_network_cli_exec_command(self, mocked_super):
        pc = PlayContext()
        pc.network_os = "ios"
        conn = connection_loader.get("network_cli", pc, "/dev/null")

        mock_send = MagicMock(return_value=b"command response")
        conn.send = mock_send
        conn._ssh_shell = MagicMock()

        # test sending a single command and converting to dict
        out = conn.exec_command("command")
        self.assertEqual(out, b"command response")
        mock_send.assert_called_with(command=b"command")

        # test sending a json string
        out = conn.exec_command(json.dumps({"command": "command"}))
        self.assertEqual(out, b"command response")
        mock_send.assert_called_with(command=b"command")
Ejemplo n.º 30
0
from ansible_collections.ansible.netcommon.tests.unit.compat import unittest
from ansible_collections.ansible.netcommon.tests.unit.compat.mock import (
    patch,
    MagicMock,
    PropertyMock,
)
from ansible.playbook.play_context import PlayContext

pytest.importorskip("ncclient")

PY3 = sys.version_info[0] == 3

builtin_import = __import__

mock_ncclient = MagicMock(name="ncclient")
mock_ncclient.__version__ = "0.6.10"


def import_mock(name, *args):
    if name.startswith("ncclient"):
        return mock_ncclient
    return builtin_import(name, *args)


if PY3:
    with patch("builtins.__import__", side_effect=import_mock):
        from ansible_collections.ansible.netcommon.plugins.connection import (
            netconf, )
        from ansible.plugins.loader import connection_loader
else: