Why remove the letter "C" before ${expression} causes error? - robotframework

I am using Python-RF framework with the example below. I scanned the file
"C" is considered as "". If in the robot file I remove the letter C before the ${expression}, it causes error
Original:
Test Template Calculate
Library CalculatorLibrary.py
*** Test Cases *** Expression Expected
Addition 12 + 2 + 2 16
2 + -3 -1
*** Keywords ***
Calculate
[Arguments] ${expression} ${expected}
Push buttons C${expression}=
Result should be ${expected}
Changed:
*** Test Cases ***
Additions 12 + 2 + 2 16
2 + -3 -1
*** Keywords ***
Calculate
[Arguments] ${expression} ${expected}
Push buttons ${expression}=
Result should be ${expected}
There is an error " 159 != -1". Everyone can share your ideas what wrong it is?
Library file:
https://bitbucket.org/robotframework/robotdemo/src/51f472687b6a46e88b7c179423f0f336e19497fc/CalculatorLibrary.py?at=master&fileviewer=file-view-default
https://bitbucket.org/robotframework/robotdemo/src/51f472687b6a46e88b7c179423f0f336e19497fc/calculator.py?at=master&fileviewer=file-view-default

Without "C":
After your first test case ${expression} is "16". Then you put "2" at the end of it, now ${expression} is "162". Then you substract 3 from it which gives you 159 and this is what you see in the error.
With "C":
Using "C" you set ${expression} to "" (empty string) and then you calculate "2-3" which gives you correct "-1".

Related

Pyomo constraint issue: not returning constrained result

