1#!/usr/bin/env python 2 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 12def my_import_resource(path): 13 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. 69 for key, value in post_var_dict.items(): 70 if key in pre_var_dict: 71 if value != pre_var_dict[key]: 72 global_var_name = re.sub("[@&]", "$", key) 73 BuiltIn().set_global_variable(global_var_name, 74 pre_var_dict[key]) 75