taf.testlib.afs¶
afs.py
AFS-specific functionality
-
class
taf.testlib.afs.AFS(config)[source]¶ Bases:
objectBasic interact with AFS.
-
_get_maps_id()[source]¶ Return list of map’s ids founded in running config.
Raises: AFSException – AFS running config is not available Returns: list of map’s ids founded in running config Return type: list
-
_get_port(connection_element)[source]¶ Get AFS port number from portmap.
Parameters: connection_element (list) – Link information Raises: AFSException – invalid port number in connection element Returns: Port number Return type: int
-
_get_ports_from_config(connection=None)[source]¶ Return AFS port number from given connection.
Parameters: connection (list) – Link information Returns: Port numbers Return type: tuple
-
class_logger= <logging.LoggerAdapter object>¶
-
reenable_port(port, dev_id)[source]¶ Set Down and than Up status for AFS port connected to given port and device.
Parameters: Returns: True if workaround performed and False if skipped.
Return type:
-
-
taf.testlib.afs.afs_conf_mode(function)[source]¶ Decorator: get afs_instance with enabled config mode for class methods.
-
taf.testlib.afs.get_unused_values(used_values, min_value, max_value)[source]¶ Return two first unused values from range min_value - max_value.
Parameters: Raises: AFSException – not enough free values
Returns: Two first unused values from range min_value - max_value
Return type:
-
taf.testlib.afs.set_vty_timeout(afs_instance, config_prompt)[source]¶ Set AFS vty timeout.
Parameters: - afs_instance (CLIGenericMixin) – Instance of AFS device
- config_prompt (str) – Prompt message
Notes
By default AFS has timeout = 1800 seconds. Such long timeout could cause excided number of allowed connection in case any error.
taf.testlib.afscross¶
afscross.py
xconnect-specific functionality
-
class
taf.testlib.afscross.AFS(config, opts, env)[source]¶ Bases:
taf.testlib.dev_basecross.GenericXConnectMixinBasic interact with ASF.
-
__init__(config, opts, env)[source]¶ Reading/updating config, initialize afs object instance.
Parameters: - config (dict) – Configuration
- opts (OptionParser) – Options
- env (Environment) – Environment object
-
class_logger= <logging.LoggerAdapter object>¶
-
cross_clear()[source]¶ Clear all connections between switches. (Not supporter for AFS environment).
Raises: CrossException – not supported method
-
cross_connect(conn_list)[source]¶ Make connections between switches.
Parameters: conn_list (list[list[int]]) – List of connections in format: [[sw1, port1, sw2, port2], … ] Examples:
cross_connect([[0, 1, 1, 1], [0, 2, 1, 2]])
-
taf.testlib.caselogger¶
taf.testlib.cli_template¶
cli_template.py
Abstract class for any CLI classes
-
class
taf.testlib.cli_template.CLIGenericMixin[source]¶ Bases:
objectBase class for CLI configuration.
-
action_on_connect(obj, alternatives, timeout=60, interval=0.1, command_timeout=600, is_shell=False)[source]¶ Performs actions on found prompts. Returns command output data. This is only for CLI connect. See action_on_expect for details.
Parameters: - obj (Channel) – CLI object of different types.
- alternatives (tuple) –
Tuples of (“expected line”, “action if line is found”, <Exit execution? (bool)>, <Use ones? (bool)>). action can be:
- str - in case this is just command;
- function - callable object to execute without parameters;
- timeout (int) – Expecting timeout.
- interval (int) – Interval between read data cycles.
- command_timeout (int) – Command execution timeout.
- is_shell (bool) – Indicates shell command
Raises: CLIException – sudoprompt is not defined
Returns: Full output
Return type:
-
action_on_expect(obj, alternatives, timeout=60, interval=0.1, command_timeout=600, is_shell=False)[source]¶ Performs actions on found prompts. Returns command output data.
Parameters: - obj (Channel) – CLI object of different types.
- alternatives (tuple | list) –
Tuples of (“expected line”, “action if line is found”, <Exit execution? (bool)>, <Use ones? (bool)>). action can be:
- str - in case this is just command;
- function - callable object to execute without parameters;
- timeout (int) – Expecting timeout.
- interval (int | float) – Interval between read data cycles.
- command_timeout (int) – Command execution timeout.
- is_shell (bool) – Indicates shell command
Raises: CLIException – timeout exceeded for command execution
Returns: Full output
Return type:
-
class_logger= <logging.LoggerAdapter object>¶
-
cmd_output_log(so, se)[source]¶ log message normalizer.
Parameters: Returns: Normalized output
Return type:
-
exec_command()[source]¶ Execute command without shell (tty).
Parameters: Returns: tuple of stdout, stderr, rc
Return type:
-
expect(obj, expect_list, timeout=60, interval=0.1, remove_cmd=True, is_shell=False)[source]¶ Expecting prompts and return prompt index in expect_list.
Parameters: - obj (Channel) – CLI obj of different types.
- expect_list (list) – List of compiled re objects to find prompt in data.
- timeout (int) – Expecting timeout.
- interval (int) – Interval between read data cycles.
- remove_cmd (bool) – Flag whether to remove command from output during searching prompt in data.
- is_shell (bool) – Indicates shell command
Returns: Found position from expect_list and full command output
Return type:
-
login()[source]¶ Do CLI object login procedure.
Parameters: - username (str) – Host login (string).
- password (str) – Host password(string).
- timeout (int) – Time to execute login procedure (integer).
- wait_login (int) – time to wait login prompt before sending <Enter>. <Enter> is necessary if login prompt has been already appeared before connection is established.
- alternatives (list of tuples) – list of alternative prompts and actions.
- connect (bool) – Flag if connection should be established before login procedure (bool).
Returns: None
-
normalize_output(data, command, ret_code, end_pattern=None)[source]¶ Removes command and command’s end flag from output data. Extracts return code of the command.
Parameters: Returns: data and return code
Return type:
-
prepare_alter(command, alternatives=None, sudo=False, ret_code=True, page_break=None)[source]¶ Adds specified alternatives to list, updates command with end command and sudo if needed.
Parameters: - command (str) – Command to be executed.
- alternatives (tuple) –
Tuples of (“expected line”, “action if line is found”, <Exit execution? (bool)>, <Use ones? (bool)>). action can be:
- str - in case this is just command;
- function - callable object to execute without parameters;
- sudo (bool) – Flag if sudo should be added to the list of alternatives .
- ret_code (bool) – Flag if return code should be added to the list of alternatives.
- page_break (bool) – Flag if page break should be added to the list of alternatives.
Returns: command, alternatives, end_pattern
Return type:
-
prepare_pexpect_obj(pexp_obj)[source]¶ Add read(), write() and expect() methods to emulate object IO methods.
Parameters: pexp_obj (pexpect) – pexpect object. Returns: pexpect object. Return type: pexpect
-
prepare_ssh_shell_obj(shell)[source]¶ Add read(), write() and expect() methods to emulate object IO methods.
Parameters: shell (paramiko.Channel) – paramiko.Channel object. Returns: paramiko.Channel object. Return type: paramiko.Channel
-
prepare_telnet_obj(telnet_obj)[source]¶ Add read() and expect() methods to object to emulate object IO methods.
Parameters: telnet_obj (telnetlib) – telnetlib object. Returns: telnetlib object Return type: telnetlib
-
randstr(length)[source]¶ Return random string with required length.
Parameters: length (int) – Required length
-
send_command()[source]¶ Run command without waiting response.
Parameters: command (str) – Command to be executed.
-
shell_command()[source]¶ Run interactive command on previously created shell (tty).
Parameters: - command (str) – Command to be executed.
- alternatives (tuple) –
Tuples of (“expected line”, “action if line is found”, <Exit execution? (bool)>, <Use ones? (bool)>). action can be:
- str - in case this is just command;
- function - callable object to execute without parameters;
- timeout (int) – Expecting timeout.
- sudo (bool) – Flag if sudo should be added to the list of alternatives.
- ret_code (bool) – Flag if return code should be added to the list of alternatives.
- expected_rc (int) – Sets return code and verifies if return code of executed command the same as expected return code (int or str).
- quiet (bool) – Flag to verify if expected return equals expected.
- raw_output (bool) – Flag whether to return ‘pure’ output.
-
-
class
taf.testlib.cli_template.CmdStatus(stdout, stderr, rc)¶ Bases:
tuple-
__getnewargs__()¶ Return self as a plain tuple. Used by copy and pickle.
-
static
__new__(_cls, stdout, stderr, rc)¶ Create new instance of CmdStatus(stdout, stderr, rc)
-
__repr__()¶ Return a nicely formatted representation string
-
_asdict()¶ Return a new OrderedDict which maps field names to their values.
-
classmethod
_make(iterable, new=<built-in method __new__ of type object>, len=<built-in function len>)¶ Make a new CmdStatus object from a sequence or iterable
-
_replace(**kwds)¶ Return a new CmdStatus object replacing specified fields with new values
-
rc¶ Alias for field number 2
-
stderr¶ Alias for field number 1
-
stdout¶ Alias for field number 0
-
taf.testlib.clicmd_iss¶
clicmd_iss.py
Module for CLI specific functionality
-
class
taf.testlib.clicmd_iss.CLICmd(ipaddr, port, login, passw, prompt, devtype, delay=None, build_path=None, img_path=None, page_break='<?> - help.', xmlrpcport=None)[source]¶ Bases:
objectClass for CLI specific functionality.
Parameters: - config – environment config.
- switches – switches list.
-
__init__(ipaddr, port, login, passw, prompt, devtype, delay=None, build_path=None, img_path=None, page_break='<?> - help.', xmlrpcport=None)[source]¶ Initialize CLICmd class
-
_connect_to_switch(prompt, timeout=20)[source]¶ SSH connect to switch and wait untill prompt string appeared.
Parameters: Returns: None
Examples:
self._connect_to_switches(sw_keys=1, prompt="Switch ")
-
cli_connect(prompt=None)[source]¶ SSH connect to switch and wait untill prompt string appeared.
Parameters: prompt (str) – expected CLI prompt. Returns: None Examples:
env.switch[1].cli.cli_connect(prompt="Switch ")
-
cli_disconnect()[source]¶ Close ssh connection to switch.
Raises: CLICMDException – error on disconnect Returns: None Examples:
env.switch[1].cli.cli_disconnect()
-
cli_get(arguments_list, prompt=None, show=True, timeout=25)[source]¶ Getting values by CLI.
Parameters: Raises: Exception – error on command execution
Returns: List of CLI-GET command results.
Return type: Examples:
env.switch[1].cli.cli_get(['enable, none 0 none', 'statistics, Port 1, RX Discards']])
-
cli_get_all(arguments_list, prompt=None, timeout=25, interval=0.1)[source]¶ Getting values by CLI.
Parameters: Raises: Exception – error on command execution
Returns: List of CLI-GET command results.
Return type:
-
cli_set(commands_list, timeout=5, prompt=None, connect=True)[source]¶ Setting values by CLI.
Parameters: Raises: Exception – error on command execution
Returns: List of CLI-SET command results.
Return type: Examples:
env.switch[1].cli.cli_set([["enable"], ["vlan-database"], ["vlan 10"]])
-
suite_logger= <logging.LoggerAdapter object>¶
-
taf.testlib.clicmd_iss.get_column_names(table_data, column_ranges)[source]¶ Get column name.
Parameters: Returns: column_names_list - List of strings with columns names
Return type:
-
taf.testlib.clicmd_iss.get_column_ranges(line)[source]¶ Get column ranges.
Parameters: line (str) – string with “–” column delimiters Returns: column_indexes - list of lists with string indexes of columns Return type: list[list[str]]
-
taf.testlib.clicmd_iss.get_dotted_table(table_lines)[source]¶ Get table data.
Parameters: table_lines (list) – list of table rows Returns: table_list - list of lists with row names and values Return type: list[list]
-
taf.testlib.clicmd_iss.get_table_title(line)[source]¶ Get table name.
Parameters: line (str) – output
-
taf.testlib.clicmd_iss.get_table_value(table_data, identifier=None, checker=None)[source]¶ Gets necessary field value from the table.
Parameters: Raises: CLICMDException – invalid row length
Returns: Field value.
Return type:
taf.testlib.clicmd_ons¶
taf.testlib.clinns¶
clinns.py
Module contains classes for managing device using SSH connection or SSH connection emulation for Linux Network
-
class
taf.testlib.clinns.CLISSHNetNS(nsname, port=None, username=None, password=None, page_break=None, prompt=None, pass_prompt=None, sudo_prompt=None, login_prompt=None, page_break_lines=None, exit_cmd=None, timeout=10, quiet=False)[source]¶ Bases:
taf.testlib.cli_template.CLIGenericMixinClass for executing command inside of namespace. Unused parameters added to support the same interface for other CLI classes.
Examples:
client = CLISSHNetNS("some_nns", timeout=10) client.exec_command("some_command")
-
__init__(nsname, port=None, username=None, password=None, page_break=None, prompt=None, pass_prompt=None, sudo_prompt=None, login_prompt=None, page_break_lines=None, exit_cmd=None, timeout=10, quiet=False)[source]¶ Initialize CLISSHNetNS class.
Parameters: - nsname (str) – NNS name.
- port (int) – Host port.
- username (str) – Host user
- password (str) – Host password
- page_break (str) – Page brake marker.
- prompt (str) – Shell prompt.
- pass_prompt (str) – Login password prompt.
- sudo_prompt (str) – Sudo password prompt.
- login_prompt (str) – Login prompt.
- page_break_lines (int) – Number of page brake lines.
- exit_cmd (str) – Command to perform telnet exit.
- timeout (int) – Default timeout for commands.
- quiet (bool) – Flag for return code verification.
-
class_logger= <logging.LoggerAdapter object>¶
-
exec_command(**kwargs)[source]¶ Add “ip netns exec ” prefix to all commands to forward them into network namespace.
-
native_cmd(command, shell=False, wait=True, verbose=True)[source]¶ Execute open command.
Parameters:
-
send_command(**kwargs)[source]¶ Add “ip netns exec ” prefix to all commands to forward them into network namespace.
-
taf.testlib.clissh¶
taf.testlib.clitelnet¶
clitelnet.py
Basic telnet class with command oriented functionality
-
class
taf.testlib.clitelnet.TelnetCMD(host=None, port=23, username=None, password=None, page_break='--More--', prompt=None, pass_prompt='Password: ', sudo_prompt=None, timeout=10, login_prompt='login: ', page_break_lines=3, exit_cmd=None, quiet=False)[source]¶ Bases:
taf.testlib.cli_template.CLIGenericMixinHighLevel telnet command oriented class. Unused parameters added to support the same interface for other CLI classes.
Examples:
client = TelnetCMD("1.1.1.1", 22) client.login("username", "paSSword")
-
__init__(host=None, port=23, username=None, password=None, page_break='--More--', prompt=None, pass_prompt='Password: ', sudo_prompt=None, timeout=10, login_prompt='login: ', page_break_lines=3, exit_cmd=None, quiet=False)[source]¶ Initialize TelnetCMD class.
Parameters: - host (str) – Target host IP address.
- port (int) – SSH port.
- username (str) – SSH login user.
- password (str) – SSH user password.
- page_break (str) – Page brake marker.
- prompt (str, list[str]) – Shell prompt or list of shell prompts.
- pass_prompt (str) – Login password prompt.
- sudo_prompt (str) – Sudo password prompt.
- timeout (int) – Default timeout for commands.
- login_prompt (str) – Login prompt.
- page_break_lines (int) – Number of page brake lines.
- exit_cmd (str) – Command to perform telnet exit (str).
- quiet (bool) – Flag for return code verification.
-
_check_telnet_obj()[source]¶ Check if telnet object exists (connection is established).
Raises: Exception – telnet connection is not established
-
_check_telnet_obj_connection()[source]¶ Verify if telnet connection exists.
Returns: True if telnet connection exists Return type: bool
-
_normalize_output(output=None, cmd=None, prompt=None)[source]¶ Remove everything from the response except the actual command output.
Parameters:
-
check_shell()[source]¶ Check if CLI connection is alive.
Raises: CLITelnetException – telnet connection is not established; user is not logged in
-
class_logger= <logging.LoggerAdapter object>¶
-
connect(with_login=True, wait_login=5, alternatives=None, wait_prompt=True, socket_closed=False)[source]¶ Create telnet connection and do login if necessary.
Parameters: - with_login (bool) – Perform login procedure or not. If param isn’t set try automatically determine login necessity. (True|False|None)
- wait_login (int) – time to wait login before sending <Enter>. <Enter> is necessary if login is already appeared.
- alternatives (tuple) –
Tuples of (“expected line”, “action if line is found”, <Exit execution? (bool)>, <Use ones? (bool)>). action can be:
- str - in case this is just command;
- function - callable object to execute without parameters;
- wait_prompt (bool) – Wait for prompt message or not.
- socket_closed (bool) – Determines if socket has been closed or not.
Raises: Exception – self.host is None; self.prompt is None
Returns: telnet stdout
Return type:
-
disconnect(with_exit=True)[source]¶ Do disconnect.
Parameters: with_exit (bool) – Flag specifies whether perform exit procedure.
-
enter_mode(cmd=None, new_prompt=None)[source]¶ Enter config/priv or other mode with specific prompt.
Parameters: Raises: Exception – undefined prompt, unexpected new prompt
Note
After success execution current prompt will be replaced with new propmt and saved in prompt_stack.
-
exec_command(command, timeout=None, sudo=False, ret_code=False)[source]¶ Execute command without shell (tty).
Parameters: Returns: output, “”, return code
Return type:
-
exit(wait_close=True)[source]¶ Do telnet exit/logout procedure. Wait until connection closed.
Parameters: wait_close (bool) – Flag specifies whether to verify successful exit and to return output data.
-
exit_mode(exit_cmd=None)[source]¶ Exit config/priv or other mode with specific prompt.
Parameters: exit_cmd (str) – Command to exit from current mode. Raises: Exception – undefined prompt, unexpected new prompt
-
get_file()[source]¶ This method isn’t supported by telnetlib.
Raises: CLITelnetException – unsupported
-
login(username=None, password=None, timeout=None, wait_login=0, alternatives=None, connect=True)[source]¶ Do CLI object login procedure.
Parameters: - username (str) – Host login (string).
- password (str) – Host password(string).
- timeout (int) – Time to execute login procedure (integer).
- wait_login (int) – time to wait login prompt before sending <Enter>. <Enter> is necessary if login prompt has been already appeared before connection is established.
- alternatives (list of tuples) – list of alternative prompts and actions.
- connect (bool) – Flag if connection should be established before login procedure (bool).
Returns: None
Raises: - Exception – username is not defined
- CLITelnetException – login timeout exceeded, unexpected login prompt
-
open_shell(raw_output=False)[source]¶ Call login method. Added to support other CLI objects interface.
Parameters: raw_output (bool) – Flag whether to read output buffer. Raises: CLITelnetException – telnet connection is not established Returns: telnet output Return type: str
-
put_file()[source]¶ This method isn’t supported by telnetlib.
Raises: CLITelnetException – unsupported
-
send_command(command)[source]¶ Run command without waiting response.
Parameters: command (str) – Command to be executed.
-
shell_command(command, alternatives=None, timeout=None, sudo=False, ret_code=True, new_prompt=None, expected_rc='0', quiet=None, raw_output=False, interval=0.1)[source]¶ Run interactive command on previously created shell (tty).
Parameters: - command (str) – Command to be executed.
- alternatives (tuple) –
Tuples of (“expected line”, “action if line is found”, <Exit execution? (bool)>, <Use ones? (bool)>). action can be:
- str - in case this is just command;
- function - callable object to execute without parameters;
- timeout (int) – Expecting timeout.
- sudo (bool) – Flag if sudo should be added to the list of alternatives.
- ret_code (bool) – Flag if return code should be added to the list of alternatives.
- expected_rc (int) – Sets return code and verifies if return code of executed command the same as expected return code (int or str).
- quiet (bool) – Flag to verify if expected return equals expected.
- raw_output (bool) – Flag whether to return ‘pure’ output.
- interval (int | float) – Interval between read data cycles.
- new_prompt (str) – Prompt which will replace current prompt after successful mode changing.
Raises: CLITelnetException – unexpected return code
-
taf.testlib.common3¶
common3.py
Testlib common functionality version 3.x
-
class
taf.testlib.common3.Cross(setup, env)[source]¶ Bases:
dictNew interface to cross object without device id.
-
cross_connect(conn_list)[source]¶ Wrapper for cross_connect method defined in xconnect.py module.
Parameters: conn_list (list[list]) – List of connections Raises: Exception – conn_list is empty
-
cross_disconnect(disconn_list)[source]¶ Wrapper for cross_disconnect method defined in xconnect.py module.
Parameters: disconn_list (list[list]) – List of connections Raises: Exception – disconn_list is empty
-
get_connection(dev_id, port_no)[source]¶ Get connection for device port.
Parameters: Raises: Exception – no connection for current port
Returns: Connection info
Return type:
-
get_device_id(connection)[source]¶ Search device in setup object by given connection.
Parameters: connection (list) – Connection info in format [sw1, port1, sw2, port2] Raises: Exception – no device in connection Returns: device id which own connection Return type: int
-
-
class
taf.testlib.common3.Environment(opts=None, **kwargs)[source]¶ Bases:
dictMain class of all test environment.
Notes
This class has to be used as base fixture in all test cases. It provides number of common methods to initialize, shutdown, cleanup environment functions which basically call appropriate methods of particular device classes.
-
__init__(opts=None, **kwargs)[source]¶ Read configuration files and create device objects.
Parameters: opts (OptionParser) – py.test config.option object which contains all py.test cli options. Raises: TAFCoreException – unexpected entry_type
Create dictionary with related device configurations.
Parameters: conf_ids (list[str]) – List of related config IDs. Raises: Exception – configuration is not found for specific device ID Returns: Dictionary with related device configurations Return type: dict
-
_get_conf(file_name=None)[source]¶ Load environment config from file.
Parameters: file_name (str) – Name of a json file with a test environment configuration.
Raises: - TAFCoreException – configuration file is not found
- IOError – error on reading configuration file
Returns: dict of the selected configuration.
Return type: Notes
This method shouldn’t be used outside this class. Use “config” attribute to access environment configuration.
-
_get_device_conf(device_id)[source]¶ Return config entry by given Id if one, else return None.
Parameters: device_id (str) – Entry ID. Returns: Entry config. Return type: dict
-
_get_prio_dict(prio)[source]¶ Return dict of entries by prio.
Parameters: prio (str) – Priority name to order dict by . Returns: dict of lists where key = priority, value = list of device objects. Return type: dict
-
_get_setup(file_name)[source]¶ Reads setup file based on provided name.
Parameters: file_name (str) – Name of a json file with setup.
Raises: - TAFCoreException – setup file is not found
- IOError – error on reading setup file
Returns: setup json content.
Return type:
-
check(entry_types=None)[source]¶ Checking environment.
Parameters: entry_types (list[str]) – List of entry types
-
class_logger= <logging.LoggerAdapter object>¶
-
cleanup(entry_types=None)[source]¶ Cleaning environment.
Parameters: entry_types (list[str]) – List of entry types
-
get_device_id(dut)[source]¶ Search device in config object by device name.
Parameters: dut (str) – Could be one of: device LINK_NAME, ‘autoname’ or ‘id’ from config. Raises: TAFCoreException – unknown device type Returns: Device id which configured. Return type: str, int Examples (Config object like):
{ "env": [ {"id": 5, "port_list": [["port1", 10000], ["port2", 40000]}, {"id": 9, "autoname": "DEV2", "port_list": [["port1", 10000], ["port2", 40000]} ] "cross": {"ID": [[5, 1, 9, 2], [5, 2, 9, 1]]} }
Result is:
# by LINK_NAME env.get_device_id("sw1") == 5 # by "autoname" env.get_device_id("DEV2") == 9 # by ID env.get_device_id(9) == 9
-
get_port_speed(dut, port_id)[source]¶ Search speed port in config object namely in ‘port_list’ by device name and port Id.
Parameters: Raises: TAFCoreException – port is not present in configuration’s ‘port_list’
Returns: Port speed or exception if there is no port with given Id in config.
Return type: Examples (Config object like):
{ "env": [ {"id": 5, "autoname": "DEV1", "port_list": [["port1", 10000], ["port2", 40000]}, {"id": 9, "ports": ["port10", 11]} ] "cross": {"ID": [[5, 1, 9, 2], [5, 2, 9, 1]]} }
Result is:
env.get_port_speed("sw1", 2) == 40000 env.get_port_speed("DEV1", 1) == 10000
-
get_ports(links=None)[source]¶ Returns dictionary of ports based on links between devices.
Parameters: links (list[list]) – List of devices in format [[‘dev1’, ‘dev2’, number_of_links, port_speed], ] (list of lists). Where: number_of_links - optional parameter(int or enum - “ALL”); port_speed - optional parameter. Raises: TAFCoreException – wrong link format Returns: ports Return type: dict Examples (Config object like):
{ "env": [ {"id": 99, "autoname": "DEV1", "port_list": [["port1", 10000], ["port2", 40000], ["port3", 10000]}, {"id": 100, "port_list": [["port10", 40000], [11, 10000], ["port12", 40000]} ] "cross": {"ID": [[99, 1, 100, 2], [99, 2, 100, 1]]} }
Result is:
ports = env.get_ports([['sw1', 'sw2', 1], ]) assert ports == {('sw2', 'sw1'): {1: "port10"}, ('sw1', 'sw2'): {1: "port1"}} ports = env.get_ports([['DEV1', 'sw2', 2], ]) assert ports == {('sw2', 'sw1'): {1: "port10", 2: 11}, ('sw1', 'sw2'): {1: "port1", 2: "port2"}} # with optional parameter "port_speed" ports = env.get_ports([['sw1', 'sw2', 1, 10000], ]) assert ports == {('sw1', 'sw2'): {1: "port1"}, ('sw2', 'sw1'): {1: "11"}} # Method returns all links between devices if no any optional parameters ports = env.get_ports([['sw1', 'sw2', ], ]) assert ports == {('sw1', 'sw2'): {1: "port1", 2: "port2"}, ('sw2', 'sw1'): {1: "port10", 2: 11}} # The same with enum "ALL" ports = env.get_ports([['sw1', 'sw2', "ALL"], ]) assert ports == {('sw1', 'sw2'): {1: "port1", 2: "port2"}, ('sw2', 'sw1'): {1: "port10", 2: 11}} # With optional parameters "port_speed" and "ALL" ports = env.get_ports([['sw1', 'sw2', "ALL", 40000], ]) assert ports == {('sw1', 'sw2'): {1: "port2"}, ('sw2', 'sw1'): {1: "port10"}} # Method returns all links between devices if no parameter ports = env.get_ports() assert ports == {('sw1', 'sw2'): {1: "port1", 2: "port2"}, ('sw2', 'sw1'): {1: "port10", 2: 11}}
-
get_real_port_name(dut, port_id)[source]¶ Search real port number/name by device name and port Id in config object.
Parameters: Raises: TAFCoreException – port_id is not found in configuration; device doesn’t have ports or port_list attributes
Returns: Real port number/name or exception if there is no port with given Id in config.
Return type: Examples (Config object like):
{ "env": [ {"id": 99, "autoname": "DEV1", "port_list": [["port1", 10000], ["port2", 10000]}, {"id": 100, "ports": ["port10", 11]} ] "cross": {"ID": [[99, 1, 100, 2], [99, 2, 100, 1]]} }
Result is:
# by LINK_MAME env.get_real_port_name("sw2", 2) == 11 # by "autoname" env.get_real_port_name("DEV1", 1) == "port1"
-
id2instance(device_id)[source]¶ Returns entry instance by device id.
Parameters: device_id (str) – Could be one of: device LINK_NAME, ‘autoname’ or ‘id’ from config. Returns: Entry instance Return type: GenericEntry Examples:
# by LINK_NAME env.id2instance("sw1") # by "autoname" env.get_device_id("DEV2") # by ID env.get_device_id("9")
-
initialize(entry_types=None)[source]¶ Initialize test environment.
Parameters: entry_types (list[str]) – List of entry types
-
ordered_action(action, prio, entry_types)[source]¶ Perform action on entries with type in entry_types and ordered by prio.
Parameters: Returns: None
-
parallelize(objects, method, safe=False)[source]¶ Run objects method in multiple threads.
Parameters: - objects (list[GenericEntry]) – list of device objects.
- method (str) – method name that has to be executed.
- safe (bool) – Hide exception raisings, but print log message.
Returns: None
Examples:
objects = [env.lhost[1], env.lhost[2]] env.parallelize(objects, "cleanup", False)
-
safe_executor(obj, method, *args, **kwargs)[source]¶ Invokes obj.method(*args, **kwargs) in try block and return error message with traceback.
Parameters: - obj (GenericEntry) – Entry instance
- method (str) – method name that has to be executed
Returns: Error message with traceback
Return type: Warning
- Don’t use in case obj.method has to return something.
- Don’t use in case an exception has to be handled by py.test.
-
-
taf.testlib.common3.softexit(message, env=None)[source]¶ Sanitizing environment and exit py.test execution.
Parameters: - message (str) – Exit message
- env (Environment) – Environment instance
taf.testlib.connpool¶
connpool.py
Connection Pool class
-
class
taf.testlib.connpool.ConnectionPool(connection_class=None, max_connections=None, time_to_live=30, **connection_kwargs)[source]¶ Bases:
objectGeneric connection pool`
-
__init__(connection_class=None, max_connections=None, time_to_live=30, **connection_kwargs)[source]¶ Initialize ConnectionPool class.
Parameters:
-
_created_connections()[source]¶ Return number of created connections
Returns: Number of created connections Return type: int
-
class_logger= <logging.LoggerAdapter object>¶
-
del_connection_in_use(connection)[source]¶ Delete connection in use (in case any error).
Parameters: connection (TelnetCMD) – Telnet connection
-
get_connection()[source]¶ Get a connection from the pool.
Raises: ConnPoolException – connection is dead, error on connection creation Returns: Telnet connection Return type: TelnetCMD
-
make_connection()[source]¶ Create a new connection.
Raises: ConnPoolException – too many connections Returns: Telnet connection Return type: TelnetCMD
-
taf.testlib.custom_exceptions¶
custom_exceptions.py
Class to handle custom exceptions with basic introspection
-
exception
taf.testlib.custom_exceptions.AFSException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle AFS exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.AccessError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for any access errors.
-
exception
taf.testlib.custom_exceptions.ArgumentError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for any argument errors.
-
exception
taf.testlib.custom_exceptions.BoundaryError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for any boundary errors.
-
exception
taf.testlib.custom_exceptions.CLICMDException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle clicmd exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CLIException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle CLI exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CLINNSException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CLIExceptionBase class to handle clinns exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CLISSHException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CLIExceptionBase class to handle clissh exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CLITelnetException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CLIExceptionBase class to handle clitelnet exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CmdArgsException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle command arguments exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.ConnPoolException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle ConnPoll exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CrossException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Xconnect exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.CustomException(value, trace=False)[source]¶ Bases:
ExceptionBase class to handle custom exceptions with basic introspection.
-
class_logger= <logging.LoggerAdapter object>¶
-
-
exception
taf.testlib.custom_exceptions.ExistsError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for any duplication errors.
-
exception
taf.testlib.custom_exceptions.HubException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Hub exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.InvalidCommandError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for any naming errors.
-
exception
taf.testlib.custom_exceptions.InvalidNameError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for any naming errors.
-
exception
taf.testlib.custom_exceptions.IxiaException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.TGExceptionBase class to handle IXIA exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.NotExistsError(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionAbstracted error class for accessing non-existent parameters.
-
exception
taf.testlib.custom_exceptions.OvsControllerException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Ovs Controller exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.PypackerException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.TGExceptionBase class to handle Pypacker exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.SshExecCommandFailed(command, ret)[source]¶ Bases:
Exception
-
exception
taf.testlib.custom_exceptions.SwitchException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Switch operation exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.SysLogException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle SysLog exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.TAFCoreException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Switch operation exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.TAFLegacyException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Pypacker exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.TGException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionGeneral TG exception.
-
exception
taf.testlib.custom_exceptions.ToolException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle Linux Tool operation exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.TrexException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.TGExceptionBase class to handle TRex exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.UICmdException(value, command, stdout, stderr, rc, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.UIExceptionBase class to handle test_ui command exceptions with basic introspection.
-
exception
taf.testlib.custom_exceptions.UIException(value, trace=False)[source]¶ Bases:
taf.testlib.custom_exceptions.CustomExceptionBase class to handle test_ui exceptions with basic introspection.
taf.testlib.dev_basecross¶
dev_basecross.py
Cross connect specific functionality
-
class
taf.testlib.dev_basecross.GenericXConnectMixin(config, opts)[source]¶ Bases:
taf.testlib.entry_template.GenericEntryGeneral Cross object functionality.
Configuration examples:
{ "name": "Zero Cross", "entry_type": "cross", "instance_type": "zero", "id": 31 }
- Where:
- entry_type and instance_type are mandatory values and cannot be changed for current device type.
- id - int or str uniq device ID (mandatory)
name - User defined device name (optional)
-
class
taf.testlib.dev_basecross.ZeroCross(config, opts)[source]¶ Bases:
taf.testlib.dev_basecross.GenericXConnectMixinStub for cross object in environment. It should be used for static connected environment.
-
_get_device_from_environment(device_id)[source]¶ Mandatory method for environment specific switch classes.
Parameters: device_id (str) – Device ID/autoname/linkname (‘tg1’)
-
cross_connect(conn_list=None)[source]¶ Mandatory method for environment specific switch classes.
Parameters: conn_list (list[list]) – List of connections
-
cross_disconnect(disconn_list=None)[source]¶ Mandatory method for environment specific switch classes.
Parameters: disconn_list (list[list]) – List of connections
-
taf.testlib.dev_chef¶
taf.testlib.dev_iperftg¶
taf.testlib.dev_ixia¶
taf.testlib.dev_linux_host¶
taf.testlib.dev_linux_host_vm¶
taf.testlib.dev_mrvcross¶
dev_mrvcross.py
MRV cross specific functionality
-
class
taf.testlib.dev_mrvcross.StaticCrossMRV(config, opts)[source]¶ Bases:
taf.testlib.dev_staticcross_ons.StaticCrossONSCross connection device based on MRV layer 1 switch.
taf.testlib.dev_onsswcross¶
dev_onsswcross.py
`Cross Connection device based on ONS switches
-
class
taf.testlib.dev_onsswcross.ONSSwitchCross(config, opts)[source]¶ Bases:
taf.testlib.dev_basecross.GenericXConnectMixinCross connection device based on ONS switch.
Configuration dictionary example:
{"id": "ONS_switch_cross_ID", "entry_type": "cross", "instance_type": "onssw", "ipaddr": "10.0.5.101", "port": "8081", "portmap":[[10, 1, 3], [10, 2, 4], [11, 1, 5], [11, 2, 6]]} Where portmap: [[<device ID>, <device port ID>, <self ONS switch port number>], ]
-
__init__(config, opts)[source]¶ Initialize ONSSwitchCross class.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
-
_clear_port_vlan_cfg(port)[source]¶ Remove port from VLAN if such configuration exists.
Parameters: port (int) – Port ID
-
_get_free_vlan()[source]¶ Return free vlan id.
Raises: Exception – no free vlans Returns: Free vlan id Return type: int
-
_get_self_port(dev_id, dev_port)[source]¶ Return self port id by connected device id and port.
Parameters: Raises: Exception – no device/port in port map
Returns: self port id
Return type:
-
class_logger= <logging.LoggerAdapter object>¶
-
cross_connect(conn_list=None)[source]¶ Peform all connections from conn_list.
Parameters: conn_list (list[list]) – List of connections
-
cross_disconnect(disconn_list=None)[source]¶ Destroy all connections from conn_list.
Parameters: disconn_list (list[list]) – List of connections
-
taf.testlib.dev_ovscontroller¶
taf.testlib.dev_settings¶
dev_settings.py
Settings entry class. ‘settings’ entry can contain any setup related info that is necessary for testing on that setup
-
class
taf.testlib.dev_settings.GenericSettings(config, opts)[source]¶ Bases:
taf.testlib.entry_template.GenericEntrySettings entry is used just to pass necessary info to tests and doesn’t require any actions.
Notes
Class returns settings dictionary without modifications on call.
taf.testlib.dev_staticcross_ons¶
dev_staticcross_ons.py
Staticcross_ons-specific functionality
-
class
taf.testlib.dev_staticcross_ons.StaticCrossONS(config, opts)[source]¶ Bases:
taf.testlib.dev_basecross.GenericXConnectMixinStub for cross object in environment.
-
__init__(config, opts)[source]¶ Initialize StaticCrossONS class.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
-
_get_device(device_id)[source]¶ Return device object by device id.
Parameters: device_id (str) – Device ID Raises: Exception – device is not present in related configurations Returns: Device object Return type: GenericEntry
-
class_logger= <logging.LoggerAdapter object>¶
-
cross_connect(conn_list=None)[source]¶ Configure Cross connect.
Parameters: conn_list (list[list]) – List of connections Raises: CrossException – devices from conn_list are not in related configurations
-
cross_disconnect(disconn_list=None)[source]¶ Configure Cross disconnect.
Parameters: disconn_list (list[list]) – List of connections
-
taf.testlib.dev_switch_lxc¶
taf.testlib.dev_switch_sdv_100g_rr¶
taf.testlib.dev_switch_seacliff¶
taf.testlib.dev_trextg¶
dev_trextg.py
TRex traffic generators specific functionality
Notes
- To install TRex client api package:
- Download package from http://trex-tgn.cisco.com/trex/release/
- Unpack main package ‘v2.00.tar.gz’ and then client package ‘trex_client_v2.00.tar.gz’
- Add path to the trex client stateless lib for PYTHONPATH environment variable: env PYTHONPATH=<your path>/trex_client/stl
-
class
taf.testlib.dev_trextg.Trex(config, opts)[source]¶ Bases:
taf.testlib.TRex.Trex.TrexMixin,taf.testlib.TRex.TrexHLT.TrexHLTMixin,taf.testlib.packet_processor.PacketProcessor,taf.testlib.tg_template.GenericTGTRex interaction base class.
Configuration examples:
TRex server Example:
{ "name": "TRex" "entry_type": "tg", "instance_type": "trex", "id": "TG1", "ports": [0, 1], "ipaddr": "1.1.1.1", "ssh_user": "user", "ssh_pass": "PassworD", }
Where:
entry_type and instance_type are mandatory values and cannot be changed
id - int or str uniq device ID (mandatory)
name - User defined device name (optional)
ports or port_list - short or long ports configuration (Only one of them has to be used)
ipaddr - remote host IP address (mandatory)
ssh_user - remote host login user (mandatory)
ssh_pass - remote host login password (mandatory)
- Notes:
- You can safely add additional custom attributes.
-
__init__(config, opts)[source]¶ Initializes connection to TRex.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
-
_get_speed_ports()[source]¶ Get ports with speed from config.
Returns: Tuple with list of ports used in real config and list of port/speed values Return type: tuple(list[tuple], list[tuple, int]) Notes
This function check if port has speed in config file.
-
class_logger= <logging.LoggerAdapter object>¶
-
cleanup(mode='complete')[source]¶ This method should do TRex ports cleanup (remove streams etc.)
Parameters: mode (str) – “fast” or “complete”. If mode == “fast”, method does not clear streams on the port (string)
-
get_os_mtu(iface=None)[source]¶ Get MTU value in host OS.
Parameters: iface (str) – Interface for getting MTU in host OS Returns: Original MTU value Return type: int Examples:
env.tg[1].get_os_mtu(iface=ports[('tg1', 'sw1')][1])
taf.testlib.dev_vethcross¶
dev_vethcross.py
Cross connection based on creating Virtual Ethernet devices
-
class
taf.testlib.dev_vethcross.VethCross(config, opts)[source]¶ Bases:
taf.testlib.dev_basecross.GenericXConnectMixinXconnect based on creating virtual ethernet interfaces.
Notes
It is used for simulated environment.
-
__init__(config, opts)[source]¶ Initialize VethCross class.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
-
_exec_x_command(connection, action)[source]¶ Create single connection.
Parameters: Raises: CrossException – incorrect action type, error on connection
-
class_logger= <logging.LoggerAdapter object>¶
-
cross_connect(conn_list=None)[source]¶ Create connections.
Parameters: conn_list (list[list]) – List of connections
-
cross_disconnect(disconn_list=None)[source]¶ Destroy connections.
Parameters: disconn_list (list[list]) – List of connections
-
generic_generic(connection, action)[source]¶ Returns set of commands to create connection between 2 default NNS.
This is used to create just veth interfaces without netns.
Parameters:
-
generic_netns(connection, action)[source]¶ Returns set of commands to create/destroy connection between default NNS and custom NNS.
Parameters:
-
get_name_port(dev_id, port_id)[source]¶ Get port name.
Parameters: Returns: Device name, Port name
Return type:
-
netns_netns(connection, action)[source]¶ Returns set of commands to create/destroy connection between 2 Linux Network Namespaces.
Parameters:
-
taf.testlib.dev_vlabcross¶
dev_vlabcross.py`
ONS Vlab virtual cross specific functionality
-
class
taf.testlib.dev_vlabcross.VlabCross(config, opts)[source]¶ Bases:
taf.testlib.dev_vlabcross.VlabEnvVlab from xconnect viewpoint.
-
_get_ports_from_config(connection=None)[source]¶ Get ports from configuration.
Parameters: connection (list) – Connection info in format [sw1, port1, sw2, port2]
Raises: - CrossException – unsupported connection type
- ValueError – error in configuration file
Returns: Ports from configuration
Return type:
-
class_logger= <logging.LoggerAdapter object>¶
-
cross_clear()[source]¶ Clear all connections between switches
Raises: CrossException – error on connections clearing Returns: True if success or False if all connections were not cleared. Return type: bool Examples:
cross_clear(env)
-
cross_connect(conn_list)[source]¶ Make connections between switches.
Parameters: conn_list (list[list]) – Set of connections in format: [[sw1, port1, sw2, port2], … ] Raises: CrossException – devices from conn_list are not in related configurations, error on connection creation Returns: True if success or raise an error if connections were not created. Return type: bool Examples:
cross_connect([[0, 1, 1, 1], [0, 2, 1, 2]])
-
cross_disconnect(disconn_list)[source]¶ Destroy connections between switches.
Parameters: disconn_list (list[list]) – Set of connections in format: [[sw1, port1, sw2, port2], … ] Raises: CrossException – error on connection destroying Returns: True if success or False if connections were not destroyed. Return type: bool Examples:
cross_disconnect([[0, 1, 1, 1], [0, 2, 1, 2]])
-
-
class
taf.testlib.dev_vlabcross.VlabEnv(config, opts)[source]¶ Bases:
taf.testlib.dev_basecross.GenericXConnectMixinVlab from device viewpoint.
-
DEFAULT_TIMEOUT= 1¶
-
__init__(config, opts)[source]¶ Initialize VlabEnv class.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
Raises: CrossException – error in vlab path
-
class_logger= <logging.LoggerAdapter object>¶
-
probe_port()[source]¶ Establishing a connection to a remote host.
Returns: True if connection is established Return type: bool
-
start()[source]¶ Starts vlab based on provided host and port info with specified number of interfaces.
Raises: - CrossException – not local environment, vlab is stopped
- Exception – error on vlab start
-
stop()[source]¶ Stops vlab based on provided host and port info.
Raises: CrossException – error on vlab stop
-
waitoff(timeout=30)[source]¶ Waiting until Vlab port is down.
Parameters: timeout (int) – Waiting timeout Raises: CrossException – error on vlab stop Returns: Vlab status Return type: dict
-
waiton(timeout=30)[source]¶ Waiting until Vlab port is up.
Parameters: timeout (int) – Waiting timeout Raises: CrossException – error on vlab start Returns: Vlab status Return type: dict
-
taf.testlib.entry_template¶
entry_template.py
Interface class for any TAF environment configuration entry
-
class
taf.testlib.entry_template.GenericEntry(config, opts)[source]¶ Bases:
objectInterface class for any TAF environment configuration entry.
-
__init__(config, opts)[source]¶ Entry __init__ method has to take 2 parameters.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
-
check()[source]¶ Called in environment check method. Used before/after TC to verify that environment is ready to use.
-
cleanup()[source]¶ Called in environment cleanup method. It’s used to delete all runtime configuration and return entry to default state.
-
create()[source]¶ Called on environment initialize step. It should contain any steps necessary to start using device instance.
-
destroy()[source]¶ Called on environment shutdown step. It should contain any necessary steps to release used device.
-
sanitize()[source]¶ Called in environment sanitize method. It’s used by pytest.softexit and should contain any steps to release possible locks.
-
start()[source]¶ This method could be called by create method and has to prepare entry object for processing commands.
E.g. It can power on device, or launch some service on it. You can use create method itself for this. But usually create method checks some CLI options (–get_only) and decides to invoke start or not.
-
stop()[source]¶ This method could be called by destroy method and has to release entry object configuration.
E.g. It can power off device, or stop some service on it. You can use destroy method itself for this. But usually destroy method checks some CLI options (–get_only, –leave_on) and decides to invoke stop or not.
-
taf.testlib.environment¶
environment.py
Environment-specific functionality
-
taf.testlib.environment.get_absolute_build_path(build_path=None)[source]¶ Return absolute path to switchpp binaries.
Parameters: build_path (str) – path to switchpp binaries . Returns: absolute path to switchpp binaries if one exists or None if not Return type: str Examples:
get_absolute_build_path(build_path="/some/path/switchpp")
-
taf.testlib.environment.get_conf_file(conf_name=None, conf_type='env')[source]¶ Return full path to conf file.
Parameters: Raises: CustomException – conf_name is None
- Raturns:
- str: absolute path to configuration file if one exists or None if else.
Notes
- Discovery order:
- search if current folder;
- search in /usr/local/bin/taf/<conf_type>/;
- search in /etc/taf/<conf_type>/.
Examples:
get_conf_file(conf_name="simplified_setup.json", conf_type='cross')
taf.testlib.fixtures¶
taf.testlib.helpers¶
helpers.py
Helpers functions
-
taf.testlib.helpers.change_stp_state(switche_instance, state)[source]¶ Disables/Enables STP state on per-port basis.
Notes
Very useful to prevent packet storm caused by global STP disabling.
Parameters: Returns: None
-
taf.testlib.helpers.clear_table(switch_instance=None, table_name=None)[source]¶ Clear table for correct test cases work.
Parameters: - switch_instance (xmlrpclib.ServerProxy object) – Switch instance to work with
- table_name (str) – Specific table name
Returns: None
Examples:
clear_table(switch_instance=env.switch[1], table_name="ACLRules")
-
taf.testlib.helpers.designated_port(priority, port_id)[source]¶ Function for return hex string value that is sum of bridgePriority and port_id in hex format.
Parameters: Returns: Hex Value without 0x prefix
Examples:
helpers.designated_port(32768, 28)
-
taf.testlib.helpers.disable_lldp_for_all_ports(switch_instance)[source]¶ Disable Lldp on all device ports.
Parameters: switch_instance (object) – Switch instance to work with Returns: None Examples:
helpers.disable_lldp_for_all_ports(env.switch[1])
-
taf.testlib.helpers.generate_random_ip(ip_exclusions=None, prefix=None, quantity=1)[source]¶ Generate list that contains randomly generated IP addresses that starts from prefix.
Parameters: Returns: ip_pool list of generated MAC addresses
Return type: Examples:
source_ips = helpers.generate_random_ip(ip_exclusions = router_ips, prefix = "10.0.1", quantity = streams_quantity)
-
taf.testlib.helpers.generate_random_mac(mac_exclusions=None, quantity=1)[source]¶ Generate list that contains randomly generated MAC addresses that starts from 00.
Parameters: Returns: mac_pool list of generated MAC addresses
Return type: Examples:
source_macs = helpers.generate_random_mac(mac_exclusions = ["01:00:02:00:00:01", ], quantity = 10)
-
taf.testlib.helpers.get_attribute_from_argvalue(argvalue, item)[source]¶ Gets an attribute from argvalues.
Parameters: item (int | str) – This can be an int (it will attempt to retrieve an index or a str (it will attempt to retrieve a NamedTuple’s field name)
Raises: - AttributeError – when attribute not found
- IndexError – when index not found
Returns: str
-
taf.testlib.helpers.get_packet_from_the_port(sniff_port=None, params=None, sniff_data=None, tg=None)[source]¶ Return packet from the sniffer data according to search criteria.
Parameters: Returns: packet or None
Examples:
helpers.get_packet_from_the_port('vlab0', ({'layer': "Ether", 'field': "src", 'value': "00:00:00:01:02:03".lower()},), data, env.tg[1])
-
taf.testlib.helpers.get_stepped_value(value, step, step_type='Down')[source]¶ Returns the rounded value, given an initial input value.
Parameters: Raises: Returns: int
-
taf.testlib.helpers.grouper(iterable, n)[source]¶ Collect data into fixed-length chunks or blocks
grouper(‘ABCDEFG’, 3) –> ABC DEF G
Modified from http://stackoverflow.com/users/1052325/reclosedev ‘s modification of http://stackoverflow.com/users/279627/sven-marnach ‘s answer
http://stackoverflow.com/a/8998040
Parameters: - iterable (iter()) – iterable to group into chunks
- n (int) – chunk size
Returns: itererable of chunks of size n
Return type: iter(list)
-
taf.testlib.helpers.grouper_it(iterable, n)[source]¶ Collect data into iterables of fixed-length chunks or blocks
grouper_it(‘ABCDEFG’, 3) –> iter(ABC) iter(DEF) iter(G)
Copyied from http://stackoverflow.com/users/1052325/reclosedev ‘s modification of http://stackoverflow.com/users/279627/sven-marnach ‘s answer
http://stackoverflow.com/a/8998040
Parameters: - iterable (iter()) – iterable to group into chunks
- n (int) – chunk size
Returns: return an iterable of iterables of chunk size n
Return type: iter(iter())
-
taf.testlib.helpers.is_double_tag_packet_received(iface=None, destination_mac=None, eth_type=37120, prio_1=6, prio_2=None, vlan_1=None, vlan_2=None, result=True, type_1=None, type_2=None, tg_instance=None)[source]¶ Check if proper packet is received.
Parameters: - iface (str) – Interface
- destination_mac (str) – Destination MAC address
- eth_type (hex) – Ether.type
- prio_1 (int) – Dot1Q.prio of outer layer
- prio_2 (int) – Dot1Q.prio of inner layer
- vlan_1 (int) – Dot1Q.vlan of outer layer
- vlan_2 (int) – Dot1Q.vlan of inner layer
- type_1 (int) – Dot1Q.type of outer layer
- type_2 (int) – Dot1Q.type of inner layer
- result (bool) – Expected result: true or false
- tg_instance (str) – TG instance
Returns: True or raise exception
Examples:
self._check_if_double_tag_packet_received(iface=data[sniff_ports[3]],destination_mac=self.destination_mac, vlan_1=self.vlan_id_20, vlan_2=self.vlan_id_10, type_1=0x8100, type_2=0x800, tg_instance=env.tg[1])
-
taf.testlib.helpers.is_entry_added_to_acl_actions_table(action=None, param=None, switch_instance=None)[source]¶ Check entry in ACL Actions Table.
Parameters: Returns: True or False
Return type: Examples:
is_entry_added_to_acl_actions_table(action=action_acl, param=param_acl, switch_instance=env.switch[1].xmlproxy)
-
taf.testlib.helpers.is_entry_added_to_acl_expressions_table(field=None, mask=None, data=None, switch_instance=None)[source]¶ Check entry in ACL Expressions Table.
Parameters: Returns: True or False
Return type: Examples:
is_entry_added_to_acl_expressions_table(field=field, mask=mask_acl, data=data_acl, switch_instance=env.switch[1].xmlproxy)
-
taf.testlib.helpers.is_entry_added_to_fdb(mac_address=None, port_id=1, vlan_id=1, switch_instance=None)[source]¶ Check dynamic entry in FDB.
Parameters: Returns: True or False
Return type: Examples:
is_entry_added_to_fdb(mac_address=source_mac, port_id=1, vlan_id=vlab_id, switch_instance=env.switch[1].xmlproxy)
-
taf.testlib.helpers.is_entry_added_to_rules_table(rule_id=1, expression_id=1, action_id=1, stage=None, enabled='Disabled', priority=1, switch_instance=None)[source]¶ Check entry in ACL Rules Table.
Parameters: - switch_instance (xmlrpclib.ServerProxy object) – Switch instance to work with
- rule_id (int) – Given ruleId from the ACLRules table
- expression_id (int) – Given expressionId from the ACLExpressions table
- action_id (int) – Given actionId from the ACLActions table
- stage (str) – “Ingress”, “Egress”, “Lookup”
- enabled (str) – Enable or disable rule
- priority (int) – Rules priority
Returns: True or False
Return type: Examples:
is_entry_added_to_rules_table(rule_id=rule_id, expression_id=expression_id, action_id=action_id, stage=rules_stage_ingress, enabled=rules_disabled, priority=priority_zero, switch_instance=env.switch[1].xmlproxy)
-
taf.testlib.helpers.is_entry_added_to_table(switch_inst, table_name, srch_params, timeout=1, expect_count=1, exist=True)[source]¶ Check if entry with specified fields values is added to table
Parameters: - switch_inst (object) – Switch instance to work with
- table_name (str) – The name of table to perform search in
- srch_params (dict) – Parameters for entry search
- timeout (int) – Time to wait
- expect_count (int) – Number of entries in the table that correspond to search parameters (integer)
- exist (bool) – Decided if entry exists in table or not (boolean)
Returns: True/False
Return type: Examples:
srch_params = {'macAddress': '00:00:00:BB:00:AA', 'portId': 24, 'valid': 'Enabled'} assert helpers.is_entry_added_to_table(env.switch[1], "DcbxRemotes", srch_params, timeout=5) assert helpers.is_entry_added_to_table(env.switch[1], "DcbxRemotes", srch_params, timeout=5, exist=False)
-
taf.testlib.helpers.is_error_in_expected(exception)[source]¶ Check if exception is in list of expected errors.
-
taf.testlib.helpers.is_packet_received(data=None, iface_1=None, iface_2=None, layer_1='Ether', field_1='dst', value_1=None, layer_2='IP', field_2='dst', value_2=None, tg_instance=None, result=True, lag_available=False, f_result=False)[source]¶ Checking if packet is received.
Parameters: - data (str) – Captured data
- iface_1 (str) – Interface
- iface_2 (str) – Interface
- layer_1 (str) – Layer to analyze
- field_1 (str) – Field to look for
- value_1 (can be different) – Comparing value
- layer_2 (str) – Layer to analyze
- field_2 (str) – Field to look for
- value_2 (can be different) – Comparing value
- tg_instance (str) – TG instance
- result (bool) – Expected result: true or false
- lag_available (bool) – is ports are in LAG: true or false
- f_result (bool) – Flag to
Returns: True or raise exception
Examples:
helpers.is_packet_received(data=data, iface_1=sniff_ports[1], iface_2=sniff_ports[0], value_1="ff:ff:ff:ff:ff:ff", layer_2="ARP", field_2="pdst", value_2="10.0.31.2", tg_instance=env.tg[1], lag_available=True)
-
taf.testlib.helpers.is_row_added_to_arp_table(timeout=60, switch_instance=None, net_address=None, if_id=None, result=True)[source]¶ Wait until proper row will be added to ARP table.
-
taf.testlib.helpers.is_row_added_to_l2multicast_table(mac_address=None, port_id=None, vlan_id=1, switch_instance=None, result=True)[source]¶ Check if row with specified parameters added to L2Multicast table.
-
taf.testlib.helpers.is_static_entry_added(mac_address=None, vlan_id=1, port_id=1, switch_instance=None)[source]¶ Check static entry in StaticMAC table
Parameters: Returns: True or False
Return type: Examples:
is_static_entry_added(mac_address=source_mac, port_id=1, vlan_id=vlab_id, switch_instance=env.switch[1].xmlproxy)
-
taf.testlib.helpers.merge_dicts(*dict_args)[source]¶ Merge dictionaries from dict_args.
When same keys present the last dictionary in args list has the highest priority.
Parameters: dict_args (tuple(dict)) – Returns: merged dictionary Return type: dict
-
taf.testlib.helpers.pass_xmlrpc_fault(func)[source]¶ Decorator to create raises functions with predefined xmlrpclib. Fault exception.
-
taf.testlib.helpers.print_sniffed_data_brief(sniffer_data)[source]¶ Print sniffed packets with sniffed count.
Parameters: sniffer_data – sniffed data Examples:
helpers.print_sniffed_data_brief(data)
-
taf.testlib.helpers.process_cli_results(return_list)[source]¶ Returns list of errors in CLI set results.
-
taf.testlib.helpers.raises(expected_exception, fail_message, *args, **kwargs)[source]¶ Assert that a code block/function call raises ExpectedException and raise a failure exception otherwise.
Notes
You can specify a callable by passing a to-be-called lambda or an arbitrary callable with arguments.
Parameters: Returns: Exception info or pytest.fail
Examples:
helpers.raises(ZeroDivisionError, "Expected ZeroDevision didn't raise.", lambda: 1/0) def f(x): return 1/x ... helpers.raises(ZeroDivisionError, "Expected exception didn't raise.", f, 0) helpers.raises(ZeroDivisionError, "Did not raise", f, x=0)
-
taf.testlib.helpers.ri_find_wrapper(switch_instance, vlan=None, ip_address=None, bandwith=100, mtu=1500, vrf=0)[source]¶ Wrapper of “find” function for RouteInterface table.
Notes
This is temporary function.
Parameters: Returns: row
Examples:
_ri_find_wrapper(env.switch[1], vlan=10, ip_address="10.0.10.1/24", mtu=100, bandwith=1500, vrf=0)
-
taf.testlib.helpers.send_receive_packets(packet_definition=None, count=5, src_port=None, dst_port=None, sniff_time=5, sniff_filter='', tg=None, expect_rcv=True)[source]¶ Send and verify receiving of packets.
-
taf.testlib.helpers.set_admin_mode_for_slave_ports(switch_instance=None, admin_mode='Down')[source]¶ Set adminMode for logical ports.
Parameters: Returns: True or raise exception
Examples:
assert helpers.set_admin_mode_for_slave_ports(switch_instance=env.switch[1])
-
taf.testlib.helpers.set_all_ports_admin_disabled(switches, wait_status=True)[source]¶ Sets all ports of all switches provided as an argument to admin state Down.
Parameters: Returns: none
Examples:
set_all_ports_admin_disabled(env.switch)
-
taf.testlib.helpers.set_equal_port_speed_and_cost(ports, switch, table, switch_id=None, cost=2000, speed=10000)[source]¶ Sets equal ports cost and speed for switch ports, and disables slave 40G ports
Parameters: Returns: None
Examples:
helpers.set_equal_port_speed_and_cost(ports, env.switch, ["MSTPPorts", "RSTPPorts", "RSTPPorts"]) helpers.set_equal_port_speed_and_cost(ports, env.switch, "RSTPPorts") helpers.set_equal_port_speed_and_cost(ports, env.switch[1], "RSTPPorts", switch_id=1]
-
taf.testlib.helpers.set_equal_ports_costs(ports, switch, switch_id, table, cost=2000)[source]¶ Sets equal port costs for switch ports.
Parameters: Returns: None
-
taf.testlib.helpers.set_equal_ports_speed(ports, switch, switch_id, speed=10000)[source]¶ Sets equal port costs for switch ports.
Parameters: Returns: None
-
taf.testlib.helpers.set_invalid_value(switch_instance=None, method=None, params=None)[source]¶ Exception handler for negative testcases.
Parameters: - switch_instance (xmlrpclib.ServerProxy object) – Switch instance to work with
- method (str) – XML RPC method to invoke
- params (list of mixed types values) – Arguments to pass to XML RPC method
Returns: None
Examples:
set_invalid_value(switch_instance=env.switch[1].xmlproxy, method="nb.Table.set.field", params=[param1, param2,param3])
-
taf.testlib.helpers.set_lldp_ports_admin_status(switch_instance, port_list, status='Disabled')[source]¶ Set LLDP port admin status on ports.
- Args
- switch_instance(object): the switch instance. port_list(list): the list of ports. status(str): the LLDP port admin status.
Returns: True or False Return type: bool
-
taf.testlib.helpers.set_mstp_mode(switch_instance=None)[source]¶ Obsoleted function. Use set_stp_mode with proper option instead.
-
taf.testlib.helpers.set_ports_admin_enabled(switches, ports, wait_status=True, fail_func=None)[source]¶ Sets provided in arguments ports to admin state Up.
Parameters: Returns: none
Examples:
ports = {('sw1', 'sw2'): {1: 2, 2: 4}} set_ports_admin_enabled(env.switch, ports) set_ports_admin_enabled(env.switch, ports, fail_func=(pytest.softexit, [mesasge, env]))
-
taf.testlib.helpers.set_rstp_mode(switch_instance=None)[source]¶ Obsoleted function. Use set_stp_mode with proper option instead.
-
taf.testlib.helpers.set_stp_mode(switch_instance=None, mode='STP')[source]¶ Set SpanningTree mode to STP|RSTP|MSTP.
Parameters: - switch_instance (xmlrpclib.ServerProxy object) – Switch class instance to work with
- mode (str) – SpanningTree mode
Returns: None
Examples:
set_stp_mode(env.switch[1], "MSTP")
-
taf.testlib.helpers.stat_counters_clear(switch_instances=None, ports=None, counter_name='EtherStatsPkts')[source]¶ Clear all statistic counters on defined port.
Notes
DO NOT USE ON CONTINUOUSLY RUNNING TRAFFIC - FUNCTION IS WAITING THAT COUNTER BECOME 0
Parameters: Returns: None
Examples:
helpers.stat_counters_clear(switch_instances=[env.switch[2], ], ports=ports["sw2", "sw1"].values(), counter_name="EtherStatsPkts256to511Octets")
-
taf.testlib.helpers.stat_counters_read(switch_instances=None, ports=None, counter_name='EtherStatsPkts', previous_results=None, expected_results=None, timeout=30)[source]¶ Read statistic counter on defined port on defined switch.
In addition if previous_results defined then sum of read results compared with sum of previous results. If expected results defined then sum of current results compared with sum of expected results and if match occurred then return results In case expected results is not defined then sum of currently read results == sum of previous results counters read again until timeout
Parameters: - switch_instances (list) – list of switch instances from env
- ports (list) – list of ports where statistic should be read
- counter_name (str) – counter that should be read
- previous_results (list) – list with previous statistics results.
- expected_results (list) – list with expected counters values from ports
- timeout (int) – timeout for re-reading counters in case sum of previous results matchedwith current results, default = 30
Returns: list with read counters from ports
Return type: Examples:
sw2_statistics = helpers.stat_counters_read(switch_instances=[env.switch[2], ], ports=ports["sw2","sw1"].values(), counter_name="EtherStatsPkts256to511Octets", previous_results=previous_sw2_stats, timeout=30)
-
taf.testlib.helpers.update_table_params(switch_inst, table_name, params, find_params=None, row_id=None, validate_updates=True)[source]¶ Configure port parameters in table.
Parameters: - switch_inst (object) – Switch instance to work with
- table_name (str) – The name of table to work with
- params (dict) – Parameters and values that should be configured for port
- find_params (list) – List of parameters to find a row in table
- row_id (int) – Row ID in table
- validate_updates (bool) – Verify if updates were set
Returns: None
Examples:
helpers.update_table_params(env.switch[1], "DcbxPfcPortsAdmin", {"willing": "Enabled", "enabled": "0,0,0,1,0,0,0,0"}, [port_id, ]) helpers.update_table_params(env.switch[1], "DcbxPorts", {"adminStatus": 'Disabled'}, row_id=24)
-
taf.testlib.helpers.validate_frame_against_multiple_layers(packet, src_mac=None, unexpected_layers=None, expected_layers=None)[source]¶ Verify that frame doesn’t contain specific set of Layers and contains correct values for other expected Layers.
Parameters: - packet (pypacker packet) – Packet that should be validated
- src_mac (None or MacAddress) – Expected src mac address of packet
- unexpected_layers (list of strings) – List of layers that should not be present is the frame
- expected_layers (list or dict) – List or Dictionary of layers with expected values that should be present in frame. If the frame contains multiple number of specific layer than value in expected_layer dictionary should be a list (list or dictionary)
Returns: None (Raises error if packet is incorrect)
Examples:
expected_layers = {"DCBXApplicationPriority": {"type": 127L, "length": 5L, "oui": 0x80c2, "subtype": 12L, "reserved": 0}, "DCBXApplicationPriorityTable": [{'priority': 7, 'protocolid': 125, 'sel': 2, 'reserved': 0L}, {'priority': 6, 'protocolid': 555, 'sel': 4, 'reserved': 0L}], "LLDPDUEnd": {"type": 0, "length": 0}} unexpected_layers = ["DCBXCongestionNotification", "DCBXConfiguration"] helpers.validate_frame_against_multiple_layers(packet, dut_mac, unexpected_layers=unexpected_layers, expected_layers=expected_layers)
-
taf.testlib.helpers.verify_port_params_in_table(switch_inst, table_name, params, find_params=None, row_id=None, timeout=0, interval=0.25)[source]¶ Verify that row has correct parameters’ values in table.
Parameters: - switch_inst (object) – Switch instance to work with
- table_name (str) – The name of table to validate the row parameters
- params (dict) – Parameters and values the row in table should match
- find_params (list) – List of parameters to find a row in table
- row_id (int) – Row ID in table
- timeout (int) – Time to wait
- interval (int) – interval in seconds between re-reading the table
Returns: None (Raises error if values are incorrect)
Examples:
helpers.verify_port_params_in_table(env.switch[1], "DcbxPfcPortsLocal", {"willing": "Enabled", "enabled": "0,0,0,0,0,0,0,1"}, [port_id, ], timeout=1) helpers.verify_port_params_in_table(env.switch[1], "DcbxPorts", {"multiplePeers": 'Enabled'}, row_id=24, timeout=1)
-
taf.testlib.helpers.wait_for_route_iface_deleted(switch, iface_id, ip_address, bandwidth, mtu, vrf, timeout)[source]¶ Wait for RouteInterface deleted if it is not after ‘timeout’ seconds elapsed
Parameters: - switch (SwitchX object) – switch for checking RouteInterface being deleted
- iface_id (str) – interface id for checking RouteInterface being deleted
- ip_address (str) – ip address for checking RouteInterface being deleted
- bandwidth (int) – bandwidth for checking RouteInterface being deleted
- mtu (int) – mtu for checking RouteInterface being deleted
- vrf (int) – vrf for checking RouteInterface being deleted
- timeout (int) – seconds for checking RouteInterface being deleted
Returns: None
Examples:
_wait_for_route_iface_deleted(env.switch[1], 3210, '2001:db8:85a3::8a3e:370:7377/96', 1000, 1280, 0, 120)
-
taf.testlib.helpers.wait_for_route_iface_status(switch, iface_id, timeout, status)[source]¶ Wait for RouteInterface changed its oper status to expected value or raise exception if it is not after ‘interval’ seconds elapsed
Parameters: Returns: None
Examples:
_wait_for_route_iface_status(env.switch[1], 2, 120, 'down')
-
taf.testlib.helpers.wait_until_entry_is_expired(expected_timeout=1, switch_instance=None, table_name='L2Multicast')[source]¶ Wait until entry is expired from table
Parameters: Returns: True or raise exception
Examples:
assert self.wait_until_entry_is_expired(timeout=10, switch_instance=env.switch[2])
-
taf.testlib.helpers.wait_until_fdb_entry_is_added(mac_address=None, port_id=1, timeout=5, vlan_id=1, switch_instance=None)[source]¶ Wait some time for adding dynamic entry to FDB.
Parameters: Returns: None
Examples:
wait_time_for_adding_entry_to_fdb(mac_address=source_mac, port_id=port_id_2, timeout=10, vlan_id=vlan_id, switch_instance=env.switch[1])
-
taf.testlib.helpers.wait_until_ops_state(switch_instance=None, port=1, state='Up', timeout=30)[source]¶ Obsoleted function. Use wait_until_value_is_changed with proper option instead.
-
taf.testlib.helpers.wait_until_row_is_added_to_routes_table(timeout=60, switch_instance=None, network_ip='10.0.2.0/24', nexthop=None)[source]¶ Wait until proper row will be added to Route table.
Parameters: Returns: Raise exception
Examples:
helpers._wait_until_row_is_added_to_routes_table(switch_instance=env.switch[1], nexthop="10.0.31.2")
-
taf.testlib.helpers.wait_until_stp_state(switch_instance=None, table='STPPorts', port=1, state='Disabled', timeout=30)[source]¶ Obsoleted function. Use wait_until_value_is_changed with proper option instead.
-
taf.testlib.helpers.wait_until_value_is_changed(switch_instance=None, table_name=None, parameter_name=None, value=None, row_id=1, timeout=30, findlist=None)[source]¶ Wait until value is changed in table
Parameters: - switch_instance (object) – Switch class instance to work with
- table_name (str) – Specific getTable method
- parameter_name (str) – Parameter in table
- value (int) – Checking value
- row_id (int) – Row id in table
- timeout (int) – time to wait until value is changed
- findlist (list) – list of parameters to find a row in the given table
Returns: True or False
Return type: Examples:
wait_until_value_is_changed(env.switch[1], "Ports2LagRemote", "partnerOperSystemPriority", 0, 1) wait_until_value_is_changed(switch_instance=env.switch[1], table_name="Ports2LagRemote", parameter_name="partnerOperSystemPriority", value=0, row_id=1, timeout=30, [1, 1])
-
taf.testlib.helpers.waiting_table_is_loaded(switch_instance, table_name, expected_table_length, watch_interval=1, timeout=120, deviation=None, direction=None, verbose=False)[source]¶ Wait until any table become necessary size, for example it can ba Dynamic ARP table or Route table.
Use deviation parameter if expected_table_length is not strict and can be larger (“+”) then expected on deviation value or smaller (“-“) then expected on deviation value or near (None=+/-) expected on deviation value
Parameters: - switch_instance (object) – switch instance from env
- table_name (str) – table name under test, example: “ARP”
- expected_table_length (int) – value table length should increase to
- watch_interval (int) – interval in seconds between re-reading table from switch instance
- timeout (int) – 120 - timeout in seconds for function execution
- deviation (int) – if expected_table_length is not strict value and some deviation in entries is acceptable
- direction (str) – “+”, “-” or None. In case None then assuming that deviation is bidirectional, both “+” and “-“
- verbose (bool) – can be True or False. In case True then monitoring table content will be displayed in debug log
Returns: True/False
Return type: Examples:
helpers.waiting_table_is_loaded(env.switch[1], "Route", 21, watch_interval = 1, timeout = 120, deviation = 2, direction = "+")
taf.testlib.hub¶
hub.py
Hub-specific functionality
-
class
taf.testlib.hub.VlabHub(config, opts)[source]¶ Bases:
objectClass for simulated hub by Vlab.
-
__init__(config, opts)[source]¶ Initialize VlabHub class.
Parameters: - config (dict) – Configuration information.
- opts (OptionParser) – py.test config.option object which contains all py.test cli options.
Raises: HubException – vlab is not present in configuration
-
class_logger= <logging.LoggerAdapter object>¶
-
taf.testlib.lab¶
lab.py
General lab functionality
-
class
taf.testlib.lab.ConsoleServer(host=None, port=23, username=None, password=None, page_break='--More--', prompt=None, pass_prompt='Password: ', sudo_prompt=None, timeout=10, login_prompt='login: ', page_break_lines=3, exit_cmd=None, quiet=False)[source]¶ Bases:
taf.testlib.lab.GeneralPortServerClass responsible for console connection.
-
static
__new__(cls, config)[source]¶ Get PortServer class related to console type.
Raises: SwitchException – unsupported console type
-
telnet_connect(timeout=45, with_login=None, wait_login=0)[source]¶ Perform telnet connection to the device.
Parameters: Raises: NotImplementedError – not implemented
-
static
-
class
taf.testlib.lab.GeneralPortServer(host=None, port=23, username=None, password=None, page_break='--More--', prompt=None, pass_prompt='Password: ', sudo_prompt=None, timeout=10, login_prompt='login: ', page_break_lines=3, exit_cmd=None, quiet=False)[source]¶ Bases:
taf.testlib.clitelnet.TelnetCMDGeneral functionality for console connection.
-
class_logger= <logging.LoggerAdapter object>¶
-
get_serial(timeout=90, with_login=None, wait_login=0)[source]¶ Connect to switch via serial.
Parameters: Notes
Create(or check) class attribute telnet with active telnet connection to switch and do login.
-
initial_config(config)[source]¶ Performs initial configuration.
Parameters: config (dict) – Configuration information.
-
telnet_connect(timeout=45, with_login=None, wait_login=0)[source]¶ Perform telnet connection to the device.
Parameters: Raises: NotImplementedError – not implemented
-
-
class
taf.testlib.lab.KVMServer(config)[source]¶ Bases:
taf.testlib.lab.ConsoleServerKVM functionality.
-
kvm_connect(output)[source]¶ Perform connection via KVM.
Parameters: output (list[str]) – KVM output Raises: SwitchException – error on connection
-
telnet_connect(timeout=45, with_login=None, wait_login=0)[source]¶ Perform telnet connection to the device.
Parameters: Raises: NotImplementedError – not implemented
-
-
class
taf.testlib.lab.PortServer(config)[source]¶ Bases:
taf.testlib.lab.ConsoleServerPortServer functionality.
-
release_serial()[source]¶ Release serial port on port server.
Raises: SwitchException – error on terminating Notes
This method kill tty on power server.
-
telnet_connect(timeout=45, with_login=None, wait_login=0)[source]¶ Perform telnet connection to the device.
Parameters: Raises: NotImplementedError – not implemented
-
taf.testlib.linux_app_host¶
taf.testlib.linux_host_bash¶
linux_host_bash.py
Linux Host UI wrappers Implementation
-
class
taf.testlib.linux_host_bash.InvalidPortContext(ui, ports)[source]¶ Bases:
objectClass to create a invalid port.
-
class
taf.testlib.linux_host_bash.LinuxHostBash(host)[source]¶ Bases:
testlib.linux_host_interface.LinuxHostInterfaceClass with UiOnpssShell wrappers.
-
BRIDGE_VLAN_COMMAND_STRING= 'bridge vlan {command} vid {vlan} dev {port} self {tagged}'¶
-
INDEX_NAME_RE= re.compile('(?P<index>\\d*):\\s(?P<name>\\w*)[@:]')¶
-
LLDP_ADMINSTATUS= {'Disabled': 'disabled', 'RxOnly': 'rx', 'TxAndRx': 'rxtx', 'TxOnly': 'tx'}¶
-
MAX_EXIT_STATUS= 256¶
-
MULTICALL_THRESHOLD= 100¶
-
RX_TX_RE= re.compile('\\s+[RT]X[^:]*:')¶
-
SSH_NO_EXIT_STATUS= -1¶
-
__init__(host)[source]¶ Initialize UiOnpssShell class.
Parameters: host (SwitchGeneral) – Switch instance
-
_configure_fc_mode(ports=None, tx_mode='normal', traffic_class=255)[source]¶ Determines 802.3x pause frame format used.
Maps priorities to traffic classes.
Parameters:
-
_disable_rx_fc(ports=None)[source]¶ Disables receive of 802.3x pause frames.
Parameters: ports (list[int]) – list of port ids
-
_disable_tx_fc(ports=None)[source]¶ Disables transmit of 802.3x pause frames per port.
Parameters: ports (list[int]) – list of port ids
-
_enable_tx_fc(ports=None)[source]¶ Enables transmit of 802.3x pause frames per port.
Parameters: ports (list[int]) – list of port ids
-
classmethod
_generate_bridge_vlan_commands(command, ports, vlans, tagged='')[source]¶ Generate Bridge VLAN commands.
Parameters: Returns: list of Bridge VLAN commands
Return type:
-
_parse_networkctl(res)[source]¶ Parsing networkctl status output.
Parameters: res (str) – command output Returns: Returns networkctl status in dictionary format Return type: dict
-
_return_user_mode(results)[source]¶ Maintained for abstraction compatibility.
Method that returns to user mode of a switch.
Parameters: results (list) – list of command execution results
-
check_device_state()[source]¶ Attempts to connect to the shell retries number of times.
Raises: SwitchException – device is not ready
-
clear_networkd_settings()[source]¶ Clear networkd settings.
Raises: UiCmdException – when restart fails
-
clear_statistics()[source]¶ Clear Statistics.
Returns: None Examples
env.switch[1].ui.clear_statistics()
-
cli_get_all(commands, timeout=None, split_lines=True, expected_rcs=frozenset({0}), multicall_treshold=100)[source]¶ Sends a list of commands, will return [‘’] if exception.
Parameters: - commands (list[list[str]) – list of commands to be executed
- timeout (int) – command execution timeout
- split_lines (bool) – split command execution results by lines or not
- expected_rcs (int | set | list | frozenset) – expected return code
- multicall_treshold (int) – minimum number of commands to be executed using multicall
Returns: list of outputs for each command
Return type:
-
cli_multicall(commands, timeout=None, expected_rcs=frozenset({0}))[source]¶ Sends a list of commands.
Parameters: Returns: list[tuple(str, tuple(str, str, int))]
Raises: UICmdException – when rc not in expected_rcs
-
cli_send_command(command, timeout=None, expected_rcs=frozenset({0}))[source]¶ Sends a single bash command.
Parameters: Raises: UIException – unexpected return code
Returns: Returns CmdStatus namedtuple of stdout, stderr, return code
Return type:
-
cli_set(commands, timeout=None, split_lines=True, expected_rcs=frozenset({0}), multicall_treshold=100)[source]¶ Sends a list of commands.
Will halt on exception from cli_send_command.
Parameters: - commands (list[list[str]]) – list of commands to be executed
- timeout (int) – command execution timeout
- split_lines (bool) – split command execution results by lines or not
- expected_rcs (int | set | list | frozenset) – expected return code
- multicall_treshold (int) – minimum number of commands to be executed using multicall
Returns: list of execution statuses for each command
Return type: Raises: UICmdException – when rc not in expected_rcs
-
configure_application_priority_rules(ports, app_prio_rules)[source]¶ Configure Application Priority rules.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_application_priority_rules([1, 2], [{"selector": 1, "protocol": 2, "priority":1}, ])
Raises: SwitchException – not implemented
-
configure_arp(garp=None, refresh_period=None, delay=None, secure_mode=None, age_time=None, attemptes=None)[source]¶ Configure ARPConfig table.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_arp(garp='Enabled')
Raises: SwitchException – not implemented
-
configure_dcbx_app(ports, **kwargs)[source]¶ Configure DCBx APP parameter for the ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_app([1, 2])
Raises: SwitchException – not implemented
-
configure_dcbx_cn(ports, **kwargs)[source]¶ Configure DCBx CN parameter for the ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_cn([1, 2], cnpvSupported='Enabled')
Raises: SwitchException – not implemented
-
configure_dcbx_ets(ports, **kwargs)[source]¶ Configure DCBx ETS Conf/Reco parameter for ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_ets([1, 2], confBandwidth=100)
Raises: SwitchException – not implemented
-
configure_dcbx_pfc(ports, **kwargs)[source]¶ Configure DCBx PFC parameter for the ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_pfc([1, 2])
Raises: SwitchException – not implemented
-
configure_global_lldp_parameters(**kwargs)[source]¶ Configure global LLDP parameters.
Parameters: **kwargs (dict) – parameters to be modified: ‘messageFastTx’; ‘messageTxHoldMultiplier’; ‘messageTxInterval’; ‘reinitDelay’; ‘txCreditMax’; ‘txFastInit’; ‘locChassisIdSubtype’. Returns: None Examples:
env.switch[1].ui.configure_global_lldp_parameters(messageTxInterval=5)
Raises: SwitchException – not implemented
-
configure_lldp_ports(ports, **kwargs)[source]¶ Configure LldpPorts records.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_lldp_ports([1, 2], adminStatus='Disabled')
Raises: SwitchException – not implemented
-
configure_ovs_resources(**kwargs)[source]¶ Configure OvsResources table.
Parameters: **kwargs (dict) – parameters to be configured: “controllerRateLimit”; “vlansLimit”; “untaggedVlan”; “rulesLimit”. Returns: None Examples:
env.switch[1].ui.configure_ovs_resources(rulesLimit=2000)
Raises: SwitchException – not implemented
-
configure_tunneling_global(**kwargs)[source]¶ Configure TunnelingGlobalAdmin table.
Parameters: **kwargs (dict) – parameters to be modified: “vnTag”; “vxlanInnerVlanProcessing”; “mode”, “vxlanDestUDPPort”. Returns: None Examples:
env.switch[1].ui.configure_tunneling_global()
Raises: SwitchException – not implemented
-
cpu_port= 0¶
-
create_dhcp_client_lease(file_name='/var/lib/dhcpd/dhcpd.leases')[source]¶ Creates a lease file via SFTP.
Parameters: file_name (str) – File name Returns: None Steps:
-# Create a lease file when DHCP Server is started
-
create_dhcp_config_file(lines, file_name='/etc/dhcp/dhcpd.conf')[source]¶ Writes configuration required to file.
Parameters: Returns: None
Steps:
-# Using sftp client open the config file in write mode -# Write the minimum configuration required by DHCP Server to the file
-
create_dhcp_relay(iface_name='global', server_ip=None, fwd_iface_name=None)[source]¶ Configure DhcpRelayAdmin or DhcpRelayV6Admin table.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_dhcp_relay(iface_name='global', server_ip='10.10.0.2')
Raises: SwitchException – not implemented
-
create_folder(name, options=None, command=None, **kwargs)[source]¶ Create folder.
Parameters: name (str) – folder name
-
create_invalid_ports(ports=None, num=1)[source]¶ Creates port name if port id is passed say [Swop100, if 100 is passed as port id]
Else creates port name with a value incremented to 10 to existing length of ports Ex[sw0p34 , currently sw0p24 is last port]
Parameters: - ports (iter()) – list of port_ids to generate port_names for
- num (int) – generate num new invalid ports
-
create_lag(lag=None, key=0, lag_type='Static', hash_mode='None')[source]¶ Creates a lag group.
Parameters: Raises: Returns: None
-
create_lag_ports(ports, lag, lag_mode='Passive', timeout='Long')[source]¶ Set port to a LAG.
Parameters: Returns: lag
Return type: int | str
Raises: NotExistsError | AccessError –
-
create_match_api_rule(prio_id, handle_id, table_id, match_field_value_mask_list, action, action_value=None)[source]¶ Set a rule into the table using the method defined in maa.py
Parameters: - prio_id (int) – Higher id has a higher priority.
- handle_id (int) – handle for match.
- table_id (int) – the source table id where match to be set.
- match_field_value_mask_list (list[tuple(str, str, str)]) – field with match field, value and mask.
- action (str) – given action for source table
- action_value (int) – action value for a specified action
-
create_match_api_tcam_subtable(source_id, table_id, table_name, max_table_entries, match_field_type_pairs, actions)[source]¶ Create a sub-table of tcam using the method defined in maa.py.
Parameters: - source_id (int) – the source id in the tcam table.
- table_id (int) – a given table id. If switchd running, table id starts from 5 If matchd is running, table id starts from 4
- table_name (str) – a given table name.
- max_table_entries (int) – maximum number of rules can be set.
- match_field_type_pairs (list[tuple(str, str)]) – list of given match field with match type
- actions (list[str]) – list of actions for configurable matches
-
create_ovs_bridge(bridge_name)[source]¶ Create OvsBridges record.
Parameters: bridge_name (str) – OVS bridge name Returns: None Examples:
env.switch[1].ui.create_ovs_bridge('spp0')
Raises: SwitchException – not implemented
-
create_ovs_bridge_controller(bridge_name, controller)[source]¶ Create OvsControllers record.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_ovs_bridge_controller("spp0", "tcp:127.0.0.1:6633")
Raises: SwitchException – not implemented
-
create_ovs_flow_actions(bridge_id, table_id, flow_id, action, param, priority=2000)[source]¶ Add row to OvsFlowActions table.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_ovs_flow_actions(0, 0, 1, 'Output', '25')
Raises: SwitchException – not implemented
-
create_ovs_flow_qualifiers(bridge_id, table_id, flow_id, field, data, priority=2000)[source]¶ Add row to OvsFlowQualifiers table.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_ovs_flow_qualifiers(0, 0, i, 'EthSrc', '00:00:00:00:00:01')
Raises: SwitchException – not implemented
-
create_ovs_flow_rules(bridge_id, table_id, flow_id, priority, enabled)[source]¶ Create OvsFlowRules table.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_ovs_flow_rules(0, 0, 1, 2000, "Enabled")
Raises: SwitchException – not implemented
-
create_ovs_port(port, bridge_name)[source]¶ Create OvsPorts record.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_ovs_port(1, 'spp0')
Raises: SwitchException – not implemented
-
create_static_route(ip, nexthop, network, distance=-1, mode='ip')[source]¶ Create StaticRoute record.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_static_route('20.20.20.0/24', '10.0.5.102', '10.0.5.101/24')
Raises: SwitchException – not implemented
-
create_syslog(syslog_proto, syslog_ip, syslog_port, syslog_localport, syslog_transport, syslog_facility, syslog_severity)[source]¶ Configure Syslog settings.
Parameters: - syslog_proto (str) – syslog host protocol Udp | Tcp
- syslog_ip (str) – syslog host IP address
- syslog_port (int) – syslog host port
- syslog_localport (int) – syslog host local port
- syslog_transport (str) – syslog host transport
- syslog_facility (int) – syslog host facility
- syslog_severity (str) – syslog host severity
Raises: SwitchException – not implemented
-
create_tunnels(tunnel_id=None, destination_ip=None, vrf=0, encap_type=None)[source]¶ Configure TunnelsAdmin table.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_tunnels(tunnel_id=records_count, destination_ip=ip_list, encap_type='VXLAN')
Raises: SwitchException – not implemented
-
create_vlan_ports(ports=None, vlans=None, tagged='Tagged')[source]¶ Creates VLANs on ports using tagged, untagged, or pvid.
Parameters: Raises: ValueError – invalid tagged type
-
delete_arp(ip, network, mode='arp')[source]¶ Delete ARP record.
Parameters: Returns: None
Examples:
env.switch[1].ui.delete_arp('10.0.5.102', '10.0.5.101/24')
Raises: SwitchException – not implemented
-
delete_lag_ports(ports)[source]¶ Deletes ports from a lag.
Parameters: ports (list[int]) – list of ports to be added into LAG Raises: UIException – Returns: None
-
delete_lags(lags=None)[source]¶ Delete lag groups.
Parameters: lags (iter() | str | list[str|int]) – list of lag IDs Raises: NotExistsError – Returns: None
-
delete_match_api_rule(handle_id, table_id)[source]¶ Delete a match from the table using the method defined in maa.py.
Parameters:
-
delete_match_api_tcam_subtable(source_id, table_id=0, table_name=None)[source]¶ Destroy a sub-table of tcam using the method defined in maa.py.
Parameters:
-
delete_ovs_bridge()[source]¶ Delete OVS Bridge.
Returns: None Examples:
env.switch[1].ui.delete_ovs_bridge()
Raises: SwitchException – not implemented
-
delete_ovs_flow_actions(bridge_id, table_id, flow_id, action, priority=2000)[source]¶ Delete row from OvsFlowActions table.
Parameters: Returns: None
Examples:
env.switch[1].ui.delete_ovs_flow_actions(0, 0, 1, 'Output')
Raises: SwitchException – not implemented
-
delete_ovs_flow_qualifiers(bridge_id, table_id, flow_id, field, priority=2000)[source]¶ Delete row from OvsFlowQualifiers table.
Parameters: Returns: None
Examples:
env.switch[1].ui.delete_ovs_flow_qualifiers(bridgeId, tableId, flowId, field)
Raises: SwitchException – not implemented
-
delete_ovs_flow_rules(bridge_id, table_id, flow_id, priority)[source]¶ Delete row from OvsFlowRules table.
Parameters: Returns: None
Examples:
env.switch[1].ui.delete_ovs_flow_rules(bridgeId, tableId, flowId, priority)
Raises: SwitchException – not implemented
-
delete_static_route(network)[source]¶ Delete StaticRoute record.
Parameters: network (str) – RouteInterface network Returns: None Examples:
env.switch[1].ui.delete_static_route('10.0.5.101/24')
Raises: SwitchException – not implemented
-
disable_lldp_on_device_ports(ports=None)[source]¶ Disable Lldp on device ports (if port=None Lldp should be disabled on all ports).
Parameters: ports (list[int]) – list of ports Returns: None Examples:
env.switch[1].ui.disable_lldp_on_device_ports()
-
enable_dcbx_tlv_transmission(ports, dcbx_tlvs='all', mode='Enabled')[source]¶ Enable/Disable the transmission of all Type-Length-Value messages.
Parameters: Returns: None
Examples:
env.switch[1].ui.enable_dcbx_tlv_transmission([1, 2], dcbx_tlvs="all", mode="Enabled")
Raises: SwitchException – not implemented
-
generate_port_name(port)[source]¶ Attempts to translate port in the port_map.
Parameters: port (int | str) – port in the port_map Raises: UIException – Returns: int | str
-
generate_port_name_mapping()[source]¶ Returns the device name (e.g. sw0p1), given a port number and vice versa.
-
get_cpu()[source]¶ Returns cpu utilization from switch.
Returns: cpu utilization from switch Return type: float
-
get_current_date(date_format='+%Y-%m-%d %T')[source]¶ Returns current date on device.
Parameters: date_format (str) – Date format to be returned Returns: Current date on device Return type: str
-
get_dhcp_client_lease_time(ports=None)[source]¶ - Returns the lease time configured for the interfaces, will raise
- exception on any error
Parameters: ports (list[int]) – List of port ids which denotes the switch interfaces Raises: SwitchException – no switch ports found Returns: Dictionary with port id as key and lease time as value Return type: dict
-
get_dhcp_status(ps_name='dhcpd')[source]¶ Gets DHCP status.
Parameters: ps_name (str) – Service name Returns: Values ‘active’|’unknown’ Return type: str Steps:
-# Execute the command to get the status of "dhcpd" service -# Return the result
-
get_icmp_ping_result(ip_addr, ip_version, options='', timeout=None, expected_rcs=frozenset({0}))[source]¶ Return parsed result of ping command.
Parameters: Returns: a dictionary containing various statistics related to a ping command
Return type:
-
get_memory(mem_type='usedMemory')[source]¶ Returns free cached/buffered memory from switch.
Parameters: mem_type (str) – memory type Returns: memory size Return type: float
-
get_port_configuration(port, **kwargs)[source]¶ Returns attribute value (int) for given port.
Parameters: - port (int | str) – port ID
- kwargs (dict) – Possible parameters: “getPortAttr”, “getPortStats”
Returns: port attribute value
Return type: int | str
Raises:
-
get_port_configuration_snapshot(port, stats='attributes', skip_list=frozenset({0}))[source]¶ Get a list of port attributes and their values.
Parameters: Returns: dict
-
get_proc_mem_info()[source]¶ Get proc mem info.
Returns: Returns /proc/meminfo dictionary Return type: dict
-
get_rules_match_api(table_id, handle_id=None)[source]¶ Lists the match api rules of the table using the method defined in maa.py.
Parameters: Returns: list[dict]
-
get_table_arp(mode='arp')[source]¶ Get ARP table.
Parameters: mode (str) – ‘arp’ or ‘ipv6 neigbor’ Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_arp()
Raises: SwitchException – not implemented
-
get_table_basic_statistics(port, stat_name=None)[source]¶ Returns a list of basic statistics found in /sys/class/net/.
Parameters: Returns: Statistics table or specific statistics value
Return type: dict | int
-
get_table_bridge_info(param=None, port=None)[source]¶ Retrieves switch properties organized under ONS 1.x.
Parameters: Raises: KeyError | UIException – port/management port info required
Returns: switch properties
Return type: str | int
-
get_table_dcbx_app_maps(table_type='Admin', port=None)[source]¶ Get DcbxAppMaps* table
Parameters: Returns: table (list of dictionaries)
Return type: Examples:
env.switch[1].ui.get_table_dcbx_app_maps("Admin", 1)
Raises: SwitchException – not implemented
-
get_table_dcbx_pfc(table_type='Local', port=None)[source]¶ Get DcbxRemotes* table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_dcbx_pfc()
Raises: SwitchException – not implemented
-
get_table_dcbx_ports(port=None, param=None)[source]¶ Get DcbxPorts table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_dcbx_ports()
Raises: SwitchException – not implemented
-
get_table_dcbx_remotes(port=None, param=None)[source]¶ Get DcbxRemotes* table.
- Args:
- port(int): port Id (optional) param(str): parameter name (optional)
- Returns:
- list[dict]|int|str: table (list of dictionaries) or value
Examples:
env.switch[1].ui.get_table_dcbx_remotes(1)
Raises: SwitchException – not implemented
-
get_table_dhcp_client_lease(file_name='/var/lib/dhcpd/dhcpd.leases')[source]¶ Gets data from a lease file
Parameters: file_name (str) – File name Returns: dictionary or a particular key’s value based on the options provided Return type: dict Steps:
-# Using sftp client open the config file in read only mode -# Store the configurations in dictionary format -# Return the entire dictionary or a particular key's value based on the options provided
-
get_table_dhcp_config(file_name='/etc/dhcp/dhcpd.conf', options=None)[source]¶ Gets configuration from file.
Parameters: Returns: DHCP configuration
Return type: Steps:
-# Using sftp client open the config file in read only mode -# Store the configurations in dictionary format -# Return the entire dictionary or a particular key's value based on the options provided
-
get_table_dhcp_relay(dhcp_relay_ipv6=False)[source]¶ Return DhcpRelayAdmin or DhcpRelayV6Admin table
Parameters: dhcp_relay_ipv6 (bool) – is IPv6 config defined Returns: None Examples:
env.switch[1].ui.get_table_dhcp_relay(dhcp_relay_ipv6=False)
Raises: SwitchException – not implemented
-
get_table_dhcp_server_ip_list(pool=None)[source]¶ Gets configured range of ip address.
Parameters: pool (str) – “range” Returns: Range of ip address Return type: list Steps:
-# From server configuration file get the range -# Return the list
-
get_table_lags()[source]¶ Get lag group information.
Notes
We can also use networkctl lag command
Returns: list[dict]
-
get_table_link_aggregation()[source]¶ Get LinkAggregation table.
Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_link_aggregation()
-
get_table_lldp(param=None)[source]¶ Get Lldp table.
Parameters: param (str) – parameter name (optional) Returns: table (list of dictionaries) Return type: list[dict]|int|str Examples:
env.switch[1].ui.get_table_lldp()
-
get_table_lldp_ports(port=None, param=None)[source]¶ Get LldpPorts table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_lldp_ports(1)
Raises: SwitchException – not implemented
-
get_table_lldp_ports_stats(port=None, param=None)[source]¶ Get LldpPorts table statistics.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_lldp_ports_stats(1)
Raises: SwitchException – not implemented
-
get_table_lldp_remotes(port=None)[source]¶ Get LldpRemotes table.
Parameters: port (int) – port Id (optional) Returns: table (list of dictionaries) or value Return type: list[dict] Examples:
env.switch[1].ui.get_table_lldp_remotes(1)
Raises: SwitchException – not implemented
-
get_table_match_api(table_id=None)[source]¶ Lists the match api tables using the method defined in maa.py
Parameters: table_id (int) – table ID Returns: list[dict]
-
get_table_ovs_bridges()[source]¶ Get OvsBridges table.
Returns: table (list of dictionaries)) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ovs_bridges()
Raises: SwitchException – not implemented
-
get_table_ovs_controllers()[source]¶ Get OvsControllers table.
Returns: table (list of dictionaries)) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ovs_controllers()
Raises: SwitchException – not implemented
-
get_table_ovs_flow_actions()[source]¶ Get OvsFlowActions table.
Returns: table (list of dictionaries)) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ovs_flow_actions()
Raises: SwitchException – not implemented
-
get_table_ovs_flow_qualifiers()[source]¶ Get OvsFlowQualifiers table.
Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ovs_flow_qualifiers()
Raises: SwitchException – not implemented
-
get_table_ovs_ports()[source]¶ Get OvsPorts table.
Returns: table (list of dictionaries)) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ovs_ports()
Raises: SwitchException – not implemented
-
get_table_ovs_rules()[source]¶ Get OvsFlowRules table.
Returns: table (list of dictionaries)) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ovs_rules()
Raises: SwitchException – not implemented
-
get_table_ports(ports=None, all_params=False, ip_addr=False)[source]¶ Returns the table ports dictionary.
Parameters: Raises: SwitchException – No switch ports found
Returns: ports table
Return type:
-
get_table_remotes_mgmt_addresses(port=None)[source]¶ Get LldpRemotesMgmtAddresses table.
Parameters: port (int) – port Id (optional) Returns: table (list of dictionaries) or value Return type: list[dict] Examples:
env.switch[1].ui.get_table_remotes_mgmt_addresses(1)
-
get_table_static_route(mode='ip')[source]¶ Get StaticRoute table.
- Args:
- mode(str): ‘ip’ or ‘ipv6’
- Returns:
- list[dict]: table (list of dictionaries)
Examples:
env.switch[1].ui.get_table_static_route()
- Raises:
- SwitchException: not implemented
;
-
get_table_statistics(port=None, stat_name=None)[source]¶ Returns port statistics via ethtool -S command.
Parameters: Raises: KeyError – invalid port ID
Returns: Statistics table or specific statistics value
Return type: dict | str
-
get_table_tunnels_admin()[source]¶ Return TunnelsAdmin table.
Returns: table Return type: list[dict] Examples:
env.switch[1].ui.get_table_tunnels_admin()
Raises: SwitchException – not implemented
-
get_table_ufd_config()[source]¶ Get UFDConfig table.
Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ufd_config()
Raises: SwitchException – not implemented
-
get_temperature()[source]¶ Get temperature from Sensors table.
Returns: CPU temperature information (Sensors table) Return type: dict
-
get_ufd_networkctl_status(ports)[source]¶ Checking networkctl status.
Parameters: ports (list[int]) – ports to check networkctl status Returns: - Returns Port Status as Dictionary format for list of Ports with attribute
- as key and attribute value as value If Uplink port -> Returns Values for Keys {‘Carrier Bound By’, ‘Link File’, ‘Driver’, ‘MTU’, ‘Network File’, ‘State’, ‘Address’, ‘Type’} If Downlink port-> Returns Values for Keys {‘Carrier Bound To’, ‘Link File’, ‘Driver’, ‘MTU’, ‘Network File’, ‘State’, ‘Address’, ‘Type’}
Return type: dict
-
icmp_ping_request(ip_addr, ip_version, options='', timeout=None, expected_rcs=frozenset({0}))[source]¶ Execute ping command.
Parameters: Returns: str
-
iputils_version(options='')[source]¶ Verify the versions of ping and ping6 in the iputils package.
Parameters: options (str) – options for the ping command Returns: str
-
is_process_active(process_name)[source]¶ Check if process active or not.
Parameters: process_name (str) – name of process Returns: True or False Return type: bool
-
logs_add_message(level, message)[source]¶ Add message into device logs.
Parameters: Raises: SwitchException – not implemented
-
map_stat_name(generic_name)[source]¶ Returns actual counter name.
Parameters: generic_name (str) – counter Name Returns: str
-
modify_bridge_info(**kwargs)[source]¶ Used for mac aging time, maintained for ONS 1.x compatibility.
Raises: KeyError – cpu port is not defined
-
modify_dhcp_status(ps_name='dhcpd', operation='start')[source]¶ Changes DHCP status.
Parameters: Returns: Result of execution
Return type: Steps:
-# Execute the command to start/stop the "dhcpd" service -# Return the result
-
modify_lags(lag, key=None, lag_type=None, hash_mode=None)[source]¶ Modify LagsAdmin table.
Parameters: Returns: None
Examples
env.switch[1].ui.modify_lags(lag=3800, lag_type=”Static”)
Raises: SwitchException – not implemented
-
modify_ports(ports, expected_rcs=frozenset({0}), **kwargs)[source]¶ Modifies settings on a list of ports.
Parameters: Raises: BoundaryError | AccessError –
Returns: None
-
modify_vlan_ports(ports=None, vlans=None, tagged='tagged')[source]¶ Changes vlan classification. Since no modify method exists in NOS, we need to delete the origin entry and re-add.
Parameters:
-
ntp_update()[source]¶ Update date and time stamp using NTP server.
Parameters: | None (bool) – status of operation (bool) or None if ntp_server not set
-
classmethod
parse_icmp_ping_result(ping_output)[source]¶ Parses the output of ping command.
Parameters: ping_output (str) – output of ping command Returns: dict
-
classmethod
parse_ip_show_stats(input_lines)[source]¶ Returns list of IP statistics.
Parameters: input_lines (list[str]) – command output Returns: list of IP statistics Return type: dict
-
classmethod
parse_row_lag(row)[source]¶ Yield lag group information.
Will convert lagId to int for ONS 1.x compatibility.Parameters: row (dict) – dictionary Returns: dict
-
classmethod
parse_table_ports(ports_table)[source]¶ Returns list of dictionary of port properties.
Parameters: ports_table (list[str]) – port information Returns: port properties Return type: dict
-
parse_table_vlan(vlan_table)[source]¶ Parses the vlan table. This needs to be a loop because previous the table is built based on previous entries.
Parameters: vlan_table (list[str] | iter()) – List of vlan raw output Returns: A dictionary containing the portId, vlanId, and tagged state for each vlan Return type: iter()
-
static
process_table_data(data, table_keys_mapping)[source]¶ Returns dictionary of items, given a table of elements.
Parameters: Returns: dict
-
restart_networkd_service()[source]¶ Restarting systemd-networkd process.
Returns: True if result is none otherwise false Return type: bool Raises: UiCmdException – when restart fails
-
restore_config()[source]¶ Restore device configuration.
Raises: SwitchException – not implemented
-
static
row_with_header(header, data)[source]¶ Returns dictionary per row of values for ‘ip show stats’.
Parameters: Returns: dictionary per row of values for ‘ip show stats’
Return type:
-
save_config()[source]¶ Save device configuration.
Raises: SwitchException – not implemented
-
set_dcb_admin_mode(ports, mode='Enabled')[source]¶ Enable/Disable DCB on ports.
Parameters: Returns: None
Examples:
env.switch[1].ui.set_dcb_admin_mode([1, 2], "Enabled")
Raises: SwitchException – not implemented
-
taf.testlib.linux_host_interface¶
linux_host_interface.py
LinuxHostInteface class
-
class
taf.testlib.linux_host_interface.LinuxHostInterface[source]¶ Bases:
objectAbstract class to store UI wrapper interface methods.
-
clear_statistics()[source]¶ Clear Statistics.
Returns: None Examples
env.switch[1].ui.clear_statistics()
-
clear_table_fdb()[source]¶ Clear Fdb table.
Returns: None Examples:
env.switch[1].ui.clear_table_fdb()
-
configure_application(application, loglevel)[source]¶ Set application loglevel.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_application('L1PortControlApp', 'Debug')
-
configure_application_priority_rules(ports, app_prio_rules)[source]¶ Configure Application Priority rules.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_application_priority_rules([1, 2], [{"selector": 1, "protocol": 2, "priority":1}, ])
-
configure_arp(garp=None, refresh_period=None, delay=None, secure_mode=None, age_time=None, attemptes=None)[source]¶ Configure ARPConfig table.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_arp(garp='Enabled')
-
configure_dcbx_app(ports, **kwargs)[source]¶ Configure DCBx APP parameter for the ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_app([1, 2])
-
configure_dcbx_cn(ports, **kwargs)[source]¶ Configure DCBx CN parameter for the ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_cn([1, 2], cnpvSupported='Enabled')
-
configure_dcbx_ets(ports, **kwargs)[source]¶ Configure DCBx ETS Conf/Reco parameter for ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_ets([1, 2], confBandwidth=100)
-
configure_dcbx_pfc(ports, **kwargs)[source]¶ Configure DCBx PFC parameter for the ports list.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_dcbx_pfc([1, 2])
-
configure_global_lldp_parameters(**kwargs)[source]¶ Configure global LLDP parameters.
Parameters: **kwargs (dict) – parameters to be modified: ‘messageFastTx’; ‘messageTxHoldMultiplier’; ‘messageTxInterval’; ‘reinitDelay’; ‘txCreditMax’; ‘txFastInit’; ‘locChassisIdSubtype’. Returns: None Examples:
env.switch[1].ui.configure_global_lldp_parameters(messageTxInterval=5)
-
configure_lldp_ports(ports, **kwargs)[source]¶ Configure LldpPorts records.
Parameters: Returns: None
Examples:
env.switch[1].ui.configure_lldp_ports([1, 2], adminStatus='Disabled')
-
create_arp(ip, mac, network, mode='arp')[source]¶ Create StaticARP record.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_arp('10.0.5.102', '00:00:22:22:22', '10.0.5.101/24')
-
create_match_api_rule(prio_id, handle_id, table_id, match_field_value_mask_list, action, action_value=None)[source]¶ Set a rule into the table.
Parameters: - prio_id (int) – Higher id has a higher priority.
- handle_id (int) – handle for match.
- table_id (int) – the source table id where match to be set.
- match_field_value_mask_list (list[tuple(str, str, str)]) – field with match field, value and mask.
- action (str) – given action for source table
- action_value (int) – action value
Raises: - UIException – for TypeError - Not enough arguments for format string
- UIException – In case of Command execution Error reported in MatchAPI
-
create_match_api_tcam_subtable(source_id, table_id, table_name, max_table_entries, match_field_type_pairs, actions)[source]¶ Create a sub-table of tcam.
Parameters: - source_id (int) – the source id in the tcam table.
- table_id (int) – a given table id. If switchd running, table id starts from 5 If matchd is running, table id starts from 4
- table_name (str) – a given table name.
- max_table_entries (int) – maximum number of flows can be set.
- match_field_type_pairs (list[tuple(str, str)]) – list of given match field with match type
- actions (list[str]) – list of actions for configurable matches
-
create_static_route(ip, nexthop, network, distance=-1, mode='ip')[source]¶ Create StaticRoute record.
Parameters: Returns: None
Examples:
env.switch[1].ui.create_static_route('20.20.20.0/24', '10.0.5.102', '10.0.5.101/24')
-
create_syslog(syslog_proto, syslog_ip, syslog_port, syslog_localport, syslog_transport, syslog_facility, syslog_severity)[source]¶ Configure Syslog settings.
Parameters: - syslog_proto (str) – syslog host protocol Udp | Tcp
- syslog_ip (str) – syslog host IP address
- syslog_port (int) – syslog host port
- syslog_localport (int) – syslog host local port
- syslog_transport (str) – syslog host transport
- syslog_facility (int) – syslog host facility
- syslog_severity (str) – syslog host severity
-
create_vlan_ports(ports=None, vlans=None, tagged='Tagged')[source]¶ Create new Ports2Vlans records.
Parameters: Returns: None
Examples:
Port 1 will be added into the vlans 3 and 4 as Untagged and port 2 will be added into the vlans 3 and 4 as Untagged env.switch[1].ui.create_vlan_ports([1, 2], [3, 4], 'Untagged')
-
create_vlans(vlans=None)[source]¶ Create new Vlans
Parameters: vlans (list[int]) – list of vlans to be created. Returns: None Examples:
env.switch[1].ui.create_vlans([2, 3])
-
delete_arp(ip, network, mode='arp')[source]¶ Delete ARP record.
Parameters: Returns: None
Examples:
env.switch[1].ui.delete_arp('10.0.5.102', '10.0.5.101/24')
-
delete_match_api_tcam_subtable(source_id, table_id=0, table_name=None)[source]¶ Destroy a sub-table of tcam.
Parameters:
-
delete_static_route(network)[source]¶ Delete StaticRoute record.
Parameters: network (str) – RouteInterface network Returns: None Examples:
env.switch[1].ui.delete_static_route('10.0.5.101/24')
-
delete_vlans(vlans=None)[source]¶ Delete existing Vlans.
Parameters: vlans (list[int]) – list of vlans to be deleted. Returns: None Examples:
env.switch[1].ui.delete_vlans([2, 3])
-
disable_lldp_on_device_ports(ports=None)[source]¶ Disable Lldp on device ports (if port=None Lldp should be disabled on all ports).
Parameters: ports (list[int]) – list of ports Returns: None Examples:
env.switch[1].ui.disable_lldp_on_device_ports()
-
enable_dcbx_tlv_transmission(ports, dcbx_tlvs='all', mode='Enabled')[source]¶ Enable/Disable the transmission of all Type-Length-Value messages.
Parameters: Returns: None
Examples:
env.switch[1].ui.enable_dcbx_tlv_transmission([1, 2], dcbx_tlvs="all", mode="Enabled")
-
get_cpu()[source]¶ Returns cpu utilization from switch.
Returns: cpu utilization from switch Return type: float
-
get_memory(mem_type='usedMemory')[source]¶ Returns free cached/buffered memory from switch.
Parameters: mem_type (str) – memory type Returns: memory size Return type: float
-
get_rules_match_api(table_id=None, handle_id=None)[source]¶ Lists the match api rules of the table.
Parameters: Returns: list[dict]
-
get_table_applications()[source]¶ Get ‘Applications’ table.
Returns: ‘Applications’ table Return type: list[dict]
-
get_table_arp(mode='arp')[source]¶ Get ARP table.
Parameters: mode (str) – ‘arp’ or ‘ipv6 neigbor’ Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_arp()
-
get_table_arp_config()[source]¶ Get ARPConfig table.
Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_arp_config()
-
get_table_dcbx_app_maps(table_type='Admin', port=None)[source]¶ Get DcbxAppMaps* table
Parameters: Returns: table (list of dictionaries)
Return type: Examples:
env.switch[1].ui.get_table_dcbx_app_maps("Admin", 1)
-
get_table_dcbx_pfc(table_type='Local', port=None)[source]¶ Get DcbxRemotes* table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_dcbx_pfc()
-
get_table_dcbx_ports(port=None, param=None)[source]¶ Get DcbxPorts table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_dcbx_ports()
-
get_table_dcbx_remotes(port=None, param=None)[source]¶ Get DcbxRemotes* table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_dcbx_remotes(1)
-
get_table_fdb(table='Fdb')[source]¶ Get Fbd table.
Parameters: table (str) – Fbd record type to be returned (‘Fbd’ or ‘Static’) Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_fdb() env.switch[1].ui.get_table_fdb('Static')
-
get_table_lldp(param=None)[source]¶ Get Lldp table.
Parameters: param (str) – parameter name (optional) Returns: table (list of dictionaries) Return type: list[dict]|int|str Examples:
env.switch[1].ui.get_table_lldp()
-
get_table_lldp_ports(port=None, param=None)[source]¶ Get LldpPorts table.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_lldp_ports(1)
-
get_table_lldp_ports_stats(port=None, param=None)[source]¶ Get LldpPorts table statistics.
Parameters: Returns: table (list of dictionaries) or value
Return type: Examples:
env.switch[1].ui.get_table_lldp_ports_stats(1)
-
get_table_lldp_remotes(port=None)[source]¶ Get LldpRemotes table.
Parameters: port (int) – port Id (optional) Returns: table (list of dictionaries) or value Return type: list[dict] Examples:
env.switch[1].ui.get_table_lldp_remotes(1)
-
get_table_match_api(table_id=None)[source]¶ Lists the match api tables.
Parameters: table_id (int) – table ID Returns: list[dict]
-
get_table_ports(ports=None, all_params=False)[source]¶ Get ‘Ports’ table.
Parameters: Returns: table (list of dictionaries)
Return type: Notes
Return all table or information about particular ports.
Examples:
env.switch[1].ui.get_table_ports() env.switch[1].ui.get_table_ports([1, 2])
-
get_table_ports2vlans()[source]¶ Get ‘Ports2Vlans’ table.
Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_ports2vlans()
-
get_table_remotes_mgmt_addresses(port=None)[source]¶ Get LldpRemotesMgmtAddresses table.
Parameters: port (int) – port Id (optional) Returns: table (list of dictionaries) or value Return type: list[dict] Examples:
env.switch[1].ui.get_table_remotes_mgmt_addresses(1)
-
get_table_static_route(mode='ip')[source]¶ Get StaticRoute table.
Parameters: mode (str) – ‘ip’ or ‘ipv6’ Returns: table (list of dictionaries) Return type: list[dict] Examples:
env.switch[1].ui.get_table_static_route()
-
get_table_statistics(port=None, stat_name=None)[source]¶ Get Statistics table.
Parameters: - port (str|int|None) – port Id to get info about (‘cpu’ or port id) (optional)
- stat_name (str) – name of statistics parameter (optional)
Returns: table (list of dictionaries)
Return type: Examples:
env.switch[1].ui.get_table_statistics() env.switch[1].ui.get_table_statistics(port=1) env.switch[1].ui.get_table_statistics(port='cpu')
-
get_table_vlans()[source]¶ Get ‘Vlans’ table.
Returns: table (list of dictionaries) Return type: list(dict) Examples:
env.switch[1].ui.get_table_vlans()
-
get_temperature()[source]¶ Get temperature from Sensors table.
Returns: CPU temperature information (Sensors table) Return type: dict
-
map_stat_name(generic_name)[source]¶ Get the UI specific stat name for given generic name.
Parameters: generic_name (str) – generic statistic name Returns: UI specific stat name Return type: str
-
modify_ports(ports, **kwargs)[source]¶ Modify records in ‘Ports’ table.
Parameters: - ports (list) – list of port IDs.
- kwargs (dict) – Parameters to be modified. Parameters names should be the same as in XMLRPC nb.Ports.set.* calls: - “pvid” - set pvid value; - “pvpt” - set pvpt value; - “adminMode” - set adminMode value; - “ingressFiltering” - set ingressFiltering value; - “maxFrameSize” - set maxFrameSize value; - “discardMode” - set discardMode value; - “cutThrough” - set cutThrough value; - “flowControl” - set flowControl value; - “speed” - set speed value; - “learnMode” - set learnMode value.
Returns: None
Examples:
env.switch[1].ui.modify_ports([1, 2], adminMode='Down')
-
modify_vlan_ports(ports=None, vlans=None, tagged='Tagged')[source]¶ Modify Ports2Vlans records.
Parameters: Returns: None
Examples:
Port 1 will be modified in the vlans 3 and 4 as Tagged env.switch[1].ui.create_vlan_ports([1, ], [3, 4], 'Tagged')
-
set_all_ports_admin_disabled()[source]¶ Set all ports into admin Down state.
Returns: None Notes
This method is used in helpers.set_all_ports_admin_disabled() for all functional test case.
-
set_dcb_admin_mode(ports, mode='Enabled')[source]¶ Enable/Disable DCB on ports.
Parameters: Returns: None
Examples:
env.switch[1].ui.set_dcb_admin_mode([1, 2], "Enabled")
-
taf.testlib.lldp¶
lldp.py
-
class
taf.testlib.lldp.Tlv[source]¶ Bases:
object-
static
get_chassis_tlv_row(tlv)[source]¶ Parameters: tlv (list) – list or dict of the chassis TLV Returns: remMan style dict Return type: dict
-
static
get_local_cap_tlv_row(tlv)[source]¶ Parameters: tlv (list) – list or dict of the port TLV Returns: row style dict Return type: dict
-
static
get_local_chassis_tlv_row(tlv)[source]¶ Parameters: tlv (list) – list or dict of the chassis TLV Returns: row style dict Return type: dict
-
static
get_local_port_tlv_row(tlv)[source]¶ Parameters: tlv (list) – list or dict of the port TLV Returns: remMan style dict Return type: dict
-
static
get_mgmt_row(tlv)[source]¶ Parameters: tlv (list) – list or dict of the mgmt TLV sub-tlvs Returns: remMan style dict Return type: dict
-
static
get_port_tlv_row(tlv)[source]¶ Parameters: tlv (list) – list or dict of the port TLV Returns: row style dict Return type: dict
-
static
taf.testlib.loggers¶
loggers.py
logging functionality for TAF
-
class
taf.testlib.loggers.ClassLogger(log_level='INFO', log_file=None, log_stream=True, for_exception=False, introspection=True)[source]¶ Bases:
objectClass logger descriptor.
-
__get__(instance, owner)[source]¶ This method is called from class.
Parameters: owner (object) – class instance Returns: logger adaptor Return type: logging.LoggerAdapter Notes
In case using logger for module level use get() method. __get__() won’t be called from module level.
-
__init__(log_level='INFO', log_file=None, log_stream=True, for_exception=False, introspection=True)[source]¶ Initialize instance of ClassLogger.
Parameters:
-
_get_logger(modulename, classname='', caller_func='')[source]¶ Configure and return loggerAdapter instance.
Parameters: Returns: logger adaptor
Return type:
-
-
class
taf.testlib.loggers.LoggerWrapper(logger, level)[source]¶ Bases:
threading.ThreadRead text message from a pipe and redirect them to a logger.
Notes
The object itself is able to supply a file descriptor to be used for writing.
fdWrite ==> fdRead ==> pipeReader
-
__init__(logger, level)[source]¶ Setup the object with a logger and a loglevel and start the thread.
-
-
class
taf.testlib.loggers.NoErrArgumentParser(*args, **kwargs)[source]¶ Bases:
argparse.ArgumentParserArgumentParser class that handle only predefined for an instance options.
Notes
The original ArgumentParser class raises an error if handle unknown option. But py.test have it’s own options and it’s own custom parser and if ArgumentParser find them it raises an error. Using this class allows not to define all possible options in each module that uses ArgumentParser.
taf.testlib.lxc¶
lxc.py
LXC-specific functionality
-
class
taf.testlib.lxc.Lxc(lxc_ip=None, lxc_iface=None, vlab_ip=None, switch_bin_path=None, switch_id=None, switch_port=8081)[source]¶ Bases:
objectBase class to work with Linux containers.
-
__init__(lxc_ip=None, lxc_iface=None, vlab_ip=None, switch_bin_path=None, switch_id=None, switch_port=8081)[source]¶ Init method for container.
Parameters: Returns: None
-
class_logger= <logging.LoggerAdapter object>¶
-
taf.testlib.magnum¶
magnum.py
Support for magnum feature of Openstack
Uses magnum tempest client that was taken form the upstream magnum repository. When using magnum clients, the environment.json file should contain some additional entries:
taf.testlib.multicall¶
multcall.py
Implement simple python command line based RPC
-
taf.testlib.multicall._ssh_cli_test()[source]¶ Private function to test RPC on the command line with ssh.
-
taf.testlib.multicall._test_env_var_size()[source]¶ Private function to verify the maximum command line payload size.
This should be smatter and bisect, but it doesn’t
-
taf.testlib.multicall.bisect_if_too_large(cmd_list, payload_generator, max_size=98304)[source]¶ Check the compressed payload lenght, if it is larger than the max CLI length (usually 127K) we bisect until we get under the limit.
If an individual cmd is greater than the max_size then we will return the original list since we can’t split a single command.
Parameters: Returns: iterator over all generator payloads for all the split cmd_list chunks
Return type: iter(str)
-
taf.testlib.multicall.decode(payload_str)[source]¶ Decode base64 encoded bz2 compress network payload
Parameters: payload_str (str) – base64 encoded bz2 compressed byte stream Returns: original byte-stream Return type: str
-
taf.testlib.multicall.encode(payload)[source]¶ Encode a string for tranmission over the network using base64 encoding of the bz2 compressed string.
We bz2 compress because we can and also to counteract the inefficiency of the base64 encoding.
Parameters: payload (str) – string we want to transmit over the wire Returns: base64 encoded, bz2 compressed string Return type: str
-
taf.testlib.multicall.generate_calls(cmd_list, parallel_limit=None, remote_module_template=<module 'taf.testlib.remote_multicall_template' from '/home/docs/checkouts/readthedocs.org/user_builds/taf-docs/checkouts/master/taf/testlib/remote_multicall_template.py'>)[source]¶ Generate a sequence of simple command line python RPC
Take the supplied python module, get the source and then insert the command list as a base64 encoded bz2 compressed json
We use the double encoding because there doesn’t seem to be a safe way to inject JSON into a python module source. We know the base64, bz2 encoding is safe and compact, so just re-use that.
The template uses a line like this, the raw triple-quoted string will be replaced with the encoded template:
cmd_list = json.loads(bz2.decompress(base64.urlsafe_b64decode(r"""{}""")))
Parameters:
taf.testlib.multiple_tg¶
pytest_onsenv.py
Multiple traffic generator specific functionality
-
class
taf.testlib.multiple_tg.MultipleTG(traffic_generators, config, opts)[source]¶ Bases:
taf.testlib.packet_processor.PacketProcessor,taf.testlib.tg_template.GenericTGClass for general TG instance combined with multiple different TGs.
-
_get_speed_ports()[source]¶ Get ports with speed from TG instances.
Returns: Tuple with list of ports used in real config and list of port/speed values Return type: tuple(list[tuple], list[tuple, int])
-
class_logger= <logging.LoggerAdapter object>¶
-
connect_port(iface)[source]¶ Simulate port link connecting (set it to admin up etc).
Parameters: iface (str) – Interface to connect. Raises: NotImplementedError – not implemented Returns: None or raise and exception.
-
disconnect_port(iface)[source]¶ Simulate port link disconnecting (set it to admin down etc).
Parameters: iface (str) – Interface to disconnect. Raises: NotImplementedError – not implemented Returns: None or raise and exception.
-
get_os_mtu(iface=None)[source]¶ Get MTU value in host OS.
Parameters: iface (str) – Interface for getting MTU in host OS Returns: Original MTU value Return type: int Examples:
env.tg[1].get_os_mtu(iface=ports[('tg1', 'sw1')][1])
-
get_port_id(tg_id, port_id)[source]¶ Return port’s sequence number in list of ports.
Parameters: Raises: ValueError – in case expected port is not in list of ports
Returns: Port sequence number in list of ports starting from 1
Return type:
-
get_tg_port_map(ifaces)[source]¶ Return ports related to specific TG.
Parameters: ifaces (list(tuple)) – list of interfaces in format (tg_id, port_id) Returns: dictionary in format {‘host id’: [port ids]} Return type: dict
-
get_uds_3_frames_count(iface)[source]¶ Read statistics - UDS3 - Capture Trigger (UDS3) - count of non-filtered received packets (valid and invalid).
-
send_stream(stream_id, **kwargs)[source]¶ Sends the stream created by ‘set_stream’ method.
Parameters: stream_id (int) – ID of the stream to be send. Returns: timestamp. Return type: float
-
set_os_mtu(iface=None, mtu=None)[source]¶ Set MTU value in host OS.
Parameters: Returns: Original MTU value
Return type: Examples:
env.tg[1].set_os_mtu(iface=ports[('tg1', 'sw1')][1], mtu=1650)
-
set_stream(*args, **kwargs)[source]¶ Set traffic stream with specified parameters on specified TG port.
Returns: stream id Return type: int Notes
It’s not expected to configure a lot of incrementation options. Different traffic generator could have different limitations for these options.
Examples:
stream_id_1 = tg.set_stream(pack_ip, count=100, iface=iface) stream_id_2 = tg.set_stream(pack_ip, continuous=True, inter=0.1, iface=iface) stream_id_3 = tg.set_stream(pack_ip_udp, count=5, protocol_increment=(3, 5), iface=iface) stream_id_4 = tg.set_stream(pack_ip_udp, count=18, sip_increment=(3, 3), dip_increment=(3, 3), iface=iface, udf_dependancies={'sip_increment': 'dip_increment'})
-
start_sniff(ifaces, **kwargs)[source]¶ Starts sniffing on specified interfaces.
Parameters: Returns: None
Notes
This method introduces additional 1.5 seconds timeout after capture enabling. It’s required by Ixia sniffer to wait until capturing is started.
Examples:
env.tg[1].start_sniff(['eth0', ], filter_layer='IP', src_filter='00:00:00:01:01:01', dst_filter='00:00:00:22:22:22')
-
-
class
taf.testlib.multiple_tg.Port(tg, port)¶ Bases:
tuple-
__getnewargs__()¶ Return self as a plain tuple. Used by copy and pickle.
-
static
__new__(_cls, tg, port)¶ Create new instance of Port(tg, port)
-
__repr__()¶ Return a nicely formatted representation string
-
_asdict()¶ Return a new OrderedDict which maps field names to their values.
-
classmethod
_make(iterable, new=<built-in method __new__ of type object>, len=<built-in function len>)¶ Make a new Port object from a sequence or iterable
-
_replace(**kwds)¶ Return a new Port object replacing specified fields with new values
-
port¶ Alias for field number 1
-
tg¶ Alias for field number 0
-
taf.testlib.netconfcmd¶
netconfcmd.py
Module for working with devices via Netconf over ssh connection
-
class
taf.testlib.netconfcmd.NETCONF(config)[source]¶ Bases:
objectClass for configure device using Netconf.
Parameters: config – Switch configuration dictionary. Examples:
client=NETCONF(env.switch[1].config)
-
__init__(config)[source]¶ Initialize NETCONF class.
Parameters: config (dict) – Switch configuration dictionary.
-
check_session()[source]¶ Check if connection exist.
Returns: True if session connected Return type: bool
-
class_logger= <logging.LoggerAdapter object>¶
-
connect(host, port=830, username=None, password=None, timeout=None)[source]¶ Establish netconf session.
Parameters: Returns: NETCONF session
Return type: ncclient.transport.Session
-
exec_operation(param, filtering=None)[source]¶ Return result of the executed Netconf operation.
Parameters: Returns: Netconf GetReply instance
Notes
This is wrapper for netconf calls.
Examples:
In [3]: netconf.exec_operation("get", ("xpath", "//system/uname")) Out[3]: <?xml version="1.0" encoding="UTF-8"?> <rpc-reply xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0" message-id="urn:uuid:1951ee4a-df07-11e2-9ddb-20cf3095bf10" last-modified="2013-06-27T08:33:02Z" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"> <data> <system xmlns="http://netconfcentral.org/ns/yuma-system"> <uname> <sysname>Linux</sysname> <release>3.2.0-48-generic</release> <version>#74-Ubuntu SMP Thu Jun 6 19:43:26 UTC 2013</version> <machine>x86_64</machine> <nodename><username></nodename> </uname> </system> </data> </rpc-reply>
-
taf.testlib.ovshelpers¶
ovshelpers.py
Helpers functions for OVS test suites
-
taf.testlib.ovshelpers.add_flow_via_controller(qualifiers, action, controller, name=None, dpid=None)[source]¶ Add flow to OVS bridge via Controller.
Parameters: Returns: None
-
taf.testlib.ovshelpers.create_packet_definition(packet_to_send)[source]¶ Create packet definition to send.
Parameters: packet_to_send (dict) – dictionary with specified packet type and fields with values Returns: packet_definition Return type: tuple(dict)
-
taf.testlib.ovshelpers.delete_flow_via_controller(qualifiers, controller, name=None)[source]¶ Delete flow from OVS bridge via Controller.
Parameters: Returns: None
-
taf.testlib.ovshelpers.set_ovs_complex_config_with_controller(ports, switch, sw_id, controller)[source]¶ Set OVS configuration on Switch.
Parameters: Returns: None
-
taf.testlib.ovshelpers.set_ovs_complex_test_preconditions(ports, test_preconditions, switch, controller, dpid=None)[source]¶ Set test preconditions, e.g. flows.
Parameters: Returns: None
-
taf.testlib.ovshelpers.set_ovs_config_with_controller(ports, switch, controller)[source]¶ Set OVS configuration on Switch.
Parameters: - ports (dict) – Links information
- switch (SwitchGeneral) – switch
- controller (OvsControllerGeneralMixin) – Controller
Returns: None
taf.testlib.packet_processor¶
packet_processor.py
Packet processor specific functionality
-
class
taf.testlib.packet_processor.PacketProcessor[source]¶ Bases:
objectThis class contents only one method to build packet from tuple of dictionaries.
-
_build_pypacker_packet(packet_definition, adjust_size=True, required_size=64)[source]¶ Builds pypacker packet based on provided packet definition.
Parameters: - packet_definition (tuple(dict)) – Packet representation (tuple of dictionaries of dictionaries)
- adjust_size (bool) – If set to True packet size will be increased to 64 bytes for Pypacker TG (CRC is included) and to 60 bytes for Ixia TG without CRC. Otherwise Ixia TG will add 4 bytes(CRC), Pypacker TG will not add CRC.
- required_size (int) – Size (in bytes) of the result packet
Returns: pypacker.packet or list of pypacker packets (if fragsize defined)
Return type: pypacker.Packet
Examples:
packet_definition = ({"Ethernet": {"dst": "00:80:C2:00:00:00", "src": "00:00:00:00:00:02"}}, {"Dot1Q": {"vid": 4}}, {"IP": {}}) packet=env.tg[1]._build_pypacker_packet(packet_definition)
-
_build_trex_packet(packet_definition, adjust_size=True, required_size=64)[source]¶ Builds trex packet based on provided packet definition.
Parameters: Returns: trex.packet or list of pypacker packets (if fragsize defined)
Return type: trex.Packet
Examples:
packet_definition = ({"Ether": {"dst": "00:80:C2:00:00:00", "src": "00:00:00:00:00:02"}}, {"Dot1Q": {"vlan": 4}}, {"IP": {}}) packet=env.tg[1]._build_trex_packet(packet_definition)
-
_get_pypacker_layer(layer)[source]¶ Get Pypacker protocol object.
Parameters: layer (str) – Protocol name e.g IP, ICMP.Echo Returns: return Pypacker object Return type: pypacker.Packet Raises: PypackerException – Pypacker library does not support protocol
-
static
_get_pypacker_layer_fields(packet)[source]¶ Get packet fields.
Parameters: packet (pypacker.Packet) – pypacker packet Returns: set of packet fields Return type: set
-
assemble_fragmented_packets(packets)[source]¶ Method for assembling packets from fragments in packet list.
Parameters: packets (list[pypacker.Packet]) – List of fragmened packets Returns: List of assembled packets Return type: list[pypacker.Packet]
-
check_packet_field(packet=None, layer=None, field=None, value=None)[source]¶ Check if specified field is present (for specified layer) and checks if field value matches specified value.
Parameters: Returns: True or False
Return type: Examples:
assert check_packet_field(packet=pypacker_packet, layer="Dot1Q", field="prio", value=4) assert check_packet_field(packet=pypacker_packet, layer="Dot1Q", field="type")
-
class_logger= <logging.LoggerAdapter object>¶
-
flt_patterns= {'ARP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 06', '00 00', '12']}, 'BOOTP': {'cfp': 'pattern1', 'mt1': 'matchUser', 'ptrn1': ['08 00', '00 00', '42']}, 'Dot1Q': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchVlan', 'ptrn1': None}, 'Dot1Q.ARP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 08 06', '00 00 FF FF 00 00', '12']}, 'Dot1Q.ICMP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 08 00 00 00 00 00 00 00 00 00 00 01', '00 00 FF FF 00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'Dot1Q.ICMPv6': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 86 dd 00 00 00 00 00 00 00 00 00 01', '00 00 FF FF 00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'Dot1Q.IP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 08 00', '00 00 FF FF 00 00', '12']}, 'Dot1Q.IPv6': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 86 dd', '00 00 FF FF 00 00', '12']}, 'Dot1Q.TCP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 08 00 00 00 00 00 00 00 00 00 00 06', '00 00 FF FF 00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'Dot1Q.UDP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['81 00 00 00 08 00 00 00 00 00 00 00 00 00 00 11', '00 00 FF FF 00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'ICMP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 00 00 00 00 00 00 00 00 00 00 01', '00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'ICMPv6': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['86 dd 00 00 00 00 00 00 00 00 00 01', '00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'IP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 00', '00 00', '12']}, 'IPv6': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['86 dd', '00 00', '12']}, 'LLDP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['01 80 c2 00 00 0e 00 00 00 00 00 00 88 cc', '00 00 00 00 00 00 FF FF FF FF FF FF 00 00', '0']}, 'PAUSE': {'cfp': 'pattern1', 'mt1': 'matchUser', 'ptrn1': ['88 08', '00 00', '12']}, 'STP': {'cfp': 'pattern1', 'mt1': 'matchUser', 'ptrn1': ['42 42 03 00 00', '00 00 00 00 00', '14']}, 'TCP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 00 00 00 00 00 00 00 00 00 00 06', '00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'UDP': {'cfp': 'pattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 00 00 00 00 00 00 00 00 00 00 11', '00 00 FF FF FF FF FF FF FF FF FF 00', '12']}, 'notARP': {'cfp': 'notPattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 06', '00 00', '12']}, 'notIP': {'cfp': 'notPattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 00', '00 00', '12']}, 'notSTP': {'cfp': 'notPattern1', 'mt1': 'matchUser', 'ptrn1': ['42 42 03 00 00', '00 00 00 00 00', '14']}, 'notUDP': {'cfp': 'notPattern1', 'lfilter': <function PacketProcessor.<lambda>>, 'mt1': 'matchUser', 'ptrn1': ['08 00 00 00 00 00 00 00 00 00 00 11', '00 00 FF FF FF FF FF FF FF FF FF 00', '12']}}¶
-
get_packet_field(packet=None, layer=None, field=None)[source]¶ Returns field value (for specified layer) from specified packet.
Parameters: Raises: PypackerException – unknown layer or field
Returns: value (may be different types, depending on field)
Return type: Examples:
value = get_packet_field(packet=pypacker_packet, layer="Dot1Q", field="vlan")
-
get_packet_layer(packet=None, layer=None, output_format='pypacker')[source]¶ Returns packet layer in pypacker or hex format.
Parameters: Returns: pypacker.Packet or str
Return type: pypacker.Packet, str
Examples:
packet_definition = ({"Ethernet": {"dst": "00:80:C2:00:00:00", "src": "00:00:00:00:00:02"}}, {"Dot1Q": {"vlan": 4}}, {"IP": {}}) pypacker_packet = _build_pypacker_packet(packet_definition) ip_layer_hex = get_packet_layer(packet=pypacker_packet, layer="IP", output_format="hex") assert ip_layer_hex[-8:] == '7f000001'
-
inner_classes= {'Echo', 'Error', 'ParamProb', 'Redirect', 'TimeExceed', 'TooBig', 'Unreach'}¶
-
lldp_lacp_tlvs= {'DCBXApplicationPriority', 'DCBXApplicationPriorityTable', 'DCBXConfiguration', 'DCBXCongestionNotification', 'DCBXPriorityBasedFlowControlConfiguration', 'DCBXRecommendation', 'LACPActorInfoTlv', 'LACPCollectorInfoTlv', 'LACPPartnerInfoTlv', 'LACPReserved', 'LACPTerminatorTlv', 'LLDPChassisId', 'LLDPDUEnd', 'LLDPDot1PortVlanId', 'LLDPGeneric', 'LLDPManagementAddress', 'LLDPOrgSpecGeneric', 'LLDPPortDescription', 'LLDPPortId', 'LLDPSystemCapabilities', 'LLDPSystemDescription', 'LLDPSystemName', 'LLDPTTL'}¶
-
packet_dictionary(packet)[source]¶ Get packet dictionary from pypacker.Packet.
Parameters: packet (pypacker.Packet) – pypacker packet Returns: dictionary created from pypacker.Packet Return type: dict Examples:
p = pypacker.Ethernet(dst="ff:ff:ff:ff:ff:ff", src="90:e6:ba:c3:17:13", type=0x806)/ pypacker.ARP(hwtype=0x1, ptype=0x800, hwlen=6, plen=4, op=1, hwsrc="90:e6:ba:c3:17:13", psrc="172.20.20.175", hwdst="00:00:00:00:00:00", pdst="172.20.20.211")/ pypacker.Padding(load='
-