Package: pytest-netdut
Netdut: automated software testing for switches using pytestNetdut is apytestplugin which provides infrastructure (e.g. pytest fixtures) which make it easy to write automated tests for network switches.FeaturesBrings the power, maturity and ecosystem of pytest to testing on network switches.Thedutfixture (Device Under Test) providing serial, ssh orEAPIconnectivity for running CLI commands on a network switch.Command-line configuration of a hostname and console name.Markers for skipping tests based on the device's type or software configuration.Compatibility with both Arista's EOS operating system, and the Metamako MOS operating system.A pythonic interfaces for writing EOS CLI commands.RequirementsRequires python3 >= 3.6, pexpect, pyeapiNetwork devices under test (DUTs) must be accessible via SSH.InstallationYou can installpytest-netdutviapipfromPyPI:$ pip install pytest-netdutThepytest-netdutplugin is not auto-loaded upon installation. To enable pytest-netdut for your
tests, add the following to aconftest.pyfile:pytest_plugins = ["pytest_netdut"]or explicitly add it when you run pytest:pytest -p pytest_netdutUsageBasicsSeveral example tests using pytest-netdut are contained inexamples/. Note that there is aconftest.pyin that directory which enables pytest-netdut and increases the verbosity of the CLI output.The DUT must be accessible via SSH to use the SSH or EAPI fixtures (the latter enables and disables the EAPI using SSH). This can usually be achieved using this EOS config:enable
        configure
            username admin privilege 15 nopassword
            aaa authorization exec default localtest_showver.pydemonstrates some basic examples using the dut fixture. The tests can be
be run using the command below.pytest--device=<YOUR_DEVICE_IP_OR_DNS>examples/test_showver.pytest_showverrunsshow versionvia EAPI:deftest_showver(dut):info=dut.eapi.sendcmd("show version")logging.critical(f"DUT model was:{info['modelName']}")Running this using a device with a hostname ofdmb224gives some simple output:AssertionsBecause this is pytest, we get great feedback when tests fail. Tests fail upon assertions. Here we use the test below as an example.deftest_check_version(dut):info=dut.eapi.sendcmd("show version")assertinfo["version"]=="1.0.0"Netdut will start EAPI and use it to run theshow versioncommand, returning the results as a python dictionary. The assertion then fails, assuming the DUT is not running version 1.0.0 of EOS (in this case it is running an old internal build):Running multiple commandsIt's rare that a test will execute a single command on the DUT. Netdut allows for multi-command tests. This can be seen inexamples/test_daemon.pywhere the daemon
is configured:dut.eapi.sendcmds("""enableconfiguredaemon sleeperexec /usr/bin/sleep 10no shutdown""")In this case the result that is returned is list of the results of each command. It's often useful
to just return the last one:defdaemon_has_started():daemon_info=dut.eapi.sendcmds(["enable",f"show daemon{sleeper_daemon}"])[-1]returndaemon_info["daemons"][sleeper_daemon]["starttime"]!=0.0Waiting for resultsIt's often useful to provide some configuration to the switch, and then wait for the
switch to act (since it's running asynchronously). pytest-netdut provides thewait_forfixture for this purpose. Again, inexamples/test_daemon.pywe usewait_forto wait for
the daemon to start and stop.# daemon_has_started is defined as a local function# wait_for calls it repeatedly until it's truewait_for(daemon_has_started,timeout=10.0)Skipping based on DUT typePerhaps some tests won't run on every type of device --pytest-netdutprovides some skipping mechanisms for this purpose. To skip a test on a particular on a DUT type use the provided
decorator:@pytest.mark.skip_device_type("DCS-7130.*",reason="Demo")deftest_that_skips_7130(dut):logging.info("Must not be 7130!")Similar decorators exist for OS type (i.e. EOS-only or MOS-only tests), and can be stacked:@pytest.mark.eos@pytest.mark.skip_device_type("DCS-7130.*")deftest_that_only_runs_on_eos_on_7130(dut):logging.info("Must be EOS on 7130!")OS decorators accept the following keywords:min_version (string)min_change_number (int)If both kwargs are specified, min_change_number takes precedence.@pytest.mark.eos(min_version="4.30.0",min_change_number=3452345)@pytest.mark.skip_device_type("DCS-7130.*")deftest_that_only_runs_on_eos_on_7130(dut):logging.info("Must be EOS on 7130!")Building test harnessesPytest's fixture mechanism is very powerful in this scenario, allowing us to set up and tear
down test configurations with low overhead.@pytest.fixturedefmy_test_harness(dut):dut.eapi.sendcmds(["enable","configure","banner motd My test is running, hands off!"])yielddut.eapi.sendcmds(["enable","configure","no banner"])deftest_mytest(my_test_harness):logging.info("Running my test here")TranslationsIn order to reduce test code verbosity and complexity a translator class provides a way to standardize tests to a particular OS.
Both CLI commands and results are standardized to EOS by default.A particular test can be written with EOS CLI and be run on MOS as well.
Consider thel1 sourcecommand which differs between EOS and MOS:@pytest.fixturedefl1_connect(dut):ifdut.ssh.cli_flavor=="eos":dut.eapi.sendcmds(["enable","configure","interface Ethernet10","l1 source interface Ethernet12"])elifdut.ssh.cli_flavor=="mos":dut.eapi.sendcmds(["enable","configure","interface Ethernet10","source Ethernet12"])which can be reduced to:@pytest.fixturedefl1_connect(dut):dut.eapi.sendcmds(["enable","configure","interface Ethernet10","l1 source interface Ethernet12"])The translator will try to find a match for each command in the predefined list of regex configuration patterns.The translator will also process return values; MOS EAPI result keys are camelCased and the translator will convert all keys
to snake_case.The translator has a predefined set of translations which can be extended by subclassing the Translator class and overridingconfig_patterns.
Return values are processed by thetranslate_keyfunction which must be defined in the subclass.Set the new translator class viaeapi.set_translator(<class instance>).ContributingThis project is under active use and development. We would appreciate help to improve it,
via pull request. Tests can be run withmake ciortox.Docstrings are according toGoogle's docstring conventions(examples).LicenseDistributed under the terms of theBSD-3license,pytest-netdutis free and open source softwareIssuesIf you encounter any problems, pleasefile an issuealong with a detailed description.Copyright (c) 2021, David Snowdon
All rights reserved.Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.Neither the name of pytest-netdut nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.