How to check if the dictionary is empty or not in robot framework using python - python-2.7

I tried to check the given dictionary is empty or not in robot framework but it is giving an error saying syntax error. Here is the following example of how I compared it:
Run Keyword If '${source_list_data}'=='[]' FAIL and the error which i got is:
Evaluating expression ''[{'data':'value'}]'=='[]'' failed: SyntaxError: invalid syntax (, line 1)

Your syntax works for me. Strange it does not work for you.
Here is another way to achieve it using Get Length:
*** Settings ***
Library Collections
*** Test Cases ***
dict_empty
${source_list_data} = create dictionary
${length} = Get Length ${source_list_data}
Run Keyword If ${length} == 0 log to console Empty Dict

To check if dictionary is empty in robot framework, automatic dictionary variable "&{EMPTY}" can be used:
Run Keyword if ${dict} == &{EMPTY} 'Some Action Keyword'

Related

unhelpful Pyomo error ERROR: Initializer for Set objective_index returned non-iterable object of type SumExpression

Here is the offending code, abstracted from the source to protect your sanity . . .
def objective_rule(model):
return sum(model.ccv[c] * model.SELECT[c] for c in model.c)
nc=40
model.c = Set(initialize=[c for c in range(1, nc+1)], ordered=True)
model.SELECT=Var(model.c, initialize=0, domain=NonNegativeReals)
model.ccv= Param(model.c, initialize=ccd, domain=NonNegativeReals)
ccd is a dictionary with the same integer keys as as model.c.
Here are the error allegations made by pyomo.
ERROR: Initializer for Set objective_index returned non-iterable object of
type SumExpression.
ERROR: Constructing component 'objective_index' from data=None failed:
TypeError: 'SumExpression' object is not iterable
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [44], line 1
----> 1 model.objective = Objective(objective_rule, sense = minimize)
3 print("Done setting up the problem.")
...
TypeError: 'SumExpression' object is not iterable
You'll notice that I don't use SumExpression in my code, so an error message that SumExpression is not iterable is not actionable.
The objection function follows the form of many, many other pyomo objective functions that do work fine.
The problem I'm working on is easy to solve in cvxpy, but I'm tasked with getting pyomo to be useful. So far, not so good.
Is there a (nonobvious) error here? Do the error messages contain actionable information? Do I have a broken pyomo installation?
The error is in the construction of your Objective().
pyomo is making the (false) assumption that the first parameter in the function call is an iterable. Most pyomo commands like making variables or constraints with a "rule" assume the first thing(s) in the call are the indexing set(s).
You should identify it by a keyword. Or just put the expression in the function. Either of these should work. (Note the use of 'rule' in the first and 'expr' in the second)
model.objective = Objective(rule=objective_rule) #minimize is default and not needed
or you can ditch the function as it is just a simple expression and put:
model.objective = Objective(expr=sum(model.ccv[c] * model.SELECT[c] for c in model.c))

Initialize list variable as empty within Robot Framework ***Variables*** section

I would like to define a list variable which is empty initially:
*** Settings ***
Library Collections
*** Variables ***
#{customers}= [] # how to do this the right way? I expect an empty list.
*** Test Cases ***
Create Customers
Add New Customer
Add New Customer
Log to console ${customers}
# results in: ['[]', {'name': 'Ben', 'id': '123'}, {'name': 'Ben', 'id': '123'}]
*** Keywords ***
Add New Customer
${customer}= Create Dictionary name=Ben id=123
Append To List ${customers} ${customer}
Regardless I know I could initialize #{customers} within testcase with 'Create List' I'm confused why the list has '[]' as first element. How I could initialize a list as empty in Variables section?
For Robot, it's enough to do this:
*** Variables ***
#{customers}=
when you use #, Robot knows you're creating a list, and there's nothing on the right side, so it will be empty. And = is optional, so you could also type:
*** Variables ***
#{customers}
If it were outside Variables section, you could also use:
${customers}= Create List
You could use the built in variable ${EMPTY} to explicitly init something to empty. You won't have a warning with it.
This one could be passed to keywords directly as well. For more check the User Guide, Space and empty variables.

