Using Variables in Variable definition - robotframework

I am trying to get variables into variables but it wont work. I searched google and tried a lot of stuff but it did not wor out.
I hope this question ist not "dumb":
What am I doing wrong ?
*** Settings ***
Library SeleniumLibrary
Library OperatingSystem
*** Variable ***
${year} Get Time return year
${month} Get Time return month
${day} Get Time return day
${output} ${CURDIR}\Testing\Tests\SRV\csdb_#{year}-#{month}-#{day}.log
*** Testcases ***
Textfile should have a line saying the service is started
${errors} = Grep File ${output} Test

From the robot framework user's guide:
The most common source for variables are Variable tables in test case
files and resource files. Variable tables are convenient, because they
allow creating variables in the same place as the rest of the test
data, and the needed syntax is very simple. Their main disadvantages
are that values are always strings and they cannot be created
dynamically.
In order to do what you want, you'll need to define the variables in a keyword. For example:
*** Keywords ***
Get Output
${year}= Get Time year
${month}= Get Time month
${day}= Get Time day
${output}= Set variable ${CURDIR}/Testing/Tests/SRV/csdb_${year}-${month}-${day}.log
[Return] ${output}
*** Testcases ***
Textfile should have a line saying the service is started
${output}= Get Output
${errors} = Grep File ${output} Test
Note: you can fetch all three parts of the data in a single call to the keyword, like so:
${year} ${month} ${day}= Get Time year month day
It's a bit hard to read with the space-separated format, but the variable names must each be separated by two or more spaces, but "year month day" should have only one.

Related

Robotframework, How to define a dynamic variable name

I want to Define variable having dynamic name.
For example
${${FILE}{VAR}} Create List // ${FILE} = TEST, ${VAR} = VAR
Then I want to get variable named '${TESTVAR}'.
Here is my Summarized code...
*** Settings ***
Library SeleniumLibrary
Library ExcelLibrary
Library Collections
*** Variables ***
${VAR}= VAR
*** Keywords ***
Open Document And Assign Variable
[Arguments] ${FILE}
Open Excel Document filename=${FILE} doc_id=doc_var
${${FILE}${VAR}} Create List # It doesn't work ..
The previous answer is not really accurate.
This can be achieved exactly with robot's "Variables inside variables" feature like so:
FOR ${idx} IN RANGE 3
${var_name} = Catenate SEPARATOR=_ var ${idx}
Set Suite Variable ${${var_name}} ${idx}
END
you get:
   var_1=1
   var_2=2
   var_3=3
Please note that variables resolution is happening only for keywords arguments (at least for robot version 3.1.2 that I am using), therefore either one of 'Set test variable', 'Set Suite Variable' or 'Set Global Variable' keywords must be used. The following won't work:
FOR ${idx} IN RANGE 3
${var_name} = Catenate SEPARATOR=_ var ${idx}
${${var_name}} = ${idx}
END
results in:
    No keyword with name '${${var_name}} =' found.
For your list case you just need to create a list variable and reassign it to dynamically named variable using the above mentioned keywords
This is currently not possible with Robot Framework. You can use "variables inside variables" to resolve the values of variables (see the documentation on this topic) but not to resolve/set the name of the variable itself.
Though I am afraid that would be confusing anyway. Maybe you can explain your motivations and people can come up with another solution for your problem.

Is it possible to give arguments inside variables in robot framework?

Library REST ${base_url}
*** Keywords ***
Get Requests
GET ${rest_of_the_url}
Output response body
*** Test Cases ***
Do some searching
Get Requests
*** Variables ***
${base_url} https://business.com
${rest_of_the_url} /api/${department}/${person_name}
How can I assign values to ${department} and ${person_name}? I don't want to set those inside Variables because then I cannot write multiple scenarios inside one .robot file. Is it possible to do the assignment as arguments?
i do not think there is a way to pass arguments within the variables,
The below section is straight from the documentation of Robotframework,
where you can create Variables inside variables
Variables inside variables
Variables are allowed also inside variables, and when this syntax is used, variables are resolved from the inside out. For example, if you have a variable ${var${x}}, then ${x} is resolved first. If it has the value name, the final value is then the value of the variable ${varname}. There can be several nested variables, but resolving the outermost fails, if any of them does not exist.
In the example below, Do X gets the value ${JOHN HOME} or ${JANE HOME}, depending on if Get Name returns john or jane. If it returns something else, resolving ${${name} HOME} fails.
*** Variables ***
${JOHN HOME} /home/john
${JANE HOME} /home/jane
*** Test Cases ***
Example
${name} = Get Name
Do X ${${name} HOME}
E.g.,
${person_name}= Set Variable Matt
${department}= Set Variable R&D
# then your code continues
${rest_of_the_url} /api/${department}/${person_name}
Set Variable documentation.
Try to see this using the Set Test / Suite / Global Variable keywords here:
https://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html
Use "Set Suite Variable" keyword then enter the variables $ {person_name} e
$ {department} inside * Variables * then you should read the value inside the test.

Getting object assignment error when attempting to create a dictionary (Robot Framework)

