Пример #1
0
def test_multi_response():
    host = "localhost"
    response1 = Response(host, "ls -al")
    response2 = Response(host, "ls -al")
    multi_response = MultiResponse()
    assert multi_response.host == ""
    multi_response.extend([response1, response2])
    assert len(multi_response) == 2
    assert multi_response.failed is True
    assert (
        repr(multi_response) ==
        "[Response(host='localhost',channel_input='ls -al',textfsm_platform='',genie_platform='',failed_when_contains=None), Response(host='localhost',channel_input='ls -al',textfsm_platform='',genie_platform='',failed_when_contains=None)]"
    )
    assert str(multi_response
               ) == "MultiResponse <Success: False; Response Elements: 2>"
    with pytest.raises(ScrapliCommandFailure):
        multi_response.raise_for_status()
    multi_response[0].failed = False
    multi_response[1].failed = False
    assert multi_response.failed is False
    assert multi_response.raise_for_status() is None
    assert multi_response.host == host
    assert (
        repr(multi_response) ==
        "[Response(host='localhost',channel_input='ls -al',textfsm_platform='',genie_platform='',failed_when_contains=None), Response(host='localhost',channel_input='ls -al',textfsm_platform='',genie_platform='',failed_when_contains=None)]"
    )
    assert str(multi_response
               ) == "MultiResponse <Success: True; Response Elements: 2>"
    assert multi_response.result == "ls -al\nls -al\n"
Пример #2
0
def test_response_parse_textfsm_no_template():
    response = Response("localhost",
                        channel_input="show ip arp",
                        textfsm_platform="potato")
    response_bytes = b""
    response._record_response(response_bytes)
    assert response.textfsm_parse_output() == []
Пример #3
0
def test_response_parse_textfsm_fail():
    response = Response("localhost",
                        channel_input="show ip arp",
                        textfsm_platform="cisco_ios")
    response_bytes = b""
    response._record_response(response_bytes)
    assert response.textfsm_parse_output() == []
Пример #4
0
def test_response_parse_ttp():
    response = Response("localhost",
                        channel_input="show ip arp",
                        genie_platform="iosxe")

    # example data lifted straight out of ttp docs
    ttp_template = """
    interface {{ interface }}
     ip address {{ ip }}/{{ mask }}
     description {{ description }}
     ip vrf {{ vrf }}
    """

    response_bytes = b"""    interface Loopback0
     description Router-id-loopback
     ip address 192.168.0.113/24
    !
    interface Vlan778
     description CPE_Acces_Vlan
     ip address 2002::fd37/124
     ip vrf CPE1
    !
"""
    response._record_response(response_bytes)
    result = response.ttp_parse_output(template=ttp_template)
    assert result[0][0]["ip"] == "192.168.0.113"
Пример #5
0
def test_response_parse_genie_fail():
    response = Response("localhost",
                        channel_input="show ip arp",
                        genie_platform="iosxe")
    response_bytes = b""
    response._record_response(response_bytes)
    assert response.genie_parse_output() == []
Пример #6
0
def test_response_parse_ttp_fail():
    response = Response("localhost",
                        channel_input="show ip arp",
                        genie_platform="iosxe")
    response_bytes = b""
    response._record_response(response_bytes)
    assert response.ttp_parse_output(template="blah") == [{}]
Пример #7
0
def test_post_send_configs(sync_cisco_iosxe_conn):
    response_one = Response("localhost", "some input", failed_when_contains=["something"])
    response_one._record_response(result=b"greatsucccess")
    multi_response = MultiResponse()
    multi_response.append(response_one)
    updated_responses = sync_cisco_iosxe_conn._post_send_configs(responses=multi_response)
    assert updated_responses[0].textfsm_platform == "cisco_iosxe"
    assert updated_responses[0].genie_platform == "iosxe"
Пример #8
0
def test_record_response_unicodedecodeerror():
    # this test validates that we catch unicdedecodeerror when decoding raw result
    response = Response("localhost",
                        channel_input="show ip arp",
                        genie_platform="iosxe")
    response_bytes = b"Manufacturer name :p\xb67\x038\x93\xa5\x03\x10\n"
    response.record_response(response_bytes)
    assert repr(
        response.result) == "'Manufacturer name :p¶7\\x038\\x93¥\\x03\\x10\\n'"