Why is Crystal .should be producing a spurious error

I am converting a Ruby program to Crystal as I learn it.
Here is an error message I am getting:
# Error
Failures:
1) Test Rule class can return the name property
Failure/Error: rule.name.should be "RpsIphone"
Expected: "RpsIphone" (object_id: 4504126256)
got: "RpsIphone" (object_id: 4524981536)
# spec/rule_spec.cr:11
And here is the code that is causing it
# from spec
rule.name.should be "RpsIphone"
I also checked that the two strings when compared with .same? also say they are not the same. I've looked at those 9 characters over and over. What am I missing?
Crystal's .should be tests for the objects being the same,
identical, same object_id
Crystal's .should eq tests for the values being the same

Django testing, issue with localised error messages

I am making the first steps with using Django localisation, and I have just faced the first difficulty. I am trying to test that something in models works as expected. For invalid input, a specific ValidationError should occur. The code in the test looks like this:
try:
p = ...
p.full_clean()
self.fail('Expected exception not raised')
except ValidationError as e:
dict_err = dict(e)
self.assertIn('category', dict_err.keys())
self.assertEqual(len(dict_err.keys()), 1, 'Encountered more than one error')
self.assertIn('blank', dict_err['category'][0])
As long as the site operates in English (LANGUAGE_CODE = 'en-uk'), the caught error looks like this:
ValidationError({'category': ['This field cannot be blank.']})
To check that I've got exactly this ValidationError, I am searching for the work 'blank' in the error message (last line of the code above).
It fails as soon as I switch the site to another language. E.g. for German it looks so:
ValidationError({'category': ['Dieses Feld darf nicht leer sein.']})
Looking for 'blank' obviously fails the test. How could I check the error message? I expect, somewhere deep in Django, there should be a unique identifier of this message (so that Django knows how to translate). But I don't see any traces of it in the error value. I would expect something like
self.assertIn(_(id), dict_err['category'][0])
would do the trick, if I could guess what id should be, and if I understand correctly what _() does.
By further trial and error, I've found that for simple messages the message ID is simply the original English message. That is, one can do:
...
expected_error = _("This field cannot be blank.")
self.assertIn(expected_error, dict_err['category'][0])
or even
self.assertEqual(expected_error, dict_err['category'][0])
It works then independent of the site language.
For errors using named-string interpolation, the code would look like follows. Assuming the English-language error message is Value 'x' is not a valid choice., we do:
expected_error = _("Value %(value)r is not a valid choice.") % {'value': 'x'}
self.assertEqual(expected_error, dict_err['category'][0])
I've found that the easiest way to determine the respective message ID is to search for the part of the English error message in the venv files. For example, I found the error above searching for "is not a valid choice", which is obviously an immutable part of the message.
Special thanks to #MosesKoledoye: his comment to my question hinted in the right direction.

Python: unable to produce the output in list format

I want to produce the output in a list format but I am failing.
It's taking some login details from a text file:
Ip1,username1,pwd1
Ip2,username2,pwd2
Ip3,username3,pwd3
Ip4,username4,pwd4
My Python script:
import os.path
save_path = "C:\Users\Public\Pythonlearn"
input_pwd_file= os.path.join(save_path,'loginfile'+'.txt')
with open(input_pwd_file) as f:
list = []
for line in f:
list.append(line)
a=list[3]
print "login details: ",a
I am getting below output:
login details: Ip4,username4,pwd4
But I want it to be like:
login details: ['Ip4','username4','pwd4']
Well, you are just appending the raw line to the list, instead of parsing it. So, it is expected that the lines in the list is exactly the same as the lines in the file. A simple way to parse the line is by using str.split() and do line_as_list = line.split(','). From there it's just a matter of using the list to make a string from.
Final note: Don't call your list variable list. That shadows the built-in constructor to build a list with.
Change a=list[3] to a=list[3].split(',') and as beruic said, don't name your list 'list'