Robotframework - using environment variables in a variable file - robotframework

I would like to construct a variable for RobotFramework within
the variable file but using the Linux environmental variable.
Could you advise on the syntax please ??
My current attempts with this:
vif_vlan = "110"
path_scripts = '%{MY_DIR}/my_path/scripts'
remote_path = "/home/mcast/mgen"
end up in not expanding the env variable %{MY_DIR} ...
Tx

Environment variables are in the environ dictionary of the os module:
import os
path_scripts = os.path.join(os.environ['MY_DIR']', 'my_path', 'scripts')

Your syntax is almost correct - Not for Python, but for Robot Framework.
In your .robot files, you can retrieve environment variables as follows:
** Variables **
| ${MY_PATH_TO_SCRIPTS} | %{MY_DIR}/my_path/scripts

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.

How to %cd to a path containing env variable in jupyter notebook

I am setting a project path to some env variable like PROJECT_HOME by us using os.environ like this:
os.environ['PROJECT_HOME'] = os.getcwd()
so I can use %cd $PROJECT_HOME/abc/xyz in later cell
However, the system return this:
[Errno 2] No such file or directory: '${PROJECT_HOME}/abc/xyz'
Is there a way to use env variable in %cd?
This works for me: %cd {os.environ['PROJECT_HOME']}
I just realized the magic %cd could access python variable. Therefore it could be done like this:
import os
PROJECT_HOME = os.getcwd()
%cd {PROJECT_HOME}
Having said that, the answer by Daniel is the right answer to the question because I asked how to %cd a path containing an environment variable.

Clean3.0 get directory contents

I am using Cleanide for Clean3.0 programming language.
What I am trying to do is to implement a function that receive name of a directory in my system, and return a list of all the files in that directory.
I don't know if the defintion of such function needs to be like File -> [string] or maybe something else, even that directory is a file maybe this is not the developers of Clean meant...
Thank a lot!
This functionality is not available in the StdEnv environment, but there are two libraries that can help with this:
The Directory library contains a module Directory which has a function getDirectoryContents :: !Path !*env -> (!(!DirError, [DirEntry]), !*env) | FileSystem env.
The Platform library contains a module System.Directory which has a function readDirectory :: !FilePath !*w -> (!MaybeOSError [FilePath], !*w).
In both cases the first argument is a path to the directory and the second argument is the *World, which is the typical way of Clean to perform impure operations (see chapter 9 of the language report).
Code examples
With Directory:
import Directory
Start w
# (dir,w) = getDirectoryContents (RelativePath []) w
= dir
With Platform:
import System.Directory
Start w
# (dir,w) = readDirectory "." w
= dir

Variables from variables file

I am trying to use variables from a variables phyton file.
I think I am doing everything as described in the user manual, yet, the variables remain unavailable to me.
This is the variables file
TEST_VAR = 'Michiel'
def get_variables(environment = 'UAT'):
if environment.upper() == 'INT':
ENV = {"NAME": "Bol.com INT",
"BROWSER": "safari",
"URL": "www.bol.com"}
else:
ENV = {"NAME": "Bol.com UAT",
"BROWSER": "firefox",
"URL": "www.bol.com"}
return ENV
I import this like this:
*** Settings ***
Variables Variables.py ${ENVIRONMENT}
Library Selenium2Library
Resource ../PO/MainPage.robot
Resource ../PO/LoginPage.robot
*** Variables ***
${ENVIRONMENT}
*** Keywords ***
Initialize suite
log ${TEST_VAR}
log start testing on ${ENV.NAME}
Start application
open browser ${ENV.URL} ${ENV.BROWSER}
Stop application
close browser
Both files are at the same level in the folder structure.
Yet the variables from the file are not available to me. Not even the normal variable.
Can someone tell me what I am doing wrong here?
Must be something small that I'm forgetting.
Many thanks.
When you use a variable file like this, you don't end up with a variable named ${ENV}. Instead, every key in the dictionary that you return becomes a variable.
From the robot framework user guide (emphasis added):
An alternative approach for getting variables is having a special get_variables function (also camelCase syntax getVariables is possible) in a variable file. If such a function exists, Robot Framework calls it and expects to receive variables as a Python dictionary or a Java Map with variable names as keys and variable values as values.
In this specific case that means that you will end up with the variables ${NAME}, ${BROWSER} and ${URL}.
If you want to set a variable named ${ENV}, you will have to make that part of the returned dictionary
# Variables.py
from robot.utils import DotDict
def get_variables(environment="UAT"):
...
return {
"ENV": DotDict(ENV)
}

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