Set Path Variables in Params in Robot Framework - robotframework

Sorry for my bad English.
The :id in ${uri_set_date} is a path variable parameter, But if I set ${params} it would become a query parameter (with ? in ?id=1&type=new) instead of path variable.
Are there any scripts that I could use to declare the id using path variables parameter?
Thank you
#Variables
${uri_set_date}= /api/v3/date/agent/:id
#Test Cases
Set_Date_Agent_Success
create session set_date_agent_success ${go_fo_gateway}
${headers}= create dictionary Access-Token=${accessToken} Accept=${appversion}
${resp}= POST On Session set_date_agent_success ${uri_set_date} headers=${headers} expected_status=200
#Validation
Should Be Equal As integers ${resp.status_code} 200
Should Be Equal As Strings ${resp.reason} OK
Should Be Equal As Strings ${resp.json()['message']} success

Related

Replacing ${variable} in json file containing 'ID'

I have some issues with how to replace a variable appearing within test data. Let me explain. I am running tests data driven and lets say I have 2 test cases. One does something and returns an 'id'. This 'id' is then used by the 2nd test case to add another entry. Such dependency is currently unavoidable since the 'id' generated is unique each time and TestCase2 depends on it.
Currently when running testcase1 I get back an 'id' which I set as a suite variable. And then testcase2 uses this 'id' variable thus set. This works if the data is hardcoded into the test case. But when the data is abstracted into a test data file I dont know how to replace the '${id} in the test data.
As an example.
TestCase2 reads data from the json file like this.
"{\"query\":\"mutation updatedata($id: Int!, $details: String!) {\\r\\n updatedetaildata(input: { id: $id, details: $details })\\r\\n}\\r\\n\",\"variables\":{\"details\":\"{\\\"total_amount\\\": 523000}\",\"id\":${ID}}}"
What I would like to find out is 1. How to replace the ${id} with suite variable that I set after running TestCase1?
2. In another scenario, if I were to pass ${id} to TestCase2 as an argument how do I get it to replace the ${id} field in the test case data?
Here's my test case :
*** Settings ***
Suite Setup Run Keywords
... Generate Access Token AND
... Generate Random Number AND
... Generate Random Name AND
... Set Testrails Attribute 1 29
Test Teardown Add Test Result
Suite Teardown Send Report to Workchat
Resource ../../../../../Main/resources/importer.robot
*** Test Case ***
Create New Mission - Belanja (Whitelist)
[Documentation] This is new test case
[Tags] api_test
Set Test ID 9449
${payload} Get File api-test/Main/collections/engagement/testing/apitest/createnewtest.json
${payload} Convert to Json ${payload}
### Req body
${response}= GraphQl Request method=POST
... referrer_url=graphql/query
... payload_path=${payload}
... token=${token}
Set Global Variable ${response}
Log To Console ${response}
${payload}= set variable ${response}
${mission_id}= get value from json ${payload} $.data.misPinCreateMission.id
Log To Console ${mission_id}
${id}= set variable ${mission_id}
Set Suite Variable ${ID} ${id}
${template}= Get File api-test/Main/collections/engagement/testing/apitest/editmission.json
${template}= replace variables ${template}
${payload} Convert to Json ${payload}
### Req body
${response}= GraphQl Request method=POST
... referrer_url=graphql/query
... payload_path=${payload}
... token=${token}
Set Global Variable ${response}
Log To Console ${response}
## Assertion
${expected_json} Get File api-test/Main/assertions/expected-json/engagement/testing/apitest/editmission.json
${expected_json}= Convert To Json ${expected_json}
I got this error message :
Create New Mission: This test for Create N... ........{'errors': [{'message': "json body could not be decoded: invalid character 'd' looking for beginning of value"}],
Both answers both be great appreciated. Thank you
Here is one way:
Replace ${ID} in template.json to be a valid number:
"{\"query\":\"mutation updatedata($id: Int!, $details: String!) {\\r\\n updatedetaildata(input: { id: $id, details: $details })\\r\\n}\\r\\n\",\"variables\":{\"details\":\"{\\\"total_amount\\\": 523000}\",\"id\":0}}"
Then you can load and modify it:
*** Settings ***
Library Collections
Library OperatingSystem
*** Test Cases ***
Jsontest
${template}= Get File template.json
${template_d}= Evaluate json.loads(${template}) modules=json
Set To Dictionary ${template_d['variables']} id 123
Log To Console ${template_d}

How to re initiate Variable value in RobotFramework in mid of test case

I have some variables defined in Resource file.
*** Variables ***
${x} SomeValue
# Derived String
${y} SomeString_${x}
After using this in existing test case I modified ${x}. After same am able to use ${x} as modified variable but ${y} remain unchanged. Do we have some way to re initiate ${y} as per new ${x}.
Short answer - not automatically; the value of ${y} will remain as is, regardless that ${x} changed.
The reason is the values in the Variables section are set once, on instantiating the suite. At that time the value of ${y} is set to "SomeString_the-current-value-of-x", and that's it; e.g. it's not some kind of pointer to the present value of ${x}, changing as ${x} changes.
If you want to re-set the value of y, you can do it after you've changed x:
${y}= Set Variable SomeString_${x}

Dictionary as variable in Robot Framework: code runs ok but the IDE yields error

I'm trying to set up a dictionary as a variable (so I can use it as a Resource and access its values from another file) and there is something that is driving me crazy.
Here is the code I have (just for testing purposes):
*** Settings ***
Documentation Suite description
Library Collections
*** Variables ***
&{SOME DICT} key1=value1 key2=value2
*** Test Cases ***
Dict Test # why $ instead of &?
${RANDOM VAR}= Get From Dictionary ${SOME DICT} key1
Log ${RANDOM VAR} WARN
If I run that, I got the expected result ([ WARN ] value1) BUT the IDE (PyCharm) is complaining about that ${SOME DICT} variable is not defined, and the dictionary declaration is not highlighted the same as variable or a list.
If I change that to &{SOME DICT} the IDE won't complain anymore, but the test fails with the following output:
Dict Test | FAIL |
Keyword 'Collections.Get From Dictionary' got positional argument after named arguments.
That is puzzling me to no end: why I have to use a $ instead of a & if it's a dictionary to make it work? Is there something I am doing wrong and it is just running by luck?
Thanks for any advice or guidance you may have!
Have a look into "Get from Dictionary" libdoc,looks like example is showing the same as your working snippet:
Name: Get From Dictionary
Source: Library (Collections)
Arguments: [dictionary, key]
Returns a value from the given ``dictionary`` based on the given ``key``.
If the given ``key`` cannot be found from the ``dictionary``, this
keyword fails.
The given dictionary is never altered by this keyword.
Example:
| ${value} = | Get From Dictionary | ${D3} | b |
=>
| ${value} = 2
Keyword implementation details are as follows:
try:
return dictionary[key]
except KeyError:
raise RuntimeError("Dictionary does not contain key '%s'." % key)
So indeed, Robot sends representation of dict content and not dict name thus value for key can be returned.
This is the same as direct call in python:
a = {u'key1': u'value1', u'key2': u'value2'}
print(a['key1'])
In the end, libdoc for that KW is not straightforward but your PyCharm plugin for Robot does not work properly in this case.
In RED Robot Editor (Eclipse based), proper case does not rise any warnings in editor, wrong-case provides error marker about arguments (better but still not clear what is exactly wrong. Blame minimalistic libdoc info).
ps. I am lead of RED project to be clear.
Simple Example to Use Key Value Variable in robot framework
Set value to dictionary
Get value from dictionary
&{initValues} Create Dictionary key1=value1 key2=value2
Set To Dictionary ${initValues} key1=newvalue1
Set To Dictionary ${initValues} key2=newvalue2
Set To Dictionary ${initValues} key3=newvalue3
${value} Get From Dictionary ${intialValues} key1

How do I set a dictionary key to the variable name and not value using RobotFramework

I need to create a dictionary and set values to them like so.
${dn-name} Set Variable Sweety
${dn-date} Set VAriable 10-02-2017
Now I need to set it to a dictionary so it looks like this :
${My_Dict} = {${dn-name}:Sweety, ${dn-date}:10-02-2017}
I am going to save this into a file later and then extract it later.
How can I do that using Create Dictionary or Set To Dictionary Keyword in Robot Framework.
You can use built-in keyword Create Dictionary to create a dictionary:
*** Test cases ***
Example
${dn-name} Set Variable Sweety
${dn-date} Set Variable 10-02-2017
&{My_Dict} Create dictionary
... dn-name=${dn-name} dn-date=${dn-date}
log dictionary: &{My_Dict}
When I run the above test and examine the log, the final step shows up like this in the log:
12:43:20.505 INFO dictionary: {u'dn-name': u'Sweety', u'dn-date': u'10-02-2017'}

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.

Resources