How to Use IF and ELSE in Robot Framework - python

Create user //Is my test case name
${random_string}= Generate Random String 8 [LOWER]
Set Global Variable ${random_string}
${body}= create dictionary email=${random_string}#mail.com firstName=${random_string} lastName=${random_string} role=ADMIN
${response}= Post On Session mysession /user json=${body} headers=${headers} //This is One Response for POST Method
${getuserresponse}= GET On Session mysession /user headers=${headers} //This is 2nd response for GET method which return all the users
FOR ${i} IN #{getuserresponse.json()}
#Validation
IF ${i['firstName']} == ${random_string} // I want to check weather GET Response contains email that I send from POST request
Log User Created Successfully
ELSE
Log User Not Created Successfully
END
Instead it gives me Error as
Evaluating IF condition failed: Evaluating expression 'ptrmipuy'(this is random_string) failed: NameError: name 'ptrmipuy' is not defined nor importable as module

Your conditions cannot have sequences with two or more spaces, since that's what robot uses to parse a statement. Everywhere you have == it needs to be ==
Also, your expressions either need to quote the string values or you can use the special syntax that converts the robot variables into python variables.
IF "${i['firstName']}" == "${random_string}"
-or-
IF $i['firstName'] == $random_string
This is covered in the documentation for the BuiltIn library, in a section titled Evaluating Expressions

Try below snippet of if else, if it works then copy paste this syntax and replace your variable. Also print your variable before comparing, if it has extra quotes, then you might get that error.
Also you should have only space before and after this symbol "=="
*** Test Cases ***
Testifelse
${Variation}= Set Variable NA
IF "${Variation}" == "NA"
Log if
ELSE
Log else
END

Related

Python Variable For Get Request?

I am trying to move over some API calls I had working over to python from postman, I am having some issues making a variable callable by my next get request. I've found a few things while searching but never found a 100% answer on how to call the environment variable in the get request...is it correct to use the {{TEST}} to call that var. Example below.
Test = Myaccoount
Json_Response_Test = requests.get('https://thisisjustatesttoaccessmyaccount/{{Test}}')
How can I carry over Test into the request?
Your code will almost work as you have it if you use the feature of newer version of Python called "format strings". These are denoted by a f at the beginning of the string. This works like this in such versions of Python:
Test = Myaccoount
Json_Response_Test = requests.get(f'https://thisisjustatesttoaccessmyaccount/{Test}')
as long as Myaccoount is a valid value that can be expanded by Python into the format string.
If you're using an older version of Python, you could do something like this:
Test = Myaccoount
Json_Response_Test = requests.get('https://thisisjustatesttoaccessmyaccount/{}'.format(Test))
BTW, it's not good form to use uppercase first character names for variables. The convention is to use uppercase only for class and type names, and use lowercase for variable and field names.

Automated Actions in odoo 12. Set values with python code

I tried to take text from one field and set it modificated to another throught Execute Python Code.
recs = record.smt
for rec in recs:
details = pythonwhois.get_whois(rec)
if 'No match for' in str(details):
record.smt2='ok'
else:
record.smt2='denied'
Error: forbidden opcode
Please, help!
For the line:
details = pythonwhois.get_whois(rec)
You are using a external library pythonwhois which is not imported, how do you suppose to use that in your execution. As import statement is also not allowed, you can't just import any library.
instead of using dot operator, try to use write function.
if 'No match for' in str(details):
smt2='ok'
else:
smt2='denied'
record.write({'smt2': smt})
Also keep in mind that record is the record on which the action is triggered; may be void

Using a Variable in REQUESTS in Python