Пример #9
0
def test_response_parse_textfsm(parse_type):
    to_dict = parse_type[0]
    expected_result = parse_type[1]
    response = Response("localhost", channel_input="show ip arp", textfsm_platform="cisco_ios")
    response_str = """Protocol  Address          Age (min)  Hardware Addr   Type   Interface
Internet  172.31.254.1            -   0000.0c07.acfe  ARPA   Vlan254
Internet  172.31.254.2            -   c800.84b2.e9c2  ARPA   Vlan254
"""
    response._record_response(response_str)
    assert response.textfsm_parse_output(to_dict=to_dict)[0] == expected_result
Пример #10
0
def test_post_send_config_failed(sync_cisco_iosxe_conn):
    response_one = Response("localhost", "some input", failed_when_contains=["something"])
    response_one._record_response(result=b"something")
    multi_response = MultiResponse()
    multi_response.append(response_one)
    updated_responses = sync_cisco_iosxe_conn._post_send_config(
        config="whocares", multi_response=multi_response
    )
    assert updated_responses.textfsm_platform == "cisco_iosxe"
    assert updated_responses.genie_platform == "iosxe"
    assert updated_responses.failed is True
Пример #11
0
def test_response_parse_genie():
    response = Response("localhost", channel_input="show ip arp", genie_platform="iosxe")
    response_str = """Protocol  Address          Age (min)  Hardware Addr   Type   Interface
Internet  172.31.254.1            -   0000.0c07.acfe  ARPA   Vlan254
Internet  172.31.254.2            -   c800.84b2.e9c2  ARPA   Vlan254
"""
    response._record_response(response_str)
    result = response.genie_parse_output()
    assert (
        result["interfaces"]["Vlan254"]["ipv4"]["neighbors"]["172.31.254.1"]["ip"] == "172.31.254.1"
    )
 def mock_send_interactive(cls,
                           interact_events,
                           failed_when_contains=None,
                           privilege_level=""):
     response = Response(
         host="fake_as_heck",
         channel_input=", ".join([event[0] for event in interact_events]),
     )
     response._record_response(
         b"clear logg\nClear logging buffer [confirm]\n\ncsr1000v#")
     return response
Пример #13
0
 def mock_send_config(
     cls,
     config,
     strip_prompt,
     failed_when_contains="",
     stop_on_failed=False,
     privilege_level="",
     timeout_ops=None,
 ):
     response = Response(host="fake_as_heck", channel_input=config)
     response._record_response(b"some stuff about whatever")
     return response
Пример #14
0
def test_response_parse_textfsm_string_path():
    template = _textfsm_get_template("cisco_ios", "show ip arp").name
    response = Response("localhost",
                        channel_input="show ip arp",
                        textfsm_platform="cisco_ios")
    response_bytes = b"""Protocol  Address          Age (min)  Hardware Addr   Type   Interface
Internet  172.31.254.1            -   0000.0c07.acfe  ARPA   Vlan254
Internet  172.31.254.2            -   c800.84b2.e9c2  ARPA   Vlan254
"""
    response.record_response(response_bytes)
    result = response.textfsm_parse_output(template=template)
    assert result[0]["address"] == "172.31.254.1"
Пример #15
0
def test_post_send_config(base_network_driver):
    responses = [
        Response(host="localhost", channel_input="nothing1"),
        Response(host="localhost", channel_input="nothing2"),
    ]
    for response in responses:
        response.record_response(result=b"nada")
    responses[0].failed = True
    actual_response = base_network_driver._post_send_config(
        multi_response=responses, config="nothing1\nnothing2")
    assert actual_response.result == "nada\nnada"
    assert actual_response.failed is True
Пример #16
0
def test_response_init():
    response = Response("localhost", "ls -al", failed_when_contains="tacocat")
    response_start_time = str(datetime.now())[:-7]
    assert response.host == "localhost"
    assert response.channel_input == "ls -al"
    assert str(response.start_time)[:-7] == response_start_time
    assert response.failed is True
    assert bool(response) is True
    assert repr(response) == "Response <Success: False>"
    assert str(response) == "Response <Success: False>"
    assert response.failed_when_contains == ["tacocat"]
    with pytest.raises(ScrapliCommandFailure):
        response.raise_for_status()
 def mock_send_commands_from_file(
     cls,
     file,
     strip_prompt,
     failed_when_contains="",
     stop_on_failed=False,
     privilege_level="",
     timeout_ops=None,
 ):
     with open(file, "r") as f:
         commands = f.read().splitlines()
     response = Response(host="fake_as_heck", channel_input=commands[0])
     response._record_response(b"some stuff about whatever")
     return [response]
