1#!/usr/bin/env python3
2
3r"""
4This file contains functions useful for printing to stdout from robot programs.
5"""
6
7import re
8import os
9
10import gen_print as gp
11import func_args as fa
12
13from robot.libraries.BuiltIn import BuiltIn
14
15gen_robot_print_debug = int(os.environ.get('GEN_ROBOT_PRINT_DEBUG', '0'))
16
17
18def sprint_vars(*args, **kwargs):
19    r"""
20    Sprint the values of one or more variables to the console.
21
22    This is a robot re-definition of the sprint_vars function in gen_print.py.  Given a list of variable
23    names, this keyword will string print each variable name and value such that each value lines up in the
24    same column as messages printed with sprint_time().
25
26    Description of argument(s):
27    args                            The names of the variables to be printed (e.g. var1 rather than ${var1}).
28    kwargs                          See sprint_varx in gen_print.py for descriptions of all other arguments.
29    """
30
31    if 'fmt' in kwargs:
32        # Find format option names in kwargs['fmt'] and wrap them with "gp." and "()" to make them into
33        # function calls.  For example, verbose would be converted to "gp.verbose()".  This allows the user
34        # to simply specify "fmt=verbose" (vs. fmt=gp.verbose()).
35        # Note "terse" has been explicitly added for backward compatibility.  Once the repo has been purged
36        # of its use, this code can return to its original form.
37        regex = "(" + "|".join(gp.valid_fmts()) + "|terse)"
38        kwargs['fmt'] = \
39            re.sub(regex, "gp.\\1()", kwargs['fmt'])
40    kwargs = fa.args_to_objects(kwargs)
41    buffer = ""
42    for var_name in args:
43        var_value = BuiltIn().get_variable_value("${" + str(var_name) + "}")
44        buffer += gp.sprint_varx(var_name, var_value, **kwargs)
45
46    return buffer
47
48
49def sprint_auto_vars(headers=0):
50    r"""
51    String print all of the Automatic Variables described in the Robot User's Guide using sprint_vars.
52
53    NOTE: Not all automatic variables are guaranteed to exist.
54
55    Description of argument(s):
56    headers                         This indicates that a header and footer should be printed.
57    """
58
59    buffer = ""
60    if int(headers) == 1:
61        buffer += gp.sprint_dashes()
62        buffer += "Automatic Variables:"
63
64    buffer += \
65        sprint_vars(
66            "TEST_NAME", "TEST_TAGS", "TEST_DOCUMENTATION", "TEST_STATUS",
67            "TEST_DOCUMENTATION", "TEST_STATUS", "TEST_MESSAGE",
68            "PREV_TEST_NAME", "PREV_TEST_STATUS", "PREV_TEST_MESSAGE",
69            "SUITE_NAME", "SUITE_SOURCE", "SUITE_DOCUMENTATION",
70            "SUITE_METADATA", "SUITE_STATUS", "SUITE_MESSAGE",
71            "KEYWORD_STATUS", "KEYWORD_MESSAGE", "LOG_LEVEL", "OUTPUT_FILE",
72            "LOG_FILE", "REPORT_FILE", "DEBUG_FILE", "OUTPUT_DIR")
73
74    if int(headers) == 1:
75        buffer += gp.sprint_dashes()
76
77    return buffer
78
79
80def gp_debug_print(buffer):
81    r"""
82    Print the buffer value only if gen_robot_print_debug is set.
83
84    This function is intended for use only by other functions in this module.
85
86    Description of argument(s):
87    buffer                          The string to be printed.
88    """
89
90    if not gen_robot_print_debug:
91        return
92    gp.gp_print(buffer)
93
94
95# In the following section of code, we will dynamically create print versions for several of the sprint
96# functions defined above.  For example, where we have an sprint_vars() function defined above that returns
97# formatted variable print outs in a string, we will create a corresponding rprint_vars() function that will
98# print that string directly to stdout.
99
100# It can be complicated to follow what's being created below.  Here is an example of the rprint_vars()
101# function that will be created:
102
103# def rprint_vars(*args, **kwargs):
104#     gp.gp_print(gp.replace_passwords(sprint_vars(*args, **kwargs)), stream='stdout')
105
106# For sprint_vars (defined above), the following functions will be created:
107
108# rprint_vars                       Robot Print Vars
109# rqprint_vars                      Robot Print Vars if ${quiet} is set to ${0}.
110# rdprint_vars                      Robot Print Vars if ${debug} is set to ${1}.
111# rlprint_vars                      Robot Print Vars to the log instead of to the console.
112
113# Abbreviated names are created for all of the preceding function names:
114# rpvars
115# rqpvars
116# rdpvars
117# rlpvars
118
119# Users are encouraged to only use the abbreviated forms for development but to then ultimately switch to
120# full names.
121# Rprint Vars (instead of Rpvars)
122
123replace_dict = {'output_stream': 'stdout', 'mod_qualifier': 'gp.'}
124
125gp_debug_print("gp.robot_env: " + str(gp.robot_env) + "\n")
126
127# func_names contains a list of all rprint functions which should be created from their sprint counterparts.
128func_names = [
129    'print_vars', 'print_auto_vars'
130]
131
132# stderr_func_names is a list of functions whose output should go to stderr rather than stdout.
133stderr_func_names = []
134
135func_defs = gp.create_print_wrapper_funcs(func_names, stderr_func_names,
136                                          replace_dict, "r")
137gp_debug_print(func_defs)
138exec(func_defs)
139
140# Define an alias.  rpvar is just a special case of rpvars where the args list contains only one element.
141cmd_buf = "rpvar = rpvars"
142gp_debug_print("\n" + cmd_buf + "\n")
143exec(cmd_buf)
144