robot test cases passing formatted variables from python to robot file - python

Can you please help me is there way to pass formatted string from python file to robot file suppose say below is my specific language py file
English.py file has below variable assigned
FILTERED_TEXT_LANG = "{} Selected"
Robot test cases is setting the variable is like below in robot file (user.robot)
${element} = Set Variable xpath=*//div[contains(#id,'org-selection-counter') and contains(text(),'${FILTERED_TEXT_LANG}.format(some_filtered_count)')]
This is required since different language is displaying the some_filtered_count in different way , is there way can make the changes from string formatted not if else conditions

Well, there's a way, but not like this:
${element} = Set Variable xpath=*//div[contains(#id,'org-selection-counter') and contains(text(),'${FILTERED_TEXT_LANG}.format(some_filtered_count)')]
you can't use Python keywords, methods etc. directly in RF. But what you can do is create your custom keyword, either in RF, or in Python, that you latter use in RF and it will fill in a language into the string. Actually, you don't even need to create anything, just reuse what's already available in String library
I can imagine something like this:
${str_with_language}= Replace String ${FILTERED_TEXT_LANG} {} ENG
${element} = Set Variable xpath=*//div[contains(#id,'org-selection-counter') and contains(text(),'${str_with_language}')]

Related

How to call a file name when I want to use a small portion of the name?

I am trying for my code to pull a file when only a portion of the file name changes.
Example: I want to pull the file named JEFF_1234.csv where 1234 is an input from a GUI window.
The reason for the file name to have this structure is I want to have one main database that has multiple files for a specific part number. So if the user inputs a part number of 1234 and that will point to 4 files. JEFF_1234.csv, SAM_1234.csv, FRED_1234.csv and JACK_1234.csv.
What you need is a way to update a template with some dynamic value.
A neat way to do this is to define a template string using curly brackets as place-holders for the content that will be generated at runtime.
jefffile_template = "JEFF_{t}.csv"
Then, once you've assigned a value to the unknown pointer, you can convert your template into an appropriate string:
jeff_filename = jefffile_template.format(t="1234")
Which will store the value of JEFF_1234.csv into the variable jeff_filename for usage later in your program.
There are other similar ways of calling formatting functions, but using this by name style is my preferred method.
...and in case you're wondering, yes, this was still valid in 2.7.

How to use variables value while sourcing a file in Python script