Пример #18
0
def test_response_record_result():
    response = Response("localhost", "ls -al")
    response_end_time = str(datetime.now())[:-7]
    response_bytes = b"""
ls -al
total 264
drwxr-xr-x  34 carl  staff   1088 Jan 27 19:07 ./
drwxr-xr-x  21 carl  staff    672 Jan 25 15:56 ../
-rw-r--r--   1 carl  staff  53248 Jan 27 19:07 .coverage
drwxr-xr-x  12 carl  staff    384 Jan 27 19:13 .git/"""
    response._record_response(response_bytes)
    assert str(response.finish_time)[:-7] == response_end_time
    assert response.result == response_bytes.decode()
    assert response.failed is False
Пример #19
0
def test_response_record_result_failed_when_success():
    response = Response("localhost", "ls -al", failed_when_contains=["!racecar!"])
    response_end_time = str(datetime.now())[:-7]
    response_str = """
ls -al
total 264
drwxr-xr-x  34 carl  staff   1088 Jan 27 19:07 ./
drwxr-xr-x  21 carl  staff    672 Jan 25 15:56 ../
-rw-r--r--   1 carl  staff  53248 Jan 27 19:07 .coverage
drwxr-xr-x  12 carl  staff    384 Jan 27 19:13 .git/"""
    response._record_response(response_str)
    assert str(response.finish_time)[:-7] == response_end_time
    assert response.result == response_str
    assert response.failed is False
def test_update_response(sync_cisco_iosxe_conn):
    response = Response("localhost", "some input")
    sync_cisco_iosxe_conn.textfsm_platform = "racecar"
    sync_cisco_iosxe_conn.genie_platform = "tacocat"
    sync_cisco_iosxe_conn._update_response(response)
    assert response.textfsm_platform == "racecar"
    assert response.genie_platform == "tacocat"
    def _pre_send_command(
        host: str,
        command: str,
        failed_when_contains: Optional[Union[str,
                                             List[str]]] = None) -> Response:
        """
        Handle pre "send_command" tasks for consistency between sync/async versions

        Args:
            host: string name of the host
            command: string to send to device in privilege exec mode
            failed_when_contains: string or list of strings indicating failure if found in response

        Returns:
            Response: Scrapli Response object

        Raises:
            TypeError: if command is anything but a string

        """
        if not isinstance(command, str):
            raise TypeError(
                f"`send_command` expects a single string, got {type(command)}, "
                "to send a list of commands use the `send_commands` method instead."
            )

        response = Response(
            host=host,
            channel_input=command,
            failed_when_contains=failed_when_contains,
        )

        return response
Пример #22
0
def test_pre_and_post_clear_config_sessions(eos_base_cfg_object, dummy_logger):
    eos_base_cfg_object.logger = dummy_logger
    eos_base_cfg_object.conn = Scrapli(host="localhost", platform="arista_eos")
    pre_response = eos_base_cfg_object._pre_clear_config_sessions()
    assert isinstance(pre_response, ScrapliCfgResponse)

    scrapli_response = Response(host="localhost",
                                channel_input="diff a config")
    post_response = eos_base_cfg_object._post_clear_config_sessions(
        response=pre_response, scrapli_responses=[scrapli_response])
    assert post_response.result == "failed to clear device configuration session(s)"

    scrapli_response.failed = False
    post_response = eos_base_cfg_object._post_clear_config_sessions(
        response=pre_response, scrapli_responses=[scrapli_response])
    assert post_response.result == "configuration session(s) cleared"
