pyats.aetest.utils package

pyats.aetest.utils.exit_cli_code(result)

Sets the cli exit code to 0 (no error) or 1 (error) and calls sys.exit. Takes a TestResult object as the result parameter. If the TestResults object’s .value attribute is ‘passed’ or ‘passx’ then the cli exit code is 0.

Return type:

nothing

pyats.aetest.utils.filter_exception(tb)

Filters an exception’s traceback stack and removes AEtest stack frames from it to make it more apparent that the error came from a script. Should be only used on user-script errors, and must not be used when an error is caught from pyats.aetest infra itself.

Any frame with __aetest_infra__ flag set is considered aetest infra stack.

Return type:

return filtered exception stack trace, with aetest stacks removed

pyats.aetest.utils.format_filter_exception(exc_type, exc_value, tb)

format filter_exception

Filters an exception’s traceback stack and removes AEtest stack frames from it to make it more apparent that the error came from a script. Should be only used on user-script errors, and must not be used when an error is caught from pyats.aetest infra itself.

Any frame with __aetest_infra__ flag set is considered aetest infra stack.

calls filter_exception to filter the traceback then formats the exception message

Returns:

  • properly formatted exception message with stack trace, with aetest

  • stacks removed

pyats.aetest.utils.get_defining_class(obj)

Property: defining class

Returns the parent class where the test function/method is defined. If object is a classtype, return itself. For methods, return the class where it was defined in.

Return type:

parent class object or None

pyats.aetest.utils.getfullargspec(func)

Return the list of arguments to function. Removes the first argument (self) if the function is a bound method.

Parameters:

(function) (func) –

Return type:

list of function arguments (without self)

pyats.aetest.utils.getmodule(obj)

wrapper api to inspect.getmodule. attempts to unwrap the object before actually reading its module information.

Parameters:

(object) (obj) –

Return type:

module where object was defined

pyats.aetest.utils.getname(obj)

returns the name of class and/or function object. If name cannot be resolved, return the object itself.

Parameters:

(object) (obj) –

Return type:

object name

pyats.aetest.utils.getsourcefile(obj)

getmodule

wrapper api to inspect.getsourcefile, makes sure that it never errors out when we cannot get the actual source information, returning ‘unknown’ instead.

Parameters:

(object) (obj) –

Return type:

object source file or unknown

pyats.aetest.utils.getsourcelines(obj)

getmodule

wrapper api to inspect.getsourcelines, makes sure that it never errors out when we cannot get the actual source line information, returning 0 instead.

Note

there is a bug with inspect.getsourcelines where if a class was defined more than once in the same file, it returns the line number of the first instance of it regardless of context. (issue 24078)

Parameters:

(object) (obj) –

Return type:

object source line or 0

pyats.aetest.utils.hasarg(func, argument)

Returns boolean on whether a function has a particular argument in its arguments list. Does not consider vararg or varkwargs.

Parameters:
  • (object) (func) –

  • (str) (argument) –

Return type:

True/False

pyats.aetest.utils.start_pdb(pdb_package)

Starts the PDB post-mortem process

Return type:

nothing

pyats.aetest.utils.unwrap(obj)

wrapper function to inspect.unwrap. This is really just a redirect to inspect.unwrap function. However, since it’s a py3 functionality, we are consolidating the api call here so that in py2 we can just return the original function without erroring.

Parameters:

(object) (obj) –

Return type:

unwrapped original function

Submodules

class pyats.aetest.utils.interaction.BaseInteraction(subject, message, section, *, timeout=None, timeout_result=None, no_email=None, from_address=None, to_address=None, email_subject=None, email_body=None)

Bases: object

BaseInteraction class

Base Interaction class to inherit from. Sets up common configuration arguments as well as the execution order when calling interact().

Set up base configuration for any interaction class

Parameters:
  • (str) (message) –

  • (str) – information needed for interaction.

  • (ref) (section) –

Optional Arguments

timeout (float/str): Number of seconds before interaction times out.

“inf” will keep going forever.

timeout_result (str): What to return (or raise) when interaction

times out before retrieving user input. Can be something other than a string depending on implementation of _handle_timeout() Default is “BLOCKED”.

no_email (bool): When True prevents the notification email from

being sent.

from_address (str): Email address to send notification from.

Default is the user login.

to_address (str): Email address to send notification to.

Default is the user login.

email_subject (str/jinja2.Template): Alternate Subject line for

email notification.

email_body (str/jinja2.Template): Alternate Body for email

notification.

interact()

Function that will pause script execution and wait for some input from a user (or timeout) before continuing. Returns a processed result, or raises an exception based on the result.

class pyats.aetest.utils.interaction.WebInteraction(*args, host=None, port=None, web_template=None, **kwargs)

Bases: BaseInteraction

WebInteraction class

Interaction class that hosts a webpage for feedback from the user. The webpage has options for all possible section results, and will raise that signal when selected, terminating exectution in that section.

Initialize the WebInteraction class with an extra argument for port

Parameters:
  • (str) (message) –

  • (str) – information needed for interaction.

  • (ref) (section) –

Optional Arguments

host (str): Host address to bind to. Default is “”, which

accepts any incoming connections.

