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