I am a beginner in Python. I want to source the file which has a variable value. I am sourcing the variable value using command line argument option. I want to use this variable as a path parameter to source my file. I am saying it to the variable. Below is the code I am trying.
folder_name = 'abc'
execfile("/a/b/c/folder_name")
and I am expecting it will take the value of folder_name as abc and execute the file as
execfile("/a/b/c/abc")
This can be done either with string concatenation, or with format - the latter being safer/better:
execfile("/a/b/c/" + folder_name)
execfile("/a/b/c/{}".format(folder_name)
For more info on format, see PyFormat
However you might want to consider if execfile is the right approach here! Other data formats can be a better option - e.g. pickle, json or yaml.
You could use .format() whenever you need to insert variable name into string:
execfile("/a/b/c/{0}".format(folder_name))
Note that {0} here corresponds to first argument that you pass to format function.
Similarly, {1}, {2},... corresponds to second, third,.. arguments of format function respectively.
You could also use % operator, but note that it is deprecated as of Python 3.1. 
As you say you are a beginner in Python then you should change your approach and should not use execfile
Instead consider using pickle or json.load to store data
You need something like this:
folder_name = 'abc'
execfile("/a/b/c/{folder_name}".format(folder_name=folder_name))

How to put values from dictionary to variable

I try to get all values from section in my ini file (via configparser) as a variable:
hue310section = dict(parser.items('HUE_310'))
for keys, value in hue310section.items():
pairs = keys + ' = ' + value
print(pairs)
it gave me partnewfilepath = http://some_site:PORT/about, but I don't know how to import this output as an python variable, that I can use partnewfilepath somewhere in my code. Of course one section will have more values than only one, and I want to change all that in variable. I trying to find solution but I think I miss something because my knowledge about python is not enough yet. I think I need to rebuilt my for statement but don't have a clue how to do it in this particular problem.
My config.ini file looks like:
[HUE_310]
partNewFilePath = ${common:domain}/about
otherValues = something
nextvalue = another something
UPDATE:
I think I need to elaborate more about what I want to achieve. In other part of my code I check version of site I want to process. If the site has, let say version 3.10 I want to get all values from section HUE_310 from my ini file, and use them as python variable. Rest of my code use those variable and if the site version will change I can get values from other section from my ini file and get those values to python variable and use them. I assume that some variables will change from version to version and that's why I want to prepare my code to check this. Also it gives me some freedom to modify some variable if site will change.
I hope it is now more clear.
You don't need a new variable or a for loop, you already have hue310section dict.
You can just use
hue310section['partNewFilePath']
which will be equal to
"http://some_site:PORT/about"
Note that after hue310section = dict(parser.items('HUE_310'))
, otherValues and nextvalue keys will also be defined.
from configobj import ConfigObj
parser_data = ConfigObj(config_path)
current = parser_data['HUE_310'].get('partNewFilePath', 'http://www.default.com')
config_path is path to the file
http://www.default.com is the default value in case that particular key is not found.

Python Environment variable within environment variable

I'm trying to set up an environment variable via Python:
os.environ["myRoot"]="/home/myName"
os.environ["subDir"]="$myRoot/subDir"
I expect the subDir environment variable to hold /home/myname/subDir, however it holds the string '$myRoot/subDir'. How do I get this functionality?
(Bigger picture : I'm reading a json file of environment variables and the ones lower down reference the ones higher up)
Use os.environ to fetch the value, and os.path to correctly put slashes in the right places:
os.environ["myRoot"]="/home/myName"
os.environ["subDir"] = os.path.join(os.environ['myRoot'], "subDir")
You can use os.path.expandvars to expand environment variables like so:
>>> import os
>>> print os.path.expandvars("My home directory is $HOME")
My home director is /home/Majaha
>>>
For your example, you might do:
os.environ["myRoot"] = "/home/myName"
os.environ["subDir"] = os.path.expandvars("$myRoot/subDir")
I think #johntellsall's answer is the better for the specific example you gave, however I don't doubt you'll find this useful for your json work.
Edit: I would now recommend using #johntellsall's answer, as os.path.expandvars() is designed explicitly for use with paths, so using it for arbitrary strings may work but is kinda hacky.
def fix_text(txt,data):
'''txt is the string to fix, data is the dictionary with the variable names/values'''
def fixer(m): #takes a regex match
match = m.groups()[0] #since theres only one thats all we worry about
#return a replacement or the variable name if its not in the dictionary
return data.get(match,"$%s"%match)
return re.sub("$([a-zA-Z]+)",fixer,txt) #regular expression to match a "$" followed by 1 or more letters
with open("some.json") as f: #open the json file to read
file_text= f.read()
data = json.loads(file_text) #load it into a json object
#try to ensure you evaluate them in the order you found them
keys = sorted(data.keys() ,key=file_text.index)
#create a new dictionary by mapping our ordered keys above to "fixed" strings that support simple variables
data2= dict(map(lambda k:(k,fixer(data[k],data)),keys)
#sanity check
print data2
[edited to fix a typo that would cause it not to work]

Prompting script to replace placeholders in template file

How can I write a Python script that takes a plain text file littered with placeholders, and then prompts me to replace each placeholder before sending it out to a provided email address?
Essentially, I’m looking to use something similar to 'Replacing text with variables' but I’d like to input the different variables from the terminal like in a simple bash script (rather than defining them in the script). I’d like to begin scripting in Python rather than continuing to write bash scripts; it’s for the best.
Once you have the template with the placeholders, you just need to render it using a dictionary that contains all the variables you need in the template as context. This is the approach used by most of the templating systems.
For example,
value = raw_input('prompt> ')
template = 'This is the {value}'
context = {'value': value}
print template.format(**context)

Categories