How to Remove item from List in Robot framework? - python

Currently we want to remove a specific character from a list in Robot framework. Not able to remove it. Currently regex method string data but not for list data.
*** settings ***
Library Collections
*** Test Cases ***
Getting a valid response
[Documentation] Sample List
#{list} = Create List      a    b   c b c c 
Log to console ${list}
In this sample example it creates a list in format ['a','b','c','b','c','c']. Our realtime data is in JSON format which we have converted into a list. However it creates a format list [{'a','b','c'}]. We want to remove curly braces from our list { }. We tried to use Remove item from list it doesn't work currently. Can someone please help?

suppose your json data is in ${json} variable
${json}= Set Variable [{'a','b','c'}]
now remove unwanted data from string
${StringData}= Remove String ${json} { } ' ,
Convert string to List using Convert To List keyword
#{List}= Convert To List ${StringData}
note: if your json data contains string values like [{ "Ford", "BMW", "Fiat" }] then use Split String keyword which returns by default list otherwise it will end up in single characters list for more reference look at this docs

Related

string manipulation in python for reading json object and '' removal

I am trying to construct a role in AWS where I am trying to have list of resources.
Below is an example
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
I am trying to construct a list with
role_arn=[]
for key in shared:
role_arn.append(f"arn:aws:iam::'{shared[key]['account_id']}':role/'{shared[key]['workbench']}'_role")
here is my output:
["arn:aws:iam::'11111':role/'aaaaa'_role", "arn:aws:iam::'22222':role/'bbbbb'_role"]
I want the '' to be removed from the list while appending into the list itself.
desired output:
["arn:aws:iam::11111:role/aaaaa_role", "arn:aws:iam::22222:role/bbbbb_role"]
I am trying my hands on python.
IS there a way to achieve it?
role_arn=[]
for key in shared:
role_arn.append(f"arn:aws:iam::{shared[key]['account_id']}:role/{shared[key]['workbench']}_role")
You don't need those ' unless you want them. You can remove it and the string formatting would still work as expected and get rid of the '.
Most likely your concern was coming from not knowing the Lietral format strings. You don't need to use '' before every variable. {} takes care of it.
This is my take on it
This uses dictionary comprehension to iterate over the shared dictionary instead of a for loop
shared ={
"mts":{
"account_id":"11111",
"workbench":"aaaaa",
"prefix":"rad600-ars-sil,rad600-srr-sil-stage1,rad600-srr-sil-stage2"
},
"tsf":{
"account_id":"22222",
"workbench":"bbbbb",
"prefix":"yyyy"
}
}
role_arn = [f"arn:aws:iam::{data['account_id']}:role/{data['workbench']}_role" for key, data in shared.items()]
print(role_arn)
Which gives the output
['arn:aws:iam::11111:role/aaaaa_role', 'arn:aws:iam::22222:role/bbbbb_role']

Keyword 'Dictionary Should Contain Item' failed by the mismatch of types

Problem:
I'm getting int type from JSON, str type from manually-created dictionary.
Local running passed case, but running on jenkins failed it:
Value of dictionary key 'columns' does not match: 2 (integer) != 2 (string)
Details:
I'm comparing 2 dictionaries, first generated by json parser, second i manually create,
Simple order of steps here are - download ZIP, unarchive, parse JSON as DICT, compare values with DICT
How i parse JSON:
`
def json_loads(json_str):
dict_data = json.loads(json_str)
return dict_data
`
How compare:
`
Compare Widget's Params As Dictionaries
[Arguments] &{param}
<...>
IF 'columns' in &{param}
... Dictionary Should Contain Item ${param.result} columns ${param.columns}
`
.robot code:
&{param2} Create Dictionary title=${name_w2} description=Description ${rndString}
... font_color=f5aef5 back_color=303030 columns=2
Open Test Form Page
${file} Export All Widgets
${path} Normalize Path ${DOWNLOAD_PATH}/results/Archive_export_${rndString}
Extract Files From Zip ${file} ${DOWNLOAD_PATH}/results/Archive_export_${rndString}
Remove File ${file}
Find Widget An Check Params From File JSON file=widget_data.json &{param2}
Keyword:
Find Widget An Check Params From File JSON
[Arguments] &{param}
${file} Get File ${param.file}
#{results} JSON Loads ${file}
${length} Get Length ${results}
${result} Set Variable ${EMPTY}
FOR ${i} IN RANGE 0 ${length}
IF '${results}[${i}][name]'=='${param.title}'
${result} Set Variable ${results}[${i}]
BREAK
END
END
Should Not Be Empty ${result} Can't find widget with title '${param.title}' in JSON
Compare Widget's Params As Dictionaries result=${result} &{param}
JSON:
[{"id":null,"uniqueKey":"KYvKkaaa-oleg-4709-9f1a-a5f3c491634f","name":"AT Imported Widget KYvKkaaa1","description":null,"order":2,"type":"xip","imageId":null,"bgColor":null,"fontColor":null,"widgetUrls":[],"roles":["Order/Service Admin","ACA Admin"],"columns":1,"systemWidget":false},{"id":null,"uniqueKey":"KYvKkaaa-oleg-4f6c-aaac-b0916038ba6c","name":"AT Imported Widget KYvKkaaa2","description":"Description KYvKkaaa","order":3,"type":"xip","imageId":61,"bgColor":"000000","fontColor":"ffffff","widgetUrls":[{"id":null,"uniqueKey":"KYvKkaaa-oleg-4215-a662-93b8cc99e59a","name":"Name1","url":"https://any.net/d/DC4aoLn4z/template_flowone_orders_requests?orgId=1&from=1663856169916&to=1663856169916&theme=dark&viewPanel=16?1"},{"id":null,"uniqueKey":"KYvKkaaa-oleg-4b25-973a-048788c99399","name":"Name2","url":"https://any.net/d/DC4aoLn4z/template_flowone_orders_requests?orgId=1&from=1663856169916&to=1663856169916&theme=dark&viewPanel=16?2"},{"id":null,"uniqueKey":"KYvKkaaa-oleg-4b26-973a-048788c99399","name":"Name3","url":"https://any.net/d/DC4aoLn4z/template_flowone_orders_requests?orgId=1&from=1663856169916&to=1663856169916&theme=dark&viewPanel=16?3"}],"roles":["Order/Service Admin","ACA Admin"],"columns":2,"systemWidget":false}]
Questions:
Why it's happening only on Jenkins?
How to avoid this problem - in my case it should pass, bcs symbol 2 in both ways.
Answer for question 2:
Robot Framework treats variable values as strings so try fixing your dictionary to look like below. Then the variables are integers.
&{param2} Create Dictionary title=${name_w2} description=Description ${rndString}
... font_color=f5aef5 back_color=${303030} columns=${2}