I setup a constraint that does not constraint the solver in pyomo.
The constraint is the following:
def revenue_positive(model,t):
for t in model.T:
return (model.D[t] * model.P[t]) >= 0
model.positive_revenue = Constraint(model.T, rule=revenue_positive)
while the model parameters are:
model = ConcreteModel()
model.T = Set(doc='quarter of year', initialize=df.index.tolist(), ordered=True)
model.P = Param(model.T, initialize=df['price'].to_dict(), within=Any, doc='Price for each quarter')
model.C = Var(model.T, domain=NonNegativeReals)
model.D = Var(model.T, domain=NonNegativeReals)
income = sum(df.loc[t, 'price'] * model.D[t] for t in model.T)
expenses = sum(df.loc[t, 'price'] * model.C[t] for t in model.T)
profit = income - expenses
model.objective = Objective(expr=profit, sense=maximize)
# Solve the model
solver = SolverFactory('cbc')
solver.solve(model)
df dataframe is:
df time_stamp price Status imbalance Difference Situation ... week month hour_of_day day_of_week day_of_year yearly_quarter
quarter ...
0 2021-01-01 00:00:00 64.84 Final 16 -3 Deficit ... 00 1 0 4 1 1
1 2021-01-01 00:15:00 13.96 Final 38 2 Surplus ... 00 1 0 4 1 1
2 2021-01-01 00:30:00 12.40 Final 46 1 Surplus ... 00 1 0 4 1 1
3 2021-01-01 00:45:00 7.70 Final 65 14 Surplus ... 00 1 0 4 1 1
4 2021-01-01 01:00:00 64.25 Final 3 -9 Deficit ... 00 1 1 4 1 1
The objective is to constraint the solver not to accept a negative revenue. As such it does not work as the solver passes 6 negative revenue values through. Looking at the indices with negative revenue, it appears the system chooses to sell at a negative price to buy later at a price even "more" negative, so from an optimization standpoint, it is ok. I would like to check the difference in results if we prohibit the solver to do that. Any input is welcome as after many searches on the web, still not the right way to write it correctly.
I did a pprint() of the constraint that returned:
positive_revenue : Size=35040, Index=T, Active=True
UPDATE following new constraint code:
def revenue_positive(model,t):
return model.D[t] * model.P[t] >= 0
model.positive_revenue = Constraint(model.T, rule=revenue_positive)
Return the following error:
ERROR: Rule failed when generating expression for constraint positive_revenue
with index 283: ValueError: Invalid constraint expression. The constraint
expression resolved to a trivial Boolean (True) instead of a Pyomo object.
Please modify your rule to return Constraint.Feasible instead of True.
Error thrown for Constraint 'positive_revenue[283]'
ERROR: Constructing component 'positive_revenue' from data=None failed:
ValueError: Invalid constraint expression. The constraint expression
resolved to a trivial Boolean (True) instead of a Pyomo object. Please
modify your rule to return Constraint.Feasible instead of True.
Error thrown for Constraint 'positive_revenue[283]'
Traceback (most recent call last):
File "/home/olivier/Desktop/Elia - BESS/run_imbalance.py", line 25, in <module>
results_df = optimize_year(df)
File "/home/olivier/Desktop/Elia - BESS/battery_model_imbalance.py", line 122, in optimize_year
model.positive_revenue = Constraint(model.T, rule=revenue_positive)
File "/home/olivier/anaconda3/lib/python3.9/site-packages/pyomo/core/base/block.py", line 542, in __setattr__
self.add_component(name, val)
File "/home/olivier/anaconda3/lib/python3.9/site-packages/pyomo/core/base/block.py", line 1087, in add_component
val.construct(data)
File "/home/olivier/anaconda3/lib/python3.9/site-packages/pyomo/core/base/constraint.py", line 781, in construct
self._setitem_when_not_present(
File "/home/olivier/anaconda3/lib/python3.9/site-packages/pyomo/core/base/indexed_component.py", line 778, in _setitem_when_not_present
obj.set_value(value)
File "/home/olivier/anaconda3/lib/python3.9/site-packages/pyomo/core/base/constraint.py", line 506, in set_value
raise ValueError(
ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (True) instead of a Pyomo object. Please modify your rule to return Constraint.Feasible instead of True.
Error thrown for Constraint 'positive_revenue[283]'
So there are 2 issues w/ your constraint. It isn't clear if one is a cut & paste issue or not.
The function call to make the constraint appears to be indented and inside of your function after the return statement, making it unreachable code. Could be just the spacing in your post.
You are incorrectly adding a loop inside of your function. You are passing in the parameter t as a function argument and then you are blowing it away with the for loop, which only executes for the first value of t in T then hits the return statement. Remove the loop. When you use the rule= structure in pyomo it will call the rule for each instance of the set that you are using in the Constraint(xx, rule=) structure.
So I think you should have:
def revenue_positive(model, t):
return model.D[t] * model.P[t] >= 0
model.positive_revenue = Constraint(model.T, rule=revenue_positive)
Updated re: the error you added.
The error cites the 283rd index. My bet is that price[283] is zero, so you are multiplying by a zero and killing your variable.
You could add a check within the function that checks if the price is zero, and in that case, just return pyo.Constraint.Feasible, which is the trivial return that doesn't influence the model (or crash)

How to prompt a user for input until the input is valid in Julia

I am trying to make a program to prompt a user for input until they enter a number within a specific range.
What is the best approach to make sure the code does not error out when I enter a letter, a symbol, or a number outside of the specified range?
In alternative to parse, you can use tryparse:
tryparse(type, str; base)
Like parse, but returns either a value of the requested type, or
nothing if the string does not contain a valid number.
The advantage over parse is that you can have a cleaner error handling without resorting to try/catch, which would hide all exceptions raised within the block.
For example you can do:
while true
print("Please enter a whole number between 1 and 5: ")
input = readline(stdin)
value = tryparse(Int, input)
if value !== nothing && 1 <= value <= 5
println("You entered $(input)")
break
else
#warn "Enter a whole number between 1 and 5"
end
end
Sample run:
Please enter a whole number between 1 and 5: 42
┌ Warning: Enter a whole number between 1 and 5
└ # Main myscript.jl:9
Please enter a whole number between 1 and 5: abcde
┌ Warning: Enter a whole number between 1 and 5
└ # Main myscript.jl:9
Please enter a whole number between 1 and 5: 3
You entered 3
This is one possible way to achieve this sort of thing:
while true
print("Please enter a whole number between 1 and 5: ")
input = readline(stdin)
try
if parse(Int, input) <= 5 || parse(Int, input) >= 1
print("You entered $(input)")
break
end
catch
#warn "Enter a whole number between 1 and 5"
end
end
Sample Run:
Please enter a whole number between 1 and 5: 2
You entered 2
See this link for how to parse the user input into an int.

Get all value from For loop in robot framework

Hi I am new in robot framework,
I need to click in some element with xpath.
I get the number of element and stored in a variable ${element}
when I run my code it found ${element}=4
Now I want to click on each element.
So i tried to get all index in a variable like ${i1} untill ${i4}
The result should give me this:
${i1} = 0
${i2} = 1
${i3} = 2
${i4} = 3
i tried this
:FOR ${i} IN RANGE 0 ${element}
\ log ${i}
But it gives result like
20181101 19:21:07.269 : INFO : ${i}: 0
20181101 19:21:08.269 : INFO : ${i}: 1
20181101 19:21:09.269 : INFO : ${i}: 2
20181101 19:21:10.269 : INFO : ${i}: 3
Thank you
In your case you should be use Nest Variable of robotframework . you can find my sample below and its should be solve your current problem.
test
${i} Set Variable i
:FOR ${n} IN RANGE 4
\ ${x} Evaluate ${n}+1
\ Set Test Variable ${${i}${x}} ${n}
log to console ${i3}
and the result is same as you expetcation
${i1} = 0
${i2} = 1
${i3} = 2
${i4} = 3
What you want to do can be achieved by using the keyword Set (Test/Suite/Global) Variable keyword. This takes two parameters and allows you to use variables in variables for creating the name.
*** Test Cases ***
TC
${element} Set Variable ${4}
:FOR ${i} IN RANGE 0 ${element}
\ Set Test Variable ${i${i}} ${i}
This results in the following Message Log in RED.
Starting test: Folder.Forloop I.TC
20181102 07:41:39.010 : INFO : ${element} = 4
20181102 07:41:39.033 : INFO : ${i0} = 0
20181102 07:41:39.044 : INFO : ${i1} = 1
20181102 07:41:39.055 : INFO : ${i2} = 2
20181102 07:41:39.064 : INFO : ${i3} = 3
Ending test: Folder.Forloop I.TC

julia 1.0 installation tests - nix-pkgs - ubuntu

My laptop:
Linux g-TP 4.13.0-26-generic #29~16.04.2-Ubuntu SMP Tue Jan 9 22:00:44
UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
I installed julia via nix-env and got the following test result
Test Summary: | Pass Broken Total
Overall | 37420635 327815 37748450
SUCCESS
What can / should I do for resolving the 327815 broken tests?
A test that is marked as broken (with #test_broke) does not lead to a test failure, all tests passed as indicated by the SUCCESS in the output.
From the docs of #test_broken:
help?> #test_broken
#test_broken ex
Indicates a test that should pass but currently consistently fails.
Tests that the expression ex evaluates to false or causes an exception.
Returns a Broken Result if it does, or an Error Result if the expression evaluates to true.
Example:
julia> using Test
julia> #testset begin
#test 1 == 1 # results in a Pass
#test 1 == 2 # results in a Fail
#test_broken 1 == 2 # results in a Broken
end
Test Summary: | Pass Fail Broken Total
test set | 1 1 1 3
ERROR: Some tests did not pass: 1 passed, 1 failed, 0 errored, 1 broken.

Robot framework how to set own name for each test case in data driven tests for report output

Could you please help me how to set own name for each test case into Data Driven to make report more readable.
REAL REPORT EXAMPLE:
Status: FAIL (critical)
Message: Several failures occurred:
1) ******************************
FAIL: Wrong value received. Expected: 0 . Actual: 3
2) ******************************
FAIL: Wrong value received. Expected: 0 . Actual: 3
3) ******************************
FAIL: Wrong value received. Expected: 0 . Actual: 3
But it is not clear from the output about details. And I would like to have some details instead of ***************,
THAT I NEED :
Status: FAIL (critical)
Message: Several failures occurred:
1) if param is empty
FAIL: Wrong value received. Expected: 0 . Actual: 3
2) if param is out of range
FAIL: Wrong value received. Expected: 0 . Actual: 3
3) if param is something more
FAIL: Wrong value received. Expected: 0 . Actual: 3
I have these detail as ${comment} for each table line into data driven. Could you please help me how to assign it for each test case inside data driven to have more understandable report.
DATA DRIVEN TEST EXAMPLE
st_ddt_test_example
[Template] st_ddt_test_example_keyword
# comment # # value setup # # value expected #
if param is empty 0 0
if param is out of range 100 0
if param is something more -8 0
Your keyword controls the error that is displayed, so it just needs to include the name as part of the error message.
Here is an example:
*** Keywords ***
Example
[Arguments] ${comment} ${1} ${2}
should be equal ${1} ${2}
... ${comment}: '${1}' != '${2}'
... False
*** Test Cases ***
Test 1
[Template] example
Test 1.0 a b
Test 1.1 b c
Test 1.2 c d
When run, the test yields the following results:
Test 1 | FAIL |
Several failures occurred:
1) Test 1.0: 'a' != 'b'
2) Test 1.1: 'b' != 'c'
3) Test 1.2: 'c' != 'd'

Resources