I've got an API request to make that involves passing some variables from user input and a config file to a filter expression contained in a dictionary.
The API uses hashes in its structure to wrap stings by default, although I can specify another string wrapping indicator if need be via a separate request. As is, what I need to do is below, basically.
I can't figure out the syntax to get those strings to populate the values between the wrapper # signs. Lots of questions about this, but none addressing the basic syntax without additional functionality, as far as I can tell.
import config
import requests
var1 = **the result of user input, a string**
var2 = **a value from a config file, also a string**
url = (config.api_url)
payload = {
'key':config.api_key,
'Operation':'GetEntities',
'Entity':'my_entity',
'Attributes':'my_attribute1,my_attribute2',
'Filter':'api_var1<eq>#var1# AND api_var2<eq>#var2#'}
response = requests.post(url,payload)
They key point is here:
'Filter':'api_var1<eq>#var1# AND api_var2<eq>#var2#'
So if var1 = '1234' and var2 = '4321' I need it to be the equivalent of:
'Filter':'api_var1<eq>#1234# AND api_var2<eq>#4321#'
As far as I understand you want something like
'Filter':'api_var1<eq>#{0}# AND api_var2<eq>#{1}#'.format(var1, var2)}
or
'Filter':'api_var1<eq>#%s# AND api_var2<eq>#%s#' % (var1, var2)}

Escaping characters for instance query matching in webpy

(The title may be in error here, but I believe that the problem is related to escaping characters)
I'm using webpy to create a VERY simple todo list using peewee with Sqlite to store simple, user submitted todo list items, such as "do my taxes" or "don't forget to interact with people", etc.
What I've noticed is that the DELETE request fails on certain inputs that contain specific symbols. For example, while I can add the following entries to my Sqlite database that contains all the user input, I cannot DELETE them:
what?
test#
test & test
This is a test?
Any other user input with any other symbols I'm able to DELETE with no issues. Here's the webpy error message I get in the browser when I try to DELETE the inputs list above:
<class 'peewee.UserInfoDoesNotExist'> at /del/test
Instance matching query does not exist: SQL: SELECT "t1"."id", "t1"."title" FROM "userinfo" AS t1 WHERE ("t1"."title" = ?) PARAMS: [u'test']
Python /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/peewee.py in get, line 2598
Web POST http://0.0.0.0:7700/del/test
When I view the database file (called todoUserList.db) in sqlitebrowser, I can see that these entries do exist with the symbols, they're all there.
In my main webpy app script, I'm using a regex to search through the db to make a DELETE request, it looks like this:
urls = (
'/', 'Index',
'/del/(.*?)', 'Delete'
)
I've tried variations of the regex, such as '/del/(.*)', but still get the same error, so I don't think that's the problem.
Given the error message above, is webpy not "seeing" certain symbols in the user input because they're not being escaped properly?
Confused as to why it seems to only happen with the select symbols listed above.
Depending on how the URL escaping is functioning it could be an issue in particular with how "?" and "&" are interpreted by the browser (in a typical GET style request & and ? are special character used to separate query string parameters)
Instead of passing those in as part of the URL itself you should pass them in as an escaped querystring. As far as I know, no web server is going to respect wacky values like that as part of a URL. If they are escaped and put in the querystring (or POST body) you'll be fine, though.

How can I use faker in conjunction with Robot Framework?

I've been trying to use the faker library to generate data without having it in my test cases as static data.
I have tried calling fake.md5(raw_output=False) directly from my keyword and also by creating a variable and assigning it this value, but neither has the intended effect. It seems that no matter what I do, the only output I'm getting during my test is fake.md5(raw_output=False).
What am I doing wrong?
Edit: My keyword (it writes to a specific field, this is just a test keyword to make sure I can use faker) -
Write username
${md5}= MD 5
${my data}= log md5: ${md5}
Input Text a11y-username ${my data}
Edit #2 - I realized I had missed out the log keyword, I have updated my code
The problem is in this statement:
${my data}= md5: ${md5}
Robot expects the first cell (or the first cell after a variable name) to be a keyword. So, in this case it thinks md5: ${md5} is a keyword, which it obviously is not. That is why you get the error No keyword with name 'md5: ${md5}' found.
I don't know what you're expecting to do with that line of code. Your value is already in a variable, are you trying to copy it to another variable, or simply print it out?
If your intention was to log the value, use the Log keyword:
Write username
${md5}= MD 5
log md5: ${md5}
If you instead want to copy the value to another variable, you can use the Set Variable keyword:
write username
${md5}= MD 5
${my data}= set variable ${md5}
Input Text a11y-username ${my data}

Categories

Resources