blob: bd61a8723a707c3ec37be3e598c87087ceb391d9 [file] [log] [blame]
George Keishinge7e91712021-09-03 11:28:44 -05001#!/usr/bin/env python3
Michael Walshbdb39652017-01-27 15:44:49 -06002
3r"""
4This module contains utility and wrapper functions useful to robot python
5programs.
6"""
7
8import re
9from robot.libraries.BuiltIn import BuiltIn
10
11
Michael Walshbdb39652017-01-27 15:44:49 -060012def my_import_resource(path):
Michael Walshbdb39652017-01-27 15:44:49 -060013 r"""
14 Import the resource file specified in path.
15
16 Description of arguments:
17 path The path to your resource file.
18
19 This function is a wrapper for BuiltIn().import_resource() and provides
20 the following benefits:
21 - When you invoke a robot program from a command line, you may specify
22 program parameters as follows:
23
24 -v --variable name:values
25
26 For example:
27
28 robot -v parm_x:1 file_x.robot
29
30 When you do "Resource utils_x.robot" in a .robot program, it processes
31 "utils_x.robot" BEFORE your command line parms are processed, as one
32 might expect. On the other hand, if one of your python library files
33 were to run BuiltIn().import_resource("utils_x.robot"), it will process
34 "utils_x.robot" AFTER your program parms are processed. Let's suppose
35 that utils_x.robot contains the following:
36
37 *** Variables ***
38 ${parm_x} ${0}
39
40 If your program is invoked like this:
41
42 robot -v parm_x:3 file_x.robot
43
44 And if your program has a python library file that invokes
45 BuiltIn().import_resource("utils_x.robot"), then parm_x will get set to
46 ${0}. In other words, instead of utils_x.robot serving to set a default
47 value for parm_x, it actually causes the user's specification of
48 "-v parm_x:3" to be overwritten.
49
50 This function will remedy that problem by keeping your -v parms intact.
51
52 - The problems with -v parms mentioned above are also found with variables
53 from your file_x.robot "** Variables **" section. Namely, they may get
54 overwritten when import_resource() is used. This function will likewise
55 remedy that problem.
56
57 """
58
59 # Retrieve the values of all current variables into a dictionary.
60 pre_var_dict = BuiltIn().get_variables()
61 # Do the import.
62 BuiltIn().import_resource(path)
63 # Once again, retrieve the values of all current variables into a
64 # dictionary.
65 post_var_dict = BuiltIn().get_variables()
66
67 # If any variable values were changed due to the prior import, set them
68 # back to their original values.
George Keishing36efbc02018-12-12 10:18:23 -060069 for key, value in post_var_dict.items():
Michael Walshbdb39652017-01-27 15:44:49 -060070 if key in pre_var_dict:
71 if value != pre_var_dict[key]:
72 global_var_name = re.sub("[@&]", "$", key)
George Keishinge635ddc2022-12-08 07:38:02 -060073 BuiltIn().set_global_variable(global_var_name,
74 pre_var_dict[key])