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