Best Python code snippet using uiautomator
conftest.py
Source:conftest.py  
1#!/usr/bin/env python2"""py.test fixtures to be used in netmiko test suite."""3from os import path4import os5import pytest6from netmiko import ConnectHandler, FileTransfer, InLineTransfer, SSHDetect7from tests.test_utils import parse_yaml8PWD = path.dirname(path.realpath(__file__))9def pytest_addoption(parser):10    """Add test_device option to py.test invocations."""11    parser.addoption(12        "--test_device",13        action="store",14        dest="test_device",15        type=str,16        help="Specify the platform type to test on",17    )18@pytest.fixture(scope="module")19def net_connect(request):20    """21    Create the SSH connection to the remote device22    Return the netmiko connection object23    """24    device_under_test = request.config.getoption("test_device")25    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")26    device = test_devices[device_under_test]27    device["verbose"] = False28    conn = ConnectHandler(**device)29    return conn30@pytest.fixture(scope="module")31def net_connect_cmd_verify(request):32    """33    Create the SSH connection to the remote device34    Return the netmiko connection object35    Set global_cmd_verify = False36    """37    device_under_test = request.config.getoption("test_device")38    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")39    device = test_devices[device_under_test]40    device["verbose"] = False41    device["global_cmd_verify"] = False42    conn = ConnectHandler(**device)43    return conn44@pytest.fixture(scope="function")45def net_connect_newconn(request):46    """47    Create the SSH connection to the remote device48    Return the netmiko connection object.49    Force a new connection for each test.50    """51    device_under_test = request.config.getoption("test_device")52    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")53    device = test_devices[device_under_test]54    device["verbose"] = False55    conn = ConnectHandler(**device)56    return conn57@pytest.fixture()58def net_connect_cm(request):59    """60    Create the SSH connection to the remote device using a context manager61    retrieve the find_prompt() data and close the connection.62    """63    device_under_test = request.config.getoption("test_device")64    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")65    device = test_devices[device_under_test]66    device["verbose"] = False67    my_prompt = ""68    with ConnectHandler(**device) as conn:69        my_prompt = conn.find_prompt()70    return my_prompt71@pytest.fixture(scope="module")72def net_connect_slog_wr(request):73    """74    Create the SSH connection to the remote device. Modify session_log init arguments.75    Return the netmiko connection object.76    """77    device_under_test = request.config.getoption("test_device")78    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")79    device = test_devices[device_under_test]80    device["verbose"] = False81    # Overwrite default session_log location82    device["session_log"] = "SLOG/cisco881_slog_wr.log"83    device["session_log_record_writes"] = True84    conn = ConnectHandler(**device)85    return conn86@pytest.fixture(scope="module")87def device_slog(request):88    """89    Create the SSH connection to the remote device. Modify session_log init arguments.90    Return the netmiko device (not connected)91    """92    device_under_test = request.config.getoption("test_device")93    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")94    device = test_devices[device_under_test]95    device["verbose"] = False96    device["session_log_file_mode"] = "append"97    return device98@pytest.fixture(scope="module")99def expected_responses(request):100    """101    Parse the responses.yml file to get a responses dictionary102    """103    device_under_test = request.config.getoption("test_device")104    responses = parse_yaml(PWD + "/etc/responses.yml")105    return responses[device_under_test]106@pytest.fixture(scope="module")107def commands(request):108    """109    Parse the commands.yml file to get a commands dictionary110    """111    device_under_test = request.config.getoption("test_device")112    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")113    device = test_devices[device_under_test]114    test_platform = device["device_type"]115    commands_yml = parse_yaml(PWD + "/etc/commands.yml")116    return commands_yml[test_platform]117def delete_file_nxos(ssh_conn, dest_file_system, dest_file):118    """119    nxos1# delete bootflash:test2.txt120    Do you want to delete "/test2.txt" ? (yes/no/abort)   [y] y121    """122    if not dest_file_system:123        raise ValueError("Invalid file system specified")124    if not dest_file:125        raise ValueError("Invalid dest file specified")126    full_file_name = "{}{}".format(dest_file_system, dest_file)127    cmd = "delete {}".format(full_file_name)128    output = ssh_conn.send_command_timing(cmd)129    if "yes/no/abort" in output and dest_file in output:130        output += ssh_conn.send_command_timing(131            "y", strip_command=False, strip_prompt=False132        )133        return output134    else:135        output += ssh_conn.send_command_timing("abort")136    raise ValueError("An error happened deleting file on Cisco NX-OS")137def delete_file_ios(ssh_conn, dest_file_system, dest_file):138    """Delete a remote file for a Cisco IOS device."""139    if not dest_file_system:140        raise ValueError("Invalid file system specified")141    if not dest_file:142        raise ValueError("Invalid dest file specified")143    full_file_name = f"{dest_file_system}/{dest_file}"144    cmd = f"delete {full_file_name}"145    output = ssh_conn.send_command_timing(cmd, delay_factor=2)146    if "Delete" in output and dest_file in output:147        output += ssh_conn.send_command_timing("\n", delay_factor=2)148        if "Delete" in output and full_file_name in output and "confirm" in output:149            output += ssh_conn.send_command_timing("y", delay_factor=2)150            return output151        else:152            output += ssh_conn.send_command_timing("n", delay_factor=2)153    raise ValueError("An error happened deleting file on Cisco IOS")154def delete_file_dellos10(ssh_conn, dest_file_system, dest_file):155    """Delete a remote file for a Dell OS10 device."""156    if not dest_file:157        raise ValueError("Invalid dest file specified")158    cmd = "delete home://{}".format(dest_file)159    output = ssh_conn.send_command_timing(cmd)160    if "Proceed to delete" in output:161        output = ssh_conn.send_command_timing("yes")162        return output163    raise ValueError("An error happened deleting file on Dell OS10")164def delete_file_generic(ssh_conn, dest_file_system, dest_file):165    """Delete a remote file for a Junos device."""166    full_file_name = "{}/{}".format(dest_file_system, dest_file)167    cmd = "rm {}".format(full_file_name)168    output = ssh_conn._enter_shell()169    output += ssh_conn.send_command_timing(cmd, strip_command=False, strip_prompt=False)170    output += ssh_conn._return_cli()171    return output172def delete_file_ciena_saos(ssh_conn, dest_file_system, dest_file):173    """Delete a remote file for a ciena device."""174    full_file_name = "{}/{}".format(dest_file_system, dest_file)175    cmd = "file rm {}".format(full_file_name)176    output = ssh_conn.send_command_timing(cmd, strip_command=False, strip_prompt=False)177    return output178def delete_file_nokia_sros(ssh_conn, dest_file_system, dest_file):179    """Delete a remote file for a Nokia SR OS device."""180    full_file_name = "{}/{}".format(dest_file_system, dest_file)181    cmd = "file delete {} force".format(full_file_name)182    cmd_prefix = ""183    if "@" in ssh_conn.base_prompt:184        cmd_prefix = "//"185    ssh_conn.send_command(cmd_prefix + "environment no more")186    output = ssh_conn.send_command_timing(187        cmd_prefix + cmd, strip_command=False, strip_prompt=False188    )189    return output190@pytest.fixture(scope="module")191def scp_fixture(request):192    """193    Create an FileTransfer object.194    Return a tuple (ssh_conn, scp_handle)195    """196    platform_args = get_platform_args()197    # Create the files198    with open("test9.txt", "w") as f:199        # Not important what it is in the file200        f.write("no logging console\n")201    with open("test2_src.txt", "w") as f:202        # Not important what it is in the file203        f.write("no logging console\n")204        f.write("logging buffered 10000\n")205    device_under_test = request.config.getoption("test_device")206    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")207    device = test_devices[device_under_test]208    device["verbose"] = False209    ssh_conn = ConnectHandler(**device)210    platform = device["device_type"]211    dest_file_system = platform_args[platform]["file_system"]212    if "ciena_saos" in platform and ssh_conn.username:213        dest_file_system = f"/tmp/users/{ssh_conn.username}"214    source_file = "test9.txt"215    dest_file = "test9.txt"216    local_file = "testx.txt"217    direction = "put"218    scp_transfer = FileTransfer(219        ssh_conn,220        source_file=source_file,221        dest_file=dest_file,222        file_system=dest_file_system,223        direction=direction,224    )225    scp_transfer.establish_scp_conn()226    # Make sure SCP is enabled227    if platform_args[platform]["enable_scp"]:228        scp_transfer.enable_scp()229    # Delete the test transfer files230    if scp_transfer.check_file_exists():231        func = platform_args[platform]["delete_file"]232        func(ssh_conn, dest_file_system, dest_file)233    if os.path.exists(local_file):234        os.remove(local_file)235    return (ssh_conn, scp_transfer)236@pytest.fixture(scope="module")237def scp_fixture_get(request):238    """239    Create an FileTransfer object (direction=get)240    Return a tuple (ssh_conn, scp_handle)241    """242    platform_args = get_platform_args()243    device_under_test = request.config.getoption("test_device")244    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")245    device = test_devices[device_under_test]246    device["verbose"] = False247    ssh_conn = ConnectHandler(**device)248    platform = device["device_type"]249    dest_file_system = platform_args[platform]["file_system"]250    source_file = "test9.txt"251    local_file = "testx.txt"252    dest_file = local_file253    direction = "get"254    scp_transfer = FileTransfer(255        ssh_conn,256        source_file=source_file,257        dest_file=dest_file,258        file_system=dest_file_system,259        direction=direction,260    )261    scp_transfer.establish_scp_conn()262    # Make sure SCP is enabled263    if platform_args[platform]["enable_scp"]:264        scp_transfer.enable_scp()265    # Delete the test transfer files266    if os.path.exists(local_file):267        os.remove(local_file)268    return (ssh_conn, scp_transfer)269@pytest.fixture(scope="module")270def tcl_fixture(request):271    """272    Create an InLineTransfer object.273    Return a tuple (ssh_conn, tcl_handle)274    """275    # Create the files276    with open("test9.txt", "w") as f:277        # Not important what it is in the file278        f.write("no logging console\n")279    device_under_test = request.config.getoption("test_device")280    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")281    device = test_devices[device_under_test]282    device["verbose"] = False283    ssh_conn = ConnectHandler(**device)284    dest_file_system = "flash:"285    source_file = "test9.txt"286    dest_file = "test9.txt"287    local_file = "testx.txt"288    direction = "put"289    tcl_transfer = InLineTransfer(290        ssh_conn,291        source_file=source_file,292        dest_file=dest_file,293        file_system=dest_file_system,294        direction=direction,295    )296    # Delete the test transfer files297    if tcl_transfer.check_file_exists():298        delete_file_ios(ssh_conn, dest_file_system, dest_file)299    if os.path.exists(local_file):300        os.remove(local_file)301    return (ssh_conn, tcl_transfer)302@pytest.fixture(scope="module")303def ssh_autodetect(request):304    """Create an SSH autodetect object.305    return (ssh_conn, real_device_type)306    """307    device_under_test = request.config.getoption("test_device")308    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")309    device = test_devices[device_under_test]310    device["verbose"] = False311    my_device_type = device.pop("device_type")312    device["device_type"] = "autodetect"313    conn = SSHDetect(**device)314    return (conn, my_device_type)315@pytest.fixture(scope="module")316def scp_file_transfer(request):317    """318    Testing file_transfer319    Return the netmiko connection object320    """321    platform_args = get_platform_args()322    # Create the files323    with open("test9.txt", "w") as f:324        # Not important what it is in the file325        f.write("no logging console\n")326    with open("test2_src.txt", "w") as f:327        # Not important what it is in the file328        f.write("no logging console\n")329        f.write("logging buffered 10000\n")330    device_under_test = request.config.getoption("test_device")331    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")332    device = test_devices[device_under_test]333    device["verbose"] = False334    ssh_conn = ConnectHandler(**device)335    platform = device["device_type"]336    file_system = platform_args[platform]["file_system"]337    source_file = "test9.txt"338    dest_file = "test9.txt"339    local_file = "testx.txt"340    alt_file = "test2.txt"341    direction = "put"342    scp_transfer = FileTransfer(343        ssh_conn,344        source_file=source_file,345        dest_file=dest_file,346        file_system=file_system,347        direction=direction,348    )349    scp_transfer.establish_scp_conn()350    # Delete the test transfer files351    if scp_transfer.check_file_exists():352        func = platform_args[platform]["delete_file"]353        func(ssh_conn, file_system, dest_file)354    if os.path.exists(local_file):355        os.remove(local_file)356    if os.path.exists(alt_file):357        os.remove(alt_file)358    return (ssh_conn, file_system)359def get_platform_args():360    return {361        "cisco_ios": {362            "file_system": "flash:",363            "enable_scp": True,364            "delete_file": delete_file_ios,365        },366        "juniper_junos": {367            "file_system": "/var/tmp",368            "enable_scp": False,369            "delete_file": delete_file_generic,370        },371        "arista_eos": {372            "file_system": "/mnt/flash",373            "enable_scp": False,374            "delete_file": delete_file_generic,375        },376        "cisco_nxos": {377            "file_system": "bootflash:",378            "enable_scp": False,379            "delete_file": delete_file_nxos,380        },381        "cisco_xr": {382            "file_system": "disk0:",383            "enable_scp": False,384            # Delete pattern is the same on IOS-XR385            "delete_file": delete_file_ios,386        },387        "linux": {388            "file_system": "/var/tmp",389            "enable_scp": False,390            "delete_file": delete_file_generic,391        },392        "dellos10": {393            "file_system": "/home/admin",394            "enable_scp": False,395            "delete_file": delete_file_dellos10,396        },397        "ciena_saos": {398            "file_system": "/tmp/users/ciena",399            "enable_scp": False,400            "delete_file": delete_file_ciena_saos,401        },402        "nokia_sros": {403            "file_system": "cf3:",404            "enable_scp": False,405            "delete_file": delete_file_nokia_sros,406        },...test_show.py
Source:test_show.py  
1from pathlib import Path2from typer.testing import CliRunner3import json4# you need to pip install -e centralcli from the root of the cloned repo5try:6    from cli import app  # type: ignore # NoQA7except (ImportError, ModuleNotFoundError):8    print('\nYou need to `pip install -e centralcli` from base directory\n')9    raise10runner = CliRunner()11test_dev_file = Path(__file__).parent / 'test_devices.json'12if test_dev_file.is_file():13    TEST_DEVICES = json.loads(test_dev_file.read_text())14else:15    raise UserWarning(f'\nYou need to populate {test_dev_file}\n')16def test_show_aps():17    result = runner.invoke(app, ["show", "aps", "--debug"],)18    assert result.exit_code == 019    assert "site" in result.stdout20    assert "status" in result.stdout21def test_show_switches():22    result = runner.invoke(app, ["show", "switches", "--debug"],)23    assert result.exit_code == 024    assert "site" in result.stdout25    assert "status" in result.stdout26def test_show_gateways():27    result = runner.invoke(app, ["show", "gateways"],)28    assert result.exit_code == 029    assert "site" in result.stdout30    assert "status" in result.stdout31def test_show_all():32    result = runner.invoke(app, ["show", "all"],)33    assert result.exit_code == 034    assert "mac" in result.stdout35    assert "serial" in result.stdout36def test_show_switch_by_name():37    result = runner.invoke(app, ["show", "switches", TEST_DEVICES["switch"]["name"], "--debug"],)38    assert result.exit_code == 039    assert "site" in result.stdout40    assert "status" in result.stdout41def test_show_switch_by_ip():42    result = runner.invoke(app, ["show", "switches", TEST_DEVICES["switch"]["ip"], "--debug"],)43    assert result.exit_code == 044    assert "site" in result.stdout45    assert "status" in result.stdout46def test_show_switch_by_mac():47    result = runner.invoke(app, ["show", "switches", TEST_DEVICES["switch"]["mac"], "--debug"],)48    assert result.exit_code == 049    assert "site" in result.stdout50    assert "status" in result.stdout51def test_show_switch_by_serial():52    result = runner.invoke(app, ["show", "switches", TEST_DEVICES["switch"]["serial"], "--debug"],)53    assert result.exit_code == 054    assert "site" in result.stdout55    assert "status" in result.stdout56def test_show_ap_by_name():57    result = runner.invoke(app, ["show", "aps", TEST_DEVICES["ap"]["name"], "--debug"],)58    assert result.exit_code == 059    # TODO show ap details not showing site???60    assert "model" in result.stdout61    assert "status" in result.stdout62def test_show_ap_by_ip():63    result = runner.invoke(app, ["show", "aps", TEST_DEVICES["ap"]["ip"], "--debug"],)64    assert result.exit_code == 065    assert "model" in result.stdout66    assert "status" in result.stdout67def test_show_ap_by_mac():68    result = runner.invoke(app, ["show", "aps", TEST_DEVICES["ap"]["mac"], "--debug"],)69    assert result.exit_code == 070    assert "model" in result.stdout71    assert "status" in result.stdout72def test_show_ap_by_serial():73    result = runner.invoke(app, ["show", "aps", TEST_DEVICES["ap"]["serial"], "--debug"],)74    assert result.exit_code == 075    assert "model" in result.stdout76    assert "status" in result.stdout77def test_show_gateway_by_name():78    result = runner.invoke(app, ["show", "gateways", TEST_DEVICES["gateway"]["name"], "--debug"],)79    assert result.exit_code == 080    assert "site" in result.stdout81    assert "status" in result.stdout82def test_show_gateway_by_ip():83    result = runner.invoke(app, ["show", "gateways", TEST_DEVICES["gateway"]["ip"], "--debug"],)84    assert result.exit_code == 085    assert "site" in result.stdout86    assert "status" in result.stdout87def test_show_gateway_by_mac():88    result = runner.invoke(app, ["show", "gateways", TEST_DEVICES["gateway"]["mac"], "--debug"],)89    assert result.exit_code == 090    assert "site" in result.stdout91    assert "status" in result.stdout92def test_show_gateway_by_serial():93    result = runner.invoke(app, ["show", "gateways", TEST_DEVICES["gateway"]["serial"], "--debug"],)94    assert result.exit_code == 095    assert "site" in result.stdout96    assert "status" in result.stdout97def test_show_device_by_name():98    result = runner.invoke(app, ["show", "devices", TEST_DEVICES["switch"]["name"], "--debug"],)99    assert result.exit_code == 0100    assert "site" in result.stdout101    assert "status" in result.stdout102def test_show_device_by_ip():103    result = runner.invoke(app, ["show", "devices", TEST_DEVICES["ap"]["ip"], "--debug"],)104    assert result.exit_code == 0105    assert "model" in result.stdout106    assert "status" in result.stdout107def test_show_device_by_mac():108    result = runner.invoke(app, ["show", "devices", TEST_DEVICES["gateway"]["mac"], "--debug"],)109    assert result.exit_code == 0110    assert "site" in result.stdout111    assert "status" in result.stdout112def test_show_device_by_serial():113    result = runner.invoke(app, ["show", "devices", TEST_DEVICES["switch"]["serial"], "--debug"],)114    assert result.exit_code == 0115    assert "site" in result.stdout116    assert "status" in result.stdout117def test_show_cache():118    result = runner.invoke(app, ["show", "cache"],)119    assert result.exit_code == 0120    assert "devices" in result.stdout121    assert "sites" in result.stdout122def test_show_variables():123    result = runner.invoke(app, ["show", "variables"],)124    assert result.exit_code == 0125    assert "_sys_serial" in result.stdout126    assert "_sys_lan_mac" in result.stdout127def test_show_variables_by_serial():128    result = runner.invoke(app, ["show", "variables", TEST_DEVICES["switch"]["serial"]],)129    assert result.exit_code == 0130    assert "_sys_serial" in result.stdout131    assert "_sys_lan_mac" in result.stdout132def test_show_variables_by_name():133    result = runner.invoke(app, ["show", "variables", TEST_DEVICES["switch"]["name"].title()],)134    assert result.exit_code == 0135    assert "_sys_serial" in result.stdout136    assert "_sys_lan_mac" in result.stdout137def test_show_templates_by_group():138    result = runner.invoke(app, ["show", "templates", "--group", TEST_DEVICES["switch"]["group"]],)139    assert result.exit_code == 0140    assert "group" in result.stdout141    assert "version" in result.stdout142def test_show_template_by_dev_name():143    result = runner.invoke(app, ["show", "templates", TEST_DEVICES["switch"]["name"].lower()],)144    assert result.exit_code == 0145    assert "BEGIN TEMPLATE" in result.stdout146    assert "%_sys_hostname%" in result.stdout147def test_show_template_by_dev_serial():148    result = runner.invoke(app, ["show", "templates", TEST_DEVICES["switch"]["serial"]],)149    assert result.exit_code == 0150    assert "BEGIN TEMPLATE" in result.stdout151    assert "%_sys_hostname%" in result.stdout152def test_show_template_by_name():153    result = runner.invoke(app, ["show", "templates", TEST_DEVICES["template"]["name"].lower(), "--group", TEST_DEVICES["template"]["group"].upper()])154    assert result.exit_code == 0155    assert "_sys_hostname%" in result.stdout156    assert "_sys_ip_address%" in result.stdout157def test_show_lldp_by_ap_name():158    result = runner.invoke(app, ["show", "lldp", TEST_DEVICES["ap"]["name"].lower()],)159    print(result.stdout)160    assert result.exit_code == 0161    assert "serial" in result.stdout162    assert "neighbor" in result.stdout163def test_show_groups():164    result = runner.invoke(app, ["show", "groups"],)165    assert result.exit_code == 0166    assert "name" in result.stdout167    assert "template group" in result.stdout168def test_show_certs():169    result = runner.invoke(app, ["show", "certs"],)170    assert result.exit_code == 0171    assert "expired" in result.stdout172    assert "checksum" in result.stdout173def test_show_logs_past():174    result = runner.invoke(app, ["show", "logs", "--past", "5d"],)175    print(result.stdout)176    assert result.exit_code == 0177    assert "Audit Logs" in result.stdout178    assert "id" in result.stdout179def test_show_switch_vlans_by_name():180    result = runner.invoke(app, ["show", "vlans", TEST_DEVICES["switch"]["name"]],)181    assert result.exit_code == 0182    assert "name" in result.stdout183    assert "pvid" in result.stdout184def test_show_events_past():185    result = runner.invoke(app, ["show", "events", "--past", "30m"],)186    assert result.exit_code == 0187    assert "Event Logs" in result.stdout188    assert "description" in result.stdout189def test_show_clients():190    result = runner.invoke(app, ["show", "clients"],)191    assert result.exit_code == 0192    assert "All Clients" in result.stdout193    assert "mac" in result.stdout194def test_show_group_level_config():195    result = runner.invoke(app, [196            "show",197            "config",198            TEST_DEVICES["gateway"]["group"],199            "--gw",200            "--out",201            f"{Path(__file__).parent.parent / 'config' / '.cache' / 'test_runner_gw_grp_config'}",202            "--debug"203        ]204    )205    assert result.exit_code == 0206    assert "!" in result.stdout...31199_conftest.py
Source:31199_conftest.py  
1#!/usr/bin/env python2"""py.test fixtures to be used in netmiko test suite."""3from os import path4import os5import pytest6from netmiko import ConnectHandler, FileTransfer, InLineTransfer, SSHDetect7from tests.test_utils import parse_yaml8PWD = path.dirname(path.realpath(__file__))9def pytest_addoption(parser):10    """Add test_device option to py.test invocations."""11    parser.addoption("--test_device", action="store", dest="test_device", type=str,12                     help="Specify the platform type to test on")13@pytest.fixture(scope='module')14def net_connect(request):15    """16    Create the SSH connection to the remote device17    Return the netmiko connection object18    """19    device_under_test = request.config.getoption('test_device')20    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")21    device = test_devices[device_under_test]22    device['verbose'] = False23    conn = ConnectHandler(**device)24    return conn25@pytest.fixture()26def net_connect_cm(request):27    """28    Create the SSH connection to the remote device using a context manager 29    retrieve the find_prompt() data and close the connection.30    """31    device_under_test = request.config.getoption('test_device')32    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")33    device = test_devices[device_under_test]34    device['verbose'] = False35    my_prompt = ""36    with ConnectHandler(**device) as conn:37        my_prompt = conn.find_prompt()38    return my_prompt39@pytest.fixture(scope='module')40def expected_responses(request):41    '''42    Parse the responses.yml file to get a responses dictionary43    '''44    device_under_test = request.config.getoption('test_device')45    responses = parse_yaml(PWD + "/etc/responses.yml")46    return responses[device_under_test]47@pytest.fixture(scope='module')48def commands(request):49    '''50    Parse the commands.yml file to get a commands dictionary51    '''52    device_under_test = request.config.getoption('test_device')53    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")54    device = test_devices[device_under_test]55    test_platform = device['device_type']56    commands_yml = parse_yaml(PWD + "/etc/commands.yml")57    return commands_yml[test_platform]58def delete_file_ios(ssh_conn, dest_file_system, dest_file):59    """Delete a remote file for a Cisco IOS device."""60    if not dest_file_system:61        raise ValueError("Invalid file system specified")62    if not dest_file:63        raise ValueError("Invalid dest file specified")64    # Check if the dest_file already exists65    full_file_name = "{0}/{1}".format(dest_file_system, dest_file)66    cmd = "delete {0}".format(full_file_name)67    output = ssh_conn.send_command_timing(cmd)68    if 'Delete' in output and dest_file in output:69        output += ssh_conn.send_command_timing("\n")70        if 'Delete' in output and full_file_name in output and 'confirm' in output:71            output += ssh_conn.send_command_timing("y")72            return output73        else:74            output += ssh_conn.send_command_timing("n")75    raise ValueError("An error happened deleting file on Cisco IOS")76@pytest.fixture(scope='module')77def scp_fixture(request):78    """79    Create an FileTransfer object.80    Return a tuple (ssh_conn, scp_handle)81    """82    device_under_test = request.config.getoption('test_device')83    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")84    device = test_devices[device_under_test]85    device['verbose'] = False86    ssh_conn = ConnectHandler(**device)87    dest_file_system = 'flash:'88    source_file = 'test9.txt'89    dest_file = 'test9.txt'90    local_file = 'testx.txt'91    direction = 'put'92    scp_transfer = FileTransfer(ssh_conn, source_file=source_file, dest_file=dest_file,93                                file_system=dest_file_system, direction=direction)94    scp_transfer.establish_scp_conn()95    # Make sure SCP is enabled96    scp_transfer.enable_scp()97    # Delete the test transfer files98    if scp_transfer.check_file_exists():99        delete_file_ios(ssh_conn, dest_file_system, dest_file)100    if os.path.exists(local_file):101        os.remove(local_file)102    return (ssh_conn, scp_transfer)103@pytest.fixture(scope='module')104def scp_fixture_get(request):105    """106    Create an FileTransfer object (direction=get)107    Return a tuple (ssh_conn, scp_handle)108    """109    device_under_test = request.config.getoption('test_device')110    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")111    device = test_devices[device_under_test]112    device['verbose'] = False113    ssh_conn = ConnectHandler(**device)114    dest_file_system = 'flash:'115    source_file = 'test9.txt'116    local_file = 'testx.txt'117    dest_file = local_file118    direction = 'get'119    scp_transfer = FileTransfer(ssh_conn, source_file=source_file, dest_file=dest_file,120                                file_system=dest_file_system, direction=direction)121    scp_transfer.establish_scp_conn()122    # Make sure SCP is enabled123    scp_transfer.enable_scp()124    # Delete the test transfer files125    if os.path.exists(local_file):126        os.remove(local_file)127    return (ssh_conn, scp_transfer)128@pytest.fixture(scope='module')129def tcl_fixture(request):130    """131    Create an InLineTransfer object.132    Return a tuple (ssh_conn, tcl_handle)133    """134    device_under_test = request.config.getoption('test_device')135    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")136    device = test_devices[device_under_test]137    device['verbose'] = False138    ssh_conn = ConnectHandler(**device)139    dest_file_system = 'flash:'140    source_file = 'test9.txt'141    dest_file = 'test9.txt'142    local_file = 'testx.txt'143    direction = 'put'144    tcl_transfer = InLineTransfer(ssh_conn, source_file=source_file, dest_file=dest_file,145                                  file_system=dest_file_system, direction=direction)146    # Delete the test transfer files147    if tcl_transfer.check_file_exists():148        delete_file_ios(ssh_conn, dest_file_system, dest_file)149    if os.path.exists(local_file):150        os.remove(local_file)151    return (ssh_conn, tcl_transfer)152@pytest.fixture(scope='module')153def ssh_autodetect(request):154    """Create an SSH autodetect object. 155    return (ssh_conn, real_device_type)156    """157    device_under_test = request.config.getoption('test_device')158    test_devices = parse_yaml(PWD + "/etc/test_devices.yml")159    device = test_devices[device_under_test]160    device['verbose'] = False161    my_device_type = device.pop('device_type')162    device['device_type'] = 'autodetect'163    conn = SSHDetect(**device)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
