I'm trying to use assertions to show some invariants (mostly in testing) Thus i want to write something like the following:
values = [ range(10) ]
expected_values = [ range(10) ]
map (lambda x: assert x[0] == x[1] ,zip( [ run_function(i) for i in values ], expected_values))
If I use this with unittest.assertEqual this works perfectly fine , but if I want to write this with an assertion it just fails. Is there a way to fix this?
The assert keyword is used when debugging code. The assert keyword lets you test if a condition in your code returns True, if not, the program will raise an AssertionError. You can write a message to be written if the code returns False, check the example below.
Use lambda function syntax to use an if statement in a lambda function. Use the syntax lambda input: true_return if condition else false_return to return true_return if condition is True and false_return otherwise.
In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.
Unfortunately, assert
is a statement and Pythons limited lambdas don't allow that in them. They also restrict things like print
.
You can use a generator expression here though.
assert all(x[0] == x[1] for x in zip( [run_function(i) for i in values ], expected_values))
I personally think that the following would be more readable
assert all(run_function(i) == j for i,j in zip(inputs, expected_values))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With