I am attempting to create a dictionary based upon data in an xls spreadsheet. Below is my code. However, when performing the "set to dictionary" (last line of the code snippet below), I'm getting the following error: TypeError: 'unicode' object does not support item assignment. Any ideas as to what I'm missing?
*** Settings ***
Library ExcelLibrary
Library Collections
*** Variables ***
${PageSheetName} = Welcome Page
${WelcomeDict} = Create Dictionary
*** Test Cases ***
Excel Sandbox Test
Get Values from Spreadsheet
#Print out the Dictionary
*** Keywords ***
Get Values from Spreadsheet
# Open the file
Open Excel Current Directory ${Excel_File_Path}DataExtract.xls
# Get the number of rows
${iTotalRows} = Get Row Count ${PageSheetName}
# Loop through each row to get the data. Only need data from Columns A & B
: FOR ${iRowNum} IN RANGE 1 ${iTotalRows}+1
\ ${KeyVal} = Read Cell Data By Name ${PageSheetName} A${iRowNum}
\ ${Value} = Read Cell Data By Name ${PageSheetName} B${iRowNum}
\ Create the Welcome Page Dictionary ${KeyVal} ${Value}
Create the Welcome Page Dictionary
[Arguments] ${key} ${val}
Set To Dictionary ${WelcomeDict} ${key} ${val}
Consider this block of code:
*** Variables ***
${WelcomeDict} = Create Dictionary
It is creating a string variable with the value "Create Dictionary". You cannot call keywords in the *** Variables *** section.
From the robot framework user guide:
Variable tables are convenient, because they allow creating variables in the same place as the rest of the test data, and the needed syntax is very simple. Their main disadvantages are that values are always strings and they cannot be created dynamically.
If you want to initialize a dictionary, use &, and just don't provide any values:
*** Variables ***
&{WelcomeDict}=

Using Get Time in Robot Framework Test cases

How to Use a particular Time For all the test cases in RF.Suppose i have to give time in some field of UI(User Interface).
I have to give that as current time plus 15 mins across all the test cases..How can this be done?
I have declared global variable in Resources.txt and this is being imported across all the test case files
${hr}= Get Time hour NOW + 15min
${min}= Get Time min NOW + 15min
When i run the test case, am getting the following error :
Setting variable '${hr}' failed: Creating a scalar variable with a list value in the Variable table is no longer possible. Create a list variable '#{hr}' and use it as a scalar variable '${hr}' instead.
Setting variable '${min}' failed: Creating a scalar variable with a list value in the Variable table is no longer possible. Create a list variable '#{min}' and use it as a scalar variable '${min}' instead.
But when i use the same in Test1.txt they are working fine..
If the code you are using is in the *** Variables *** section, the format is wrong. Within the variables table you cannot call keywords. What you're doing is creating a list named ${hr} with the literal value of ["Get Time", "hour", "NOW + 15min"]
From the robot framework user's guide:
The most common source for variables are Variable tables in test case
files and resource files. Variable tables are convenient, because they
allow creating variables in the same place as the rest of the test
data, and the needed syntax is very simple. Their main disadvantages
are that values are always strings and they cannot be created
dynamically.
You will need to call the Get Time keyword from within a keyword or test case. Since you want to do this at startup, you can call the keyword in the suite setup.
*** Keywords ***
initialize timestamp variables
${hr}= Get Time hour NOW + 15min
${min}= Get Time min NOW + 15min
set suite variable ${hr}
set suite variable ${min}
*** Settings ***
Suite setup initialize timestamp varaibles
If you do this in multiple suites, it's entirely possible that not all suites will use exactly the same value. An alternative solution would be to set a global variable, and only set it once. Each suite could detect if it's been set yet, and only set it if it hasn't been set.
You could also do this through a python based variable file.
Note: this solution only sets the variable for the current suite. If you do this in a suite initialization file (eg: mysuite/__init__.robot), you will need to use Set Global Variable rather than Set Suite Variable.

Why is the value of a suite variable lost after importing it from a resource file?

From what I read about variable scopes and importing resource files in robotframework doc i would expect this to work (python 2.7, RF 2.8.7):
Test file:
*** Settings ***
Resource VarRes.txt
Suite Setup Preconditions
*** Variables ***
*** Test Cases ***
VarDemo
Log To Console imported [${TODAY}]
*** Keywords ***
Resource file:
*** Settings ***
Library DateTime
*** Variables ***
${TODAY} ${EMPTY} # Initialised during setup, see keyword Preconditions
*** Keywords ***
Format Local Date
[Arguments] ${inc} ${format}
${date} = Get Current Date time_zone=local increment=${inc} day result_format=${format}
[Return] ${date} # formatted date
Preconditions
${TODAY} = Format Local Date 0 %Y-%m-%d
Log To Console inited [${TODAY}]
However the output is:
inited [2015-03-20]
imported []
RF documentation states:
Variables with the test suite scope are available anywhere in the test
suite where they are defined or imported. They can be created in
Variable tables, imported from resource and ....
which I think is done here.
If I add a line to keyword Preconditions like this, it works:
Preconditions
${TODAY} = Format Local Date 0 %Y-%m-%d
Set Suite Variable ${TODAY}
Log To Console inited [${TODAY}]
The reason is that in the first line a local variable is defined, instead of initialising the test suite variable declared in the variable table. A paragraph in RF doc hints to that:
Variables set during the test execution either using return values
from keywords or using Set Test/Suite/Global Variable keywords always
override possible existing variables in the scope where they are set
I think a major drawback of RF is that you cannot define variables dynamically in the variable table. Setting the scope of a variable from within a keyword is something I try to avoid.
For dynamic variables, you might to use a variable file in Python. See the section "Implementing variable file as Python or Java class" in the User Guide.
For example, I use a variables.py with:
if platform.system() in ['Darwin', 'Linux']:
OS_FAMILY = 'unix'
elif platform.system() == 'Windows':
OS_FAMILY = 'windows'
else:
OS_FAMILY = 'unknown'
OS_FAMILY_IS_UNIX = OS_FAMILY == 'unix'
OS_FAMILY_IS_WINDOWS = OS_FAMILY == 'windows'
Then in the Robot Tests I can use the dynamic variables ${OS_FAMILY}, ${OS_FAMILY_IS_UNIX}, and ${OS_FAMILY_IS_WINDOWS} anywhere.
You should be able to do create your ${TODAY} variable.

Resources