Пример #23
0
def test_multi_response():
    response1 = Response("localhost", "ls -al")
    response2 = Response("localhost", "ls -al")
    multi_response = MultiResponse([response1, response2])
    assert len(multi_response) == 2
    assert multi_response.failed is True
    assert repr(multi_response) == "MultiResponse <Success: False; Response Elements: 2>"
    assert str(multi_response) == "MultiResponse <Success: False; Response Elements: 2>"
    with pytest.raises(ScrapliCommandFailure):
        multi_response.raise_for_status()
    multi_response[0].failed = False
    multi_response[1].failed = False
    assert multi_response.failed is False
    assert multi_response.raise_for_status() is None
    assert repr(multi_response) == "MultiResponse <Success: True; Response Elements: 2>"
    assert str(multi_response) == "MultiResponse <Success: True; Response Elements: 2>"
Пример #24
0
 def mock_send_configs(cls, configs, strip_prompt):
     responses = []
     response = Response(host="fake_as_heck", channel_input=configs[0])
     response._record_response("some stuff about whatever")
     responses.append(response)
     response = Response(host="fake_as_heck", channel_input=configs[1])
     response._record_response("some stuff about whatever")
     responses.append(response)
     return [response]
Пример #25
0
def test_update_response(mocked_network_driver):
    response = Response("localhost", "some input")
    conn = mocked_network_driver([])
    conn.textfsm_platform = "racecar"
    conn.genie_platform = "tacocat"
    conn._update_response(response)
    assert response.textfsm_platform == "racecar"
    assert response.genie_platform == "tacocat"
Пример #26
0
def test_post_commit_config(base_cfg_object):
    # send a failed response so we also cover the logger message indicating that there was a fail
    commit_config_response = ScrapliCfgResponse(host="localhost")
    scrapli_response = Response(host="localhost",
                                channel_input="commit a config")
    post_commit_config_response = base_cfg_object._post_commit_config(
        response=commit_config_response, scrapli_responses=[scrapli_response])
    assert post_commit_config_response.failed is True
Пример #27
0
    def _update_response(self, response: Response) -> None:
        """
        Update response with network driver specific data

        This happens here as the underlying channel provides a response object but is unaware of any
        of the network/platform specific attributes that may need to get updated

        Args:
            response: response to update

        Returns:
            N/A  # noqa: DAR202

        Raises:
            N/A

        """
        response.textfsm_platform = self.textfsm_platform
        response.genie_platform = self.genie_platform
Пример #28
0
def test_post_get_version(base_cfg_object):
    # send a failed response so we also cover the logger message indicating that there was a fail
    get_version_response = ScrapliCfgResponse(host="localhost")
    scrapli_response = Response(host="localhost", channel_input="show version")
    post_get_version_response = base_cfg_object._post_get_version(
        response=get_version_response,
        scrapli_responses=[scrapli_response],
        result="blah")
    assert post_get_version_response.failed is True
    assert post_get_version_response.result == "blah"
    def _post_send_command(raw_response: bytes, processed_response: bytes,
                           response: Response) -> Response:
        """
        Handle post "send_command" tasks for consistency between sync/async versions

        Args:
            raw_response: raw response returned from the channel
            processed_response: processed response returned from the channel
            response: response object to update with channel results

        Returns:
            Response: Scrapli Response object

        Raises:
            N/A

        """
        response._record_response(result=processed_response)  # pylint: disable=W0212
        response.raw_result = raw_response
        return response
Пример #30
0
    def send_inputs_interact(self,
                             channel_inputs: List[str],
                             hidden_response: bool = False) -> Response:
        """
        Send inputs in an interactive fashion, used to handle prompts that occur after an input.

        Args:
            channel_inputs: list of four string elements representing...
                channel_input - initial input to send
                expected_prompt - prompt to expect after initial input
                response - response to prompt
                final_prompt - final prompt to expect
            hidden_response: True/False response is hidden (i.e. password input)

        Returns:
            Response: scrapli Response object

        Raises:
            TypeError: if inputs is not tuple or list

        """
        if not isinstance(channel_inputs, list):
            raise TypeError(
                f"`send_inputs_interact` expects a List, got {type(channel_inputs)}"
            )
        channel_input, expectation, channel_response, finale = channel_inputs
        response = Response(
            self.transport.host,
            channel_input,
            expectation=expectation,
            channel_response=channel_response,
            finale=finale,
        )
        raw_result, processed_result = self._send_input_interact(
            channel_input, expectation, channel_response, finale,
            hidden_response)
        response.raw_result = raw_result.decode()
        response.record_response(processed_result.decode().strip())
        return response