### Installing pyATS Examples and Templates Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/changelog/2015/june.md Shows how to install pyATS examples and templates as PyPI packages using pip. ```bash bash$ pip install ats.examples bash$ pip install ats.templates ``` -------------------------------- ### Start Setup Handler Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Initiates a setup handler. Ensure the current context is testsuite before calling. ```python >>> # Make sure current context is testsuite >>> aerunner.start_setuphandler('firstsetuphandler') ``` -------------------------------- ### Linux FileUtils Example Setup Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/utilities/file_transfer_utilities.md This snippet shows the structure of a testbed YAML file and the initial Python setup for using FileUtils. It demonstrates how to load a testbed configuration and prepare for file operations. ```yaml testbed: servers: server_alias: server: myserver.domain.com address: 1.1.1.1 credentials: default: username: my_username password: my_password ``` ```python from pyats.utils.fileutils import FileUtils from pyats.topology import loader tb = loader.load('tb.yaml') # This with statement ensures that any sessions are automatically closed ``` -------------------------------- ### Start Setup Handler Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Starts a setuphandler section within a testsuite. Ensure the current context is set to 'testsuite' before calling. ```python >>> # Make sure current context is testsuite >>> aerunner.start_setuphandler('asetuphandler') ``` -------------------------------- ### AEtest Common Setup Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aetest/structure.md Defines a common setup section for an AEtest script by inheriting from aetest.CommonSetup. Includes example subsections for checking arguments, connecting to devices, and configuring interfaces. ```python # Example # ------- # # an example common setup # import the aetest module from pyats import aetest # define a common setup section by inherting from aetest class ScriptCommonSetup(aetest.CommonSetup): @aetest.subsection def check_script_arguments(self): pass @aetest.subsection def connect_to_devices(self): pass @aetest.subsection def configure_interfaces(self): pass ``` -------------------------------- ### Complete PyATS AERunner Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aereport/index.md A comprehensive example demonstrating the setup and execution of a test suite using AEClient and AERunner, including starting the server, connecting the client, and setting various test parameters. ```python import time import subprocess from pyats.aereport.aerunner import AERunner from pyats.aereport.client import AEClient svrpid, svrport, servername = AERunner.start_server(logsdir='/tmp/ttt/', logfilename='logfile.log') clt = AEClient(port=svrport,servername=servername) clt.connect() clt.start_testsuite(**{'jobname':'job1', 'submitter':'anUser'}) clt.add_ats_packages(packages=[('Csccon', '1.1'), ('aetest', '1.2')]) args = {'dnsname':'aDnsName', 'post':{'status':'aStatus', 'cmd':'aCmd'}, 'bgPost':False, 'attributes':[{'name':'aName', 'value':'aSuperValue'}, {'name':'secondName', 'value':'superValue2'}]} clt.set_tims(**args) clt.start_clean() time.sleep(0.4) clt.set_initinfo(script='aScript', pargs='pargs') clt.set_runinfo(comment='aComment') clt.stop_clean() clt.set_initinfo(host='aHost', params={'cli':'aCli', 'errors':'10', 'reason':'aReason', 'type':'aReportType', 'sem':{'alignment':True, 'traceback':False}, ) ``` -------------------------------- ### Example Usage Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aereport/index.md Demonstrates how to use AERunner and AEClient for starting a server, connecting, and executing various API calls. ```APIDOC ## Example Usage ### Description Example demonstrating the usage of AERunner and AEClient for starting a server, connecting, and invoking various API calls. ### Code Example ```python import time import subprocess from pyats.aereport.aerunner import AERunner from pyats.aereport.client import AEClient # Start the server svrpid, svrport, servername = AERunner.start_server(logsdir='/tmp/ttt/', logfilename='logfile.log') # Initialize and connect the client clt = AEClient(port=svrport, servername=servername) clt.connect() # Start a test suite clt.start_testsuite(**{'jobname':'job1', 'submitter':'anUser'}) # Add ATS packages clt.add_ats_packages(packages=[('Csccon', '1.1'), ('aetest', '1.2')]) # Set TIMS information args = {'dnsname':'aDnsName', 'post':{'status':'aStatus', 'cmd':'aCmd'}, 'bgPost':False, 'attributes':[{'name':'aName', 'value':'aSuperValue'}, {'name':'secondName', 'value':'superValue2'}]} clt.set_tims(**args) # Start and stop clean process clt.start_clean() time.sleep(0.4) clt.stop_clean() # Set initialization and run information clt.set_initinfo(script='aScript', pargs='pargs') clt.set_runinfo(comment='aComment') clt.set_initinfo(host='aHost', params={'cli':'aCli', 'errors':'10', 'reason':'aReason', 'type':'aReportType', 'sem':{'alignment':True, 'traceback':False}}) # Generate XML reports and terminate the server (example calls) # clt.generate_xml_reports(path='/tmp/') # AERunner.terminate_server() ``` ``` -------------------------------- ### start_setuphandler Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Starts a setup handler section. This method is used to initiate a setup phase within the test execution flow. It is expected that the current context is a testsuite when this method is called. ```APIDOC ## start_setuphandler(kwargs) ### Description Starts a setup handler section. This method is used to initiate a setup phase within the test execution flow. It is expected that the current context is a testsuite when this method is called. ### Parameters * **name** (*str*) – Name of the handler section * **clienthost** (*str*) – Name of the host machine the client is running on * **pid** (*str*) – Process ID of the client * **logfilepath** (*str*) – Optional - path to the log file. ### Example ```pycon >>> # Make sure current context is testsuite >>> aerunner.start_setuphandler('firstsetuphandler') ``` ### Returns If mode is strict and an issue is seen, an Exception will be raised. Else None in all other cases ### Return type: Exception or None ``` -------------------------------- ### AEClient Example: Start Server, Connect, Make RPCs, Generate Reports Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md This example demonstrates the full lifecycle of using AEClient. It includes starting the AEReport server, creating an AEClient instance, connecting to the server, making several RPC calls (start_testsuite, add_ats_packages, stop_testsuite, generate_xml_reports), and finally terminating the server. Ensure the server process is started before running this client code. ```python >>> # Start the server process (if not already done) >>> svrpid, svrport, servername = AERunner.start_server(logsdir='/tmp/ttt/', >>> logfilename='logfile.log') >>> # Create an AEClient instance >>> clt = AEClient(port=svrport,servername=servername) >>> # Connect to the server >>> clt.connect() >>> # Make RPCs >>> clt.start_testsuite(**{'name':'job1', >>> 'submitter':'anUser'}) >>> clt.add_ats_packages(packages=[('Csccon', '1.1'), ('aetest', '1.2')]) >>> clt.stop_testsuite() >>> # Generate your xml reports >>> clt.generate_xml_reports(path='/tmp/') >>> # Terminate the server >>> AERunner.terminate_server() ``` -------------------------------- ### Start Common Setup Context Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Initiates a common setup context within a testscript. This function adds a section to the common setup list and pushes it to the context stack. ```pycon >>> # Make sure current context is testscript >>> aerunner.start_commonsetup(logfilepath='/tmp/logfile.log', >>> xref={'file':'/init/info/file', >>> 'line':'30'}) ``` -------------------------------- ### PyATS AERunner Setup and Execution Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aereport/index.md This snippet demonstrates the basic setup and execution flow of an AERunner job, including setting ATS paths, versions, packages, starting job execution, and test scripts. ```python clt.set_ats(path= '/aPath/', versions= '5.3.0', packages=[('aPackage','1.0')]) clt.start_jobexecution() clt.start_testscript(logfilepath='/tmp/logfile.log') clt.start_commonsetup(logfilepath='/tmp/logfile.log') clt.stop_commonsetup() ``` -------------------------------- ### Testcase Setup Failure with Goto Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aetest/control.md Demonstrates how to use 'goto' to skip to the cleanup section of the current testcase when a setup fails. ```python class TestcaseOne(aetest.Testcase): @aetest.setup def setup(self): # setup failed, go to cleanup of testcase self.failed('test failed', goto = ['cleanup']) ``` -------------------------------- ### Running PyATS Job with Testbed File Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/topology/creation.md Examples of starting pyats run job and passing in a testbed file or URL using the --testbed-file argument. ```bash pyats run job jobfile.py --testbed-file /path/to/my/testbed/file/testbed.yaml pyats run job jobfile.py --testbed-file "https:///testbed.yaml" ``` -------------------------------- ### Copying Latest Examples and Templates Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/changelog/2015/june.md Instructions to copy the latest examples and templates to a pyATS instance, backing up existing ones. ```bash bash$ cd $VIRTUAL_ENV bash$ mv examples examples_bak bash$ mv templates templates_bak bash$ cp -r /auto/pyats/examples . bash$ cp -r /auto/pyats/templates . ``` -------------------------------- ### Clean File Loading Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/kleenex/inputs.md An example demonstrating how clean file content is loaded. ```yaml # Example # ------- # # demonstrating how clean file content is loaded ``` -------------------------------- ### Install pyATS with All Optional Extras Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/getting_started/index.md Installs pyATS along with all available optional extras. ```bash pip install pyats[full] ``` -------------------------------- ### Example Service Wrapper for IOSXE Execute Service Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/connections/wrapper.md This example demonstrates a Service Wrapper configured for the execute service on an IOSXE device. ```python # This is a catch-all for all Connection types pyats.connections.BaseConnection
# This is the standard unicon connection unicon.Connection
# Used for rest connections rest.connector.Rest
# Used for yang connections yang.connector.Gnmi yang.connector.Netconf ``` -------------------------------- ### Install pyATS with Optional Packages Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/changelog/2019/july.md Install pyATS with specific optional features like libraries, templating, robot framework integration, or a full installation. ```bash pip install pyats[library] pip install pyats[template] pip install pyats[robot] pip install pyats[full] ``` -------------------------------- ### Install Documentation Build Dependencies Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/README.md Use this command to install all necessary build dependencies for the pyATS documentation. ```bash make install_build_deps ``` -------------------------------- ### Install pyATS Core Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/getting_started/index.md Installs only the core pyATS framework. Use this if you do not need optional extras. ```bash pip install pyats ``` -------------------------------- ### YAML Markup Examples Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/utilities/yaml_markup.md Illustrates various pyATS YAML markup examples for referencing device attributes, interfaces, environment variables, callables, included files, user input, encoded strings, and CLI arguments. These examples demonstrate how to dynamically populate YAML configurations. ```text # reference to current device name %{self} ``` ```text # reference to attributes within current device %{self.x.y.z} ``` ```text # reference to logical interface within current device # (replaced with actual interface name) %INTF{logical_interface_name} ``` ```text # reference to arbitrary attribute within this YAML file %{a.b.c} ``` ```text # reference to the list of keys of this attribute within this YAML file %{d.e.keys()} ``` ```text # reference to environment variable from the os # (replaced with actual environment variable name) %ENV{environment_variable_name} ``` ```text # reference to callable without parameter # (replaced with actual path to callable) %CALLABLE{path.to.callable} ``` ```text # reference to callable with parameters param1, param2 and param3 # (replaced with actual path to callable) %CALLABLE{path.to.callable(param1,param2,param3)} ``` ```text # reference to callable with paramter param1 and # kwarg style parameter param2 %CALLABLE{path.to.callable(param1, param2='val1')} ``` ```text # reference to content from other YAML file # (replaced with actual path to YAML file) %INCLUDE{yaml_file_path} ``` ```text # prompt user to enter string content manually %ASK{optional prompt text} ``` ```text # Reference to text encoded with "pyats secret encode" command # Encoded credential passwords are substituted by secret strings. # Other encoded references are substituted with their decoded string. # See secret strings documentation for details. %ENC{} ``` ```text # Reference to text encoded with "pyats secret encode --prefix x" command. # Encoded credential passwords are substituted by secret strings. # Other encoded references are substituted with their decoded string. # See secret strings documentation for details. %ENC{, prefix=x} ``` ```text # Reference to "some_arg" will be replaced by "some_value" if # the command line "pyats run job --some_arg some_value" is used. %CLI{some_arg} ``` ```text # If the command line argument is provided without a value, # the value is set to boolean 'True'. The following command line # sets the value for "some_flag" to True. # "pyats run job --some_flag" %CLI{some_flag} ``` ```text # If the command line argument has multiple values, # the variable is replaced with a list of values. # The following command line argument creates a list # of values in place of the devices variable. # "pyats run job --devices R1 R2" %CLI{devices} ``` -------------------------------- ### Device instantiation and configuration example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/topology/index.md Illustrates creating a Device object with a name, alias, interfaces, and associating it with a testbed. ```python >>> device = Device('myDevice') >>> from pyats.topology import Testbed, Interface >>> testbed = Testbed('myTestbed') >>> interface = Interface('Ethernet1/1', 'ethernet') >>> device = Device('myNewDevice', ... alias = 'myAlias', ... interfaces = [interface,], ... testbed = testbed) ``` -------------------------------- ### Install pyATS Source: https://github.com/ciscotestautomation/pyats/blob/main/README.md Use this command to install the pyATS framework with all its features. It is available through the Python Package Index. ```bash $ pip install pyats[full] ``` -------------------------------- ### Example Script Arguments and Profile Configuration Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/manifest/introduction.md Defines example script arguments and a profile configuration within a manifest file. ```yaml arguments: mail-html: True configuration: easypy_config.yaml profile: local: arguments: testbed-file: testbed.yaml ``` -------------------------------- ### Install pyATS Full Package Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/README.md Ensure you have the full pyATS package installed before proceeding with documentation contributions. ```bash pip install pyats[full] ``` -------------------------------- ### Create Testbed Objects Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/topology/concept.md Demonstrates how to create Testbed objects, both empty and with initial configurations, and how to add or remove devices. ```python # Example # ------- # # creating testbed objects from pyats.topology import Testbed, Device # create some device objects for demonstration's sake device_a = Device('A') device_b = Device('B') device_c = Device('C') device_d = Device('D') # creating an empty testbed testbed_a = Testbed(name = 'emptyTestbed') # creating a testbed with an alias testbed_b = Testbed(name = 'myTestbed', alias = 'yetAnotherTestbed') # creating a testbed with devices testbed_c = Testbed(name = 'testbedWithDevicesFromStart', devices = [device_a, device_b]) # adding devices into testbeds testbed_d = Testbed(name = 'testbedToReceiveDevices') testbed_d.add_device(device_c) # removing devices from a testbed testbed_e = Testbed(name = 'testbedToRemoveDevices', devices = [device_d]) testbed_e.remove_device(device_d) # squeezing a testbed to keep only wanted devices testbed_e = Testbed(name = 'testbedToSqueeze', devices = [device_a, device_b, device_c]) testbed_e.squeeze(device_b.name, device_c.name) # connect to all devices in this testbed in parallel testbed_e.connect() # connect to specific devices in this testbed in parallel ``` -------------------------------- ### Example of @setup decorator Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aetest/index.md Illustrates the usage of the @setup decorator to designate a method as the setup section for a Testcase. This section handles necessary configurations and checks before test execution. ```python >>> class Testcase(aetest.Testcase): ... @aetest.setup ... def simple_setup(self): ... pass ``` -------------------------------- ### Initialize and Configure Testbed Topology Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/topology/index.md Sets up a basic testbed with devices and links, demonstrating initial topology configuration. ```python >>> from pyats.topology import Device,Link,Interface,Testbed >>> t = Testbed('tb') >>> t.add_device(Device('d1')) >>> t.add_device(Device('d2')) >>> t.add_device(Device('d3')) >>> d1 = t.devices.d1 >>> d2 = t.devices.d2 >>> d3 = t.devices.d3 >>> l12 = Link('l12') >>> l13 = Link('l13') >>> l23 = Link('l23') >>> d1.add_interface(Interface("d1.i1", link=l12, type="ethernet")) >>> d1.add_interface(Interface("d1.i2", link=l13, type="ethernet")) >>> d2.add_interface(Interface("d2.i1", link=l12, type="ethernet")) >>> d2.add_interface(Interface("d2.i2", link=l23, type="ethernet")) >>> d3.add_interface(Interface("d3.i1", link=l13, type="ethernet")) >>> d3.add_interface(Interface("d3.i2", link=l23, type="ethernet")) >>> [dev for dev in t.devices] ['d3', 'd2', 'd1'] >>> [link.name for link in t.links] ['l23', 'l12', 'l13'] ``` -------------------------------- ### Simplistic Single Connection Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/connections/integration.md Shows how to establish a single connection instance to a testbed device using the Device.connect() method. All associated services are then available as methods of the device object. Requires importing the topology module and loading a testbed configuration. ```python # Example # ------- # # simplistic connection example # using the topology module from pyats import topology # let's write an inline testbed file for simplicity # (edit this to whatever your testbed looks like) testbed = topology.loader.load(''' testbed: name: my-inline-testbed devices: tplana-hath: type: iosxe os: iosxe connections: a: protocol: telnet ip: 10.1.1.1 port: 10000 ''') # pick the device to work with device = testbed.devices['tplana-hath'] # we should be able to directly connect to it device.connect() assert device.connected # run the various services associated with this connection device.execute('show version') device.configure('clock set 18:00:00 April 4 2063') # disconnect from it device.disconnect() ``` -------------------------------- ### Start AEReport Server Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Starts the AEReport XML RPC server. It verifies the logs directory, gets a free port, and starts the server process. This method polls for a 'ready' signal from the server. ```python >>> AERunner(logsdir='/bla/bla', logfilename='test').start_server() ``` -------------------------------- ### Get Distribution Location Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/utils/index.md Retrieves the installation location of a distribution. ```python dist_info = DistInfo(dist) location = dist_info.location ``` -------------------------------- ### Interactive PyATS Shell Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/cli/pyats_shell.md This example shows how to launch the pyats shell with a testbed file and interact with the loaded topology, including connecting to devices and executing commands. ```text $ pyats shell --testbed-file tb.yaml Welcome to pyATS Interactive Shell ================================== Python 3.7.0 (default, Sep 6 2018, 16:54:40) [Clang 10.0.0 (clang-1000.10.25.5)] >>> from pyats.topology import loader >>> testbed = loader.load('tb.yaml') ------------------------------------------------------------------------------- >>> testbed.devices TopologyDict({'nx-osv-1': , 'csr1000v-1': }) >>> testbed.devices['nx-osv-1'].connect() [2019-02-11 12:27:54,780] +++ nx-osv-1 logfile /tmp/nx-osv-1-default-20190211T122754780.log +++ [2019-02-11 12:27:54,781] +++ Unicon plugin nxos +++ [2019-02-11 12:27:54,784] +++ connection to spawn: telnet 172.25.192.90 17003, id: 4620986912 +++ [2019-02-11 12:27:54,785] connection to nx-osv-1 [2019-02-11 12:27:54,787] telnet 172.25.192.90 17003 Trying 172.25.192.90... Connected to asg-virl-ubuntu.cisco.com. Escape character is "^]\'. nx-osv-1# [2019-02-11 12:27:55,655] +++ initializing handle +++ [2019-02-11 12:27:55,656] +++ nx-osv-1: executing command 'term length 0' +++ term length 0 nx-osv-1# [2019-02-11 12:27:55,824] +++ nx-osv-1: executing command 'term width 511' +++ term width 511 nx-osv-1# [2019-02-11 12:27:55,991] +++ nx-osv-1: executing command 'terminal session-timeout 0' +++ terminal session-timeout 0 nx-osv-1# [2019-02-11 12:27:56,161] +++ nx-osv-1: config +++ config term Enter configuration commands, one per line. End with CNTL/Z. nx-osv-1(config)# no logging console nx-osv-1(config)# line console nx-osv-1(config-console)# exec-timeout 0 nx-osv-1(config-console)# terminal width 511 nx-osv-1(config-console)# end nx-osv-1# "Escape character is ".^]\'.\r\n\r\r\n\rnx-osv-1# " >>> now exiting InteractiveConsole... ``` -------------------------------- ### Remove pyATS examples and templates folders Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/changelog/2015/june.md Before upgrading, remove the 'templates' and 'examples' folders from your pyATS instance. This ensures new templates and examples are installed via pip. Back up any local modifications before deletion. ```bash bash$ cd $VIRTUAL_ENV # note - this will delete it. If you modified examples/templates, # make sure to make local backups bash$ rm -rf templates examples ``` -------------------------------- ### RobotFramework Example using pyATS Keywords Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/robot/native.md Demonstrates importing the pyATS Robot Framework library and using keywords to set up a testbed, connect to a device, and run pyATS test cases. ```robotframework # Example # ------- # # Demonstration of pyATS Robot Framework Keywords *** Settings *** # Importing test libraries, resource files and variable files. Library ats.robot.pyATSRobot *** Variables *** # Defining variables that can be used elsewhere in the test data. # Can also be driven as dash argument at runtime ${datafile} datafile.yaml ${testbed} testbed.yaml *** Test Cases *** # Creating test cases from available keywords. Initialize # select the testbed to use use testbed "${testbed}" # connec to testbed device through cli connect to device "ios" as alias "cli" CommonSetup # calling pyats common_setup run testcase "basic_example_script.common_setup" Testcase pass # calling pyats testcase run testcase "basic_example_script.tc_one" ``` -------------------------------- ### Get Pip Packages Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/utils/index.md Retrieves a list of installed pip packages. ```python ### pyats.utils.utils.get_pip_pkgs() Get pip packages ``` -------------------------------- ### PyATS Job File Example for Rerunning Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/easypy/rerun.md Example of a pyATS job file demonstrating how to execute a testscript using the run() function. This setup is used in conjunction with rerun functionalities. ```python import os from pyats.easypy import run # All run() must be inside a main function def main(runtime): # Find the location of the script in relation to the job file test_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) testscript = os.path.join(test_path, 'basic_example_script.py') # Execute the testscript run(testscript=testscript, runtime = runtime) run(testscript=testscript, runtime = runtime) ``` -------------------------------- ### Load Testbed and Connect to Devices Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/getting_started/index.md Demonstrates loading a testbed YAML file and interacting with devices, including establishing connections and executing commands. ```python # loader our newly minted testbed file from pyats.topology import loader testbed = loader.load('ios_testbed.yaml') # access the devices testbed.devices # AttrDict({'ios-1': , # 'ios-2': }) ios_1 = testbed.devices['ios-1'] ios_2 = testbed.devices['ios-2'] # find links from one device to another for link in ios_1.find_links(ios_2): print(repr(link)) # # establish basic connectivity ios_1.connect() # issue commands print(ios_1.execute('show version')) ios_1.configure(''' interface GigabitEthernet0/0 ip address 10.10.10.1 255.255.255.0 ''') # establish multiple, simultaneous connections ios_2.connect(alias = 'console', via = 'a') ios_2.connect(alias = 'vty_1', via = 'vty') ``` -------------------------------- ### Instantiate and Load Configurations Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/datastructures/configuration.md Demonstrates how to instantiate the Configuration class and load configurations from INI, YAML, and Python entrypoint files. Use this to set up your application's configuration. ```Python from pyats.datastructures import Configuration # instantiating it cfg = Configuration() # loading some INI style config files cfg.load_cfgs('/path/to/file.ini') cfg.load_cfgs('/path/to/file.conf') # load yaml style config files cfg.load_yamls('/path/to/config.yaml') # loading python entrypoints cfg.load_entrypoint(group = 'entrypoint.group.name') cfg ``` -------------------------------- ### start_setuphandler Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Starts a setuphandler section within a testsuite. It allows specifying client host, process ID, handler name, and an optional log file path. ```APIDOC ## start_setuphandler(kwargs) ### Description Starts a setuphandler section in testsuite. ### Parameters * **clienthost** (*str*) – Name of the host machine the client is running on * **pid** (*str*) – Process ID of the client * **name** (*str*) – Name of the handler section * **logfilepath** (*str*) – Optional - path to the log file. ### Returns If mode is strict and an issue is seen, an Exception will be raised. Else None in all other cases ### Return type Exception or None ``` -------------------------------- ### SACommonSetupReporter.start() Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aetest/index.md Starts the SACommonSetupReporter. ```APIDOC ## SACommonSetupReporter.start() ### Description Starts the SACommonSetupReporter. ### Method `start()` ### Endpoint N/A (Method call) ### Parameters None ### Request Example ```python sa_common_setup_reporter.start() ``` ### Response None ``` -------------------------------- ### Example Testbed YAML File Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/getting_started/index.md A sample YAML file describing network devices, their operating systems, connections, and interface configurations. ```yaml testbed: name: IOS_Testbed credentials: default: username: admin password: cisco enable: password: cisco devices: ios-1: # <----- must match to your device hostname in the prompt os: ios type: ios connections: a: protocol: telnet ip: 1.1.1.1 port: 11023 ios-2: os: ios type: ios connections: a: protocol: telnet ip: 1.1.1.2 port: 11024 vty: protocol: ssh ip: 5.5.5.5 topology: ios-1: interfaces: GigabitEthernet0/0: ipv4: 10.10.10.1/24 ipv6: '10:10:10::1/64' link: link-1 type: ethernet Loopback0: ipv4: 192.168.0.1/32 ipv6: '192::1/128' link: ios1_Loopback0 type: loopback ios-2: interfaces: GigabitEthernet0/0: ipv4: 10.10.10.2/24 ipv6: '10:10:10::2/64' link: link-1 type: ethernet Loopback0: ipv4: 192.168.0.2/32 ipv6: '192::2/128' link: ios2_Loopback0 type: loopback ``` -------------------------------- ### Interactive Debugger Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aetest/debugging.md This example shows the output of an interactive debugging session when an exception occurs during test execution. The session starts with a '(pdb)' prompt, indicating that the debugger is active and waiting for user input. ```python # The result of subsection subsection is => PASSED # The result of common setup is => PASSED # +------------------------------------------------------------------------------+ # | Starting testcase TestcaseOne | # +------------------------------------------------------------------------------+ # +------------------------------------------------------------------------------+ # | Starting section setup | # +------------------------------------------------------------------------------+ # The result of section setup is => PASSED # +------------------------------------------------------------------------------+ # | Starting section test | # +------------------------------------------------------------------------------+ # Caught exception during execution: # Traceback (most recent call last): # File "a.py", line 16, in test # blablabla() # NameError: name 'blablabla' is not defined # > example_pdb_on_failure.py(16)test() # > blablabla() # (Pdb) ``` -------------------------------- ### Register Service Wrapper via Entry Point Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/connections/wrapper.md Demonstrates how to make a service wrapper discoverable by defining it as an entry point in the `setup.py` file under the `pyats.connections.wrapper` descriptor. ```python setup( ..., # console entry point entry_points = { 'pyats.connections.wrapper': [ 'example_wrapper = path.to.path:ExampleWrapper' ] } ) ``` -------------------------------- ### PyATS ConnectionManager: Single Connection Examples Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/connections/manager.md Demonstrates establishing single device connections using `ConnectionManager.connect()` and `ConnectionManager.instantiate()`. Shows how to use default and custom connection classes, aliases, and via paths. Also illustrates propagating arguments to the connection's `__init__()` method. ```python # Example # ------- # # ConnectionManager.connect() and .instantiate() method # (simple/single connection class instance) # given a device connection manager object device.connectionmgr # # we could establish connections using the default class # ------------------------------------------------------ # just connect device.connect() # equivalent to: device.connectionmgr.connect() # connect using a different path and alias # (this requires device.connections['mgmt'] to be populated) device.connect(alias = 'vty_1', via = 'mgmt') # equivalent to: device.connectionmgr.connect(alias = 'vty_1', via = 'mgmt') # we could establish connections using another class # -------------------------------------------------- from some_connection_lib import AltConnImpl # just connect using it device.connect(cls = AltConnImpl) # equivalent to: device.connectionmgr.connect(cls = AltConnImpl) # connect using a different path and alias and that class device.connect(cls = AltConnImpl, alias = 'vty_1', via = 'mgmt') # equivalent to: device.connectionmgr.connect(cls = AltConnImpl, # alias = 'vty_1', # via = 'mgmt') # additionally, we could instantiate the object first # --------------------------------------------------- connection = device.instantiate(cls = AltConnImpl) # and modify various attributes before we connect connection.new_attribute = 'x' connection.connect() # note that after device.instantiate() is called, the newly created # connection object is saved both under the given alias in the connection # manager, and returned for your direct access. # -------------------------------------------------------------------------- # all other arguments to connect() api are propagated to the connection class # (assuming AltConnImpl took arguments timeout, term_width and max_buffer) device.connect(cls = AltConnImpl, alias = 'session_1', timeout = 100, term_width = 512, max_buffer = 999999) # eg, equivalent to: # device.connectionmgr.connections['session_1'] = AltConnImpl(timeout = 100, # term_width = 512, # max_buffer = 999999) # device.connectionmgr.connections['session_1'].connect() ``` -------------------------------- ### TopologyDict get method example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/topology/index.md Demonstrates accessing values in a TopologyDict using keys or aliases, with an optional default value. ```python >>> td = TopologyDict() >>> td['a'] = TopologyObject('a', alias = 'b') >>> td.get('a') is td['a'] True >>> td.get('b') is td['a'] True >>> td.get('c') is None True >>> td.get('c', 'default') 'default' ``` -------------------------------- ### Creating and Configuring Device Objects Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/topology/concept.md Demonstrates the creation of Device objects, setting attributes like alias and OS, and defining connection parameters. It also shows how to add interfaces to devices and associate devices with a testbed. ```python from pyats.topology import Testbed, Device, Interface # create some interfaces for adding to devices intf_a = Interface('Eth1/1', 'ethernet') intf_b = Interface('Eth2/1', 'ethernet') # creating a testbed for demonstration's sake testbed = Testbed('exampleTestbed') # creating an empty device device_a = Device('emptyDevice') # giving device a different alias device_a.alias = 'newAlias' # set device os device_a.os = 'iosxe' # creating a device with connection parameters device_b = Device('deviceThatCanBeConnected', os='iosxe', connections={ 'mgmt': { 'protocol': 'telnet', 'ip': '1.1.1.1' }, }) # adding interface to device objects device_b.add_interface(intf_a) # creating device with interfaces device_c = Device('deviceCreatedWithIntfs', os='iosxe', interfaces = [intf_b]) # associating a device to a testbed can be done either by performing # a testbed.add_device() call, or directly by setting a device's testbed # attribute, which automatically performs the parent add_device() call device_c.testbed = testbed # checking if an intf object belongs to a device can be done # using the in operator assert intf_b in device_c # loop through interfaces on a device for intf in device_c: print(intf.name) ``` -------------------------------- ### RunInfoFileHandler Operations Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/log/index.md Specific file handler for run info files, with methods to get tail start and handle tailing files. ```APIDOC ## RunInfoFileHandler ### Description Specific file handler for run info files. ### Methods - `get_tail_start(file_path)`: Gets the starting point for tailing a file. - `tailing_file(file_path)`: Handles tailing a file. ``` -------------------------------- ### NestedAttrDict Usage Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/datastructures/attrdict.md Demonstrates various object access, get with default, delete, and set operations using dot notation with NestedAttrDict. ```python my_dict = { 'a': 1, 'b': 2, 'c': { 'x': 10, 'y': 20, 'z': { 'value': 100, }, }, } obj = NestedAttrDict(my_dict) # get api obj.get('c.y') # 20 obj.get('a') # 1 # get with default obj.get('c.z.non_existent_value', 1000) # 1000 # delete del obj['c.x'] # NestedAttrDict({'a': 1, # 'b': 2, # 'c': NestedAttrDict({'y': 20, # 'z': NestedAttrDict({'value': 100})})}) # set obj['c.z.value_two'] = 200 # NestedAttrDict({'a': 1, # 'b': 2, # 'c': NestedAttrDict({'y': 20, # 'z': NestedAttrDict({'value': 100, # 'value_two': 200})})}) ``` -------------------------------- ### start_commonsetup Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Ensures the current context is a testscript and adds a common setup section, pushing it onto the context stack. ```APIDOC ## start_commonsetup(kwargs) ### Description Make sure the current context is a testscript (TestScript). If yes, add a section to the list commonsetup And push this section to the context stack. ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **clienthost** (str) – Name of the host machine the client is running on - **pid** (str) – Process ID of the client - **logfilepath** (str) – Mandatory - Path to the log file for the testcase - **name** (str) – Name of the section ### Request Example ```pycon >>> # Make sure current context is testscript >>> aerunner.start_commonsetup(logfilepath='/tmp/logfile.log', >>> xref={'file':'/init/info/file', >>> 'line':'30'}) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Return Type Exception or None ``` -------------------------------- ### Combined Processor API Usage Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aetest/processors.md Illustrates the combined usage of affix and get for pre and exception processors, and affix for post processors on test functions. ```python from pyats import aetest def print_parameters(section): print(section.parameters) def print_exception_message(section, exc_type, exc_value, exc_traceback): print('exception : ', exc_type, exc_value) return True class CommonSetup(aetest.CommonSetup): @aetest.subsection def subsection(self): # affix pre-processors and exception-processors to testcase aetest.processors.affix(Testcase, pre = [print_parameters], exception = [print_exception_message]) class Testcase(aetest.Testcase): @aetest.setup def setup(self): # check if testcase has processors for type_ in ('pre', 'post', 'exception'): if aetest.processors.get(self, type_): print('Testcase has %s-processors' % type_) # affix post-processors to test function aetest.processors.affix(self.test, post = [print_parameters]) # affix exception-processors to testException function aetest.processors.affix(self.testException, exception = [print_exception_message]) @aetest.test def test(self): pass @aetest.test def testException(self): pyATS() # the above example probably didn't make much sense. # the goal is to show you what can be done. ``` -------------------------------- ### Self Instance Consistency in PyATS Testcase Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aetest/behavior.md This example illustrates how `self` maintains its instance state across setup and test methods within a `Testcase` class. It shows how an attribute set in `setup` is accessible and modifiable in subsequent `test` methods, ensuring consistent behavior throughout the testcase execution. ```python # Example # ------- # # self, consistency explained from pyats import aetest # define a testcase where its tests # expects self.value to be set by the setup section, # and continues to be carried throughout class Testcase(aetest.Testcase): @aetest.setup def setup(self): self.value = 1 @aetest.test def test_one(self): self.value += 1 assert self.value == 2 @aetest.test def test_one(self): self.value += 1 assert self.value == 3 # run the Testcase tc = Testcase() print(tc()) # passed ``` -------------------------------- ### Get Test Results Dictionary Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aereport/index.md Retrieves a dictionary containing the results of all test cases and subtests within each test script. The structure of the returned dictionary is shown in the example. ```default {Task-id1 : {'sample_abstract_testcase' : 'passed', 'sample_testcase_with_subtests.subtest_one' : 'passed', sample_testcase_with_subtests.subtest_two : 'failed', ........}, Task-id2 : { .......}, } ``` -------------------------------- ### Manually Creating a Simple Testbed Topology Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/topology/creation.md Example of creating a testbed topology from scratch by manually instantiating Testbed, Device, Interface, and Link objects. ```python # import testbed objects from pyats.topology import Testbed, Device, Interface, Link # create your testbed testbed = Testbed('manuallyCreatedTestbed', alias = 'iWishThisWasYaml', passwords = { 'tacacs': 'lab', 'enable': 'lab', }, servers = { 'tftp': { 'name': 'my-tftp-server', 'address': '10.1.1.1', }, }) # create your devices device = Device('tediousProcess', alias = 'gimmyYaml', connections = { 'a': { 'protocol': 'telnet', 'ip': '192.168.1.1', 'port': 80 } }) # create your interfaces interface_a = Interface('Ethernet1/1', type = 'ethernet', ipv4 = '1.1.1.1') interface_b = Interface('Ethernet1/2', type = 'ethernet', ipv4 = '1.1.1.2') # create your links link = Link('ethernet-1') # now let's hook up everything together ``` -------------------------------- ### Define a Testcase with Setup and Cleanup Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/aetest/structure.md Shows how to create a more complex test case with a setup method to initialize state and a cleanup method to revert changes. A custom UID is assigned to this test case. ```python from pyats import aetest class SlightlyMoreComplexTestcase(aetest.Testcase): uid = 'id_of_this_testcase' @aetest.setup def setup(self): self.value = 1 @aetest.test def another_trivial_test(self): self.value += -1 assert self.value == 0 @aetest.cleanup def cleanup(self): del self.value ``` -------------------------------- ### Define a PyATS AEtest Testcase Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/apidoc/aetest/index.md Example of subclassing the aetest.Testcase class to define a test case with setup, test, and cleanup methods. This is the standard way to structure tests in PyATS. ```python >>> class MyTestcase(aetest.Testcase): ... @aetest.setup ... def setup(self): ... pass ... ... @aetest.test ... def test(self): ... pass ... ... @aetest.cleanup ... def cleanup(self): ... pass ``` -------------------------------- ### Minimal YAML Testbed File Example Source: https://github.com/ciscotestautomation/pyats/blob/main/docs/resources/testbench.md Provides the structure for the shortest possible YAML testbed file, defining a single device with its type, alias, and connection details, along with a single interface. ```yaml # Example # ------- # # testbench YAML testbed file devices: device_name: # use actual device name here type: "device_type" alias: "alias of device" # optional connections: a: # define a single connection protocol: "telnet" ip: 1.1.1.1 port: 8888 topology: device_name: # use actual device name here interfaces: Ethernet1/1: # define a single interface alias: "test_intf" # optional type: "ethernet" ```