Getting the last value of a key value pair in a json like string

I have a json like string (incomplete json) in which I am trying to retrieve the value of the last key:value pair. The incomplete json like string looks like this:
"BaseCode":null,"BrokerSymbol":null,"CustID":null,"SynthDesc":""}],"#nexturl":"https://someurl.com"}
I am trying to access the value of the #nexturl key and this is the code I've till now:
str1.split(":")[-1]
this gives the output //someurl.com. 2 issues here are that splitting on : removes the https prefix and also doesn't seem like a great approach as if the url contains any more : it will split on that. Is there someway I can get the entire value of #nexturl key?
As requested, assuming your string is as follows:
mystr = '"BaseCode":null,"BrokerSymbol":null,"CustID":null,"SynthDesc":""}],"#nexturl":"https://someurl.com"}'
You can grab the key:value pair containing “#nexturl” by using:
mystr[mystr.index('"#nexturl":'):len(mystr)-1]

Whoosh: How to get search excerpts as a list

From the Whoosh documentation I can get matched search terms with some context with:
results = mysearcher.search(myquery)
for hit in results:
print(hit["title"])
# Assume "content" field is stored
print(hit.highlights("content"))
I'd like to access the "highlights" as a list of separated items (so that I can enumerate them in a html list) but the output of hit.highlights() appears to be of type <class 'str'>, and it's not clear to me that there's a unique delimiter.
Is there a way I can get a list instead of everything concatenated into one string?
You could just convert the highlighted string with the separator "..." to a list.
It's as simple as this:
highlights_list = hit.highlights("content").split("...")

Python: Json.load gives list and can't parse data from it

I have a data.json file, which looks like this:
["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
I am trying to get "Event" from this file using python and miserably failing at this.
with open('data.json', 'r') as json_file:
data = json.load(json_file)
print (data['Event'])
I get the following error:
TypeError: list indices must be integers or slices, not str
And even when I try
print (data[0]['Event'])
then I get this error:
TypeError: string indices must be integers
One more thing:
print(type(data))
gives me "list"
I have searched all over and have not found a solution to this. I would really appreciate your suggestions.
You could use the ast module for this:
import ast
mydata = ["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
data = ast.literal_eval(mydata[0])
data
{'Day': 'Today', 'Event': '1', 'Date': '2019-03-20'}
data['Event']
'1'
Edit
Your original code does load the data into a list structure, but only contains a single string entry inside that list, despite proper json syntax. ast, like json, will parse that string entry into a python data structure, dict.
As it sits, when you try to index that list, it's not the same as calling a key in a dict, hence the slices cannot be str:
alist = [{'a':1, 'b':2, 'c':3}]
alist['a']
TypeError
# need to grab the dict entry from the list
adict = alist[0]
adict['a']
1
You need to convert the elements in data to dict using json module.
Ex:
import json
with open(filename) as infile:
data = json.load(infile)
for d in data:
print(json.loads(d)['Event'])
Or:
data = list(map(json.loads, data))
print(data[0]["Event"])
Output:
1
Your problem is that you are parsing it as a list that consists of a single element that is a string.
["{\"Day\":\"Today\",\"Event\":\"1\", \"Date\":\"2019-03-20\"}"]
See how the entire content of the list is surrounded by " on either side and every other " is preceded by a \? The slash generally means to ignore the special meaning the following character might have, but interpret it as purely a string.
If you have control over the file's contents, the easiest solution would be to adjust it. You will want it to be in a format like this:
[{"Day":"Today", "Event": "1", "Date": "2019-03-20"}]
Edit: As others have suggested, you can also parse it in its current state. Granted, cleaning the data is tedious, but oftentimes worth the effort. Though this may not be one of those cases. I'm leaving this answer up anyway because it may help with explaining why OPs initial attempt did not work, and why he received the error messages he got.

Categories