port (int): Port to host webpage. Default is 0, which requests a

port from the kernel.

web_template (str/jinja2.Template): Jinja template for webpage. Can

extend default_web_template for jinja template inheritence.

timeout (float/str): Number of seconds before interaction times out.

“inf” will keep going forever.

timeout_result (str): What to return (or raise) when interaction

times out before retrieving user input. Can be something other than a string depending on implementation of _handle_timeout() Default is “blocked”.

no_email (bool): When True prevents the notification email from

being sent.

from_address (str): Email address to send notification from.

Default is the user login.

to_address (str): Email address to send notification to.

Default is the user login.

email_subject (str/jinja2.Template): Alternate Subject line for

email notification.

email_body (str/jinja2.Template): Alternate Body for email

notification.

class pyats.aetest.utils.interaction.WebInteractionHTTPHandler(request, client_address, server)

Bases: BaseHTTPRequestHandler

HTTPHandler to serve interation webpage and process contents. Subclass of http.server.BaseHTTPRequestHandler

do_GET()

Override do_GET to handle GET requests. URL path is disregarded since only one page exists to be served. Serves HTML webpage with a submit button to trigger a seperate POST request.

do_POST()

Override do_POST to handle POST requests. URL path is disregarded since only one POST request is expected.

log_message(format_str, *args)

Overrides the default logger for the HTTP Handler so that it logs to the same logger as the rest of the module.

class pyats.aetest.utils.interaction.WebInteractionTCPServer(*args, html_layout, **kwargs)

Bases: TCPServer

TCP server subclass for retrieving webpage content. Other than additional instance variable, behaves exactly like socketserver’s TCPServer.

Built-in __init__

Initializes WebInteractionTCPServer with additional variables.

Parameters:
  • (str (server_address) – for hosting server

  • int) (Tuple containing host address and port) – for hosting server

  • (cls) (RequestHandlerClass) – requests

  • (str) (html_layout) –

class pyats.aetest.utils.pause.PauseOnPhrase(pause_on)

Bases: Handler

Pause on phrase is implemented internally using this class - a subclass of logging.Handler.

In effect, when pause on phrase is enabled, an instance of this class is attached at root logger to handle all incoming message. If a message mets the given conditions, pause will occur.

built-in __init__

instantiates the pause handler with given information.

Parameters:

(str/dict) (pause_on) – of pause_on information

code(frame, section, message, pattern, **kwargs)

on pause, provide code.interact() shell to user

collect(frame, section, message, pattern, **kwargs)

collect data from devices using CLI command or Genie API calls

custom(frame, section, message, pattern, pattern_match, **kwargs)

Custom handler for log messages. Calls the custom method configured by the user and pass the currect test function object and steps to user method.

Parameters:
  • frame (FrameType) – Current frame object from inspect.currentframe (unused)

  • section (str) – Current section from the reporter

  • message (str) – the log message that was matched

  • pattern (str) – the pattern that matched the message (unused)

  • pattern_match (regex object) – the pattern match regex object that matched

email(frame, section, message, pattern, **kwargs)

on pause, sends user notification email and generates pause file

emit(record)

api called by logger while handling LogRecord objects. This is where the log message is validated against the pause criterions, and if found, performs the given action.

static get_user_frame()

Static method that returns the actual frame where the pause occured, eg, ignore all frames related to this file & logging module.

classmethod init(pause_on)

API called by AEtest.run() api that sets and starts this feature.

pdb(frame, section, message, pattern, **kwargs)

on pause, provide pdb.set_trace() debugger to user

static translate_pause_string(string)

api called by AEtest command-line parser. Allows conversion of string command-line inputs into dict types required by the loader class (and adheres to schema)

class pyats.aetest.utils.pause.PausePdb(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=False, readrc=True)

Bases: Pdb

Subclass of pdb.Pdb, intended to do everything except always skips all frames related to this file and python logging module. This allows the debugger/interactive shell to be started always in the frame that called logging (where we are paused on)

Instantiate a line-oriented interpreter framework.

The optional argument ‘completekey’ is the readline name of a completion key; it defaults to the Tab key. If completekey is not None and the readline module is available, command completion is done automatically. The optional arguments stdin and stdout specify alternate input and output file objects; if not specified, sys.stdin and sys.stdout are used.

trace_dispatch(frame, event, arg)

Dispatch a trace function for debugged frames based on the event.

This function is installed as the trace function for debugged frames. Its return value is the new trace function, which is usually itself. The default implementation decides how to dispatch a frame, depending on the type of event (passed in as a string) that is about to be executed.

The event can be one of the following:

line: A new line of code is going to be executed. call: A function is about to be called or another code block

is entered.

return: A function or other code block is about to return. exception: An exception has occurred. c_call: A C function is about to be called. c_return: A C function has returned. c_exception: A C function has raised an exception.

For the Python events, specialized functions (see the dispatch_*() methods) are called. For the C events, no action is taken.

The arg parameter depends on the previous event.

pyats.aetest.utils.pause.check_list(value)

api to be used by pause_file_schema, validating that the input patterns format matches up to the expectation. This is a workaround for schemaengine not supporting nested list/dict types correctly.