Reputation:
I am facing the problem of checking if my function returns nan in one of the unittest cases.
Doing a bit of research I found this question which already asks how to do it and a solution is provided.
One of the solutions is using assertTrue(math.isnan(nan_value))
but it has the downside of raising a TypeError
if x
is neither a float
nor a Real
.
The other solution consist on defining a class of Numerical Assertions where you can handle the nan case. I could implement this and happily solve my problem.
However checking for nan looks like a common test that a lot of people might need to do (either in unittests or just in plain if/else blocks).
So my question is a bit like: Is there already a implementation that does this in a stardard way, so anybody that checks for nans will always run the same code and obtain the same result? Or the common approach is to define myself the check provided in the linked question?
Does a feature like this exist in numpy, math or unittest libraries? I think it would be extremely useful to have an assertNan
function in unittest
Upvotes: 3
Views: 724
Reputation: 16660
Given that for non-float
data type it is not nan either way I would use the implicit feature of the order of evaluation (and skipping) for and
logical clauses. Namely, if the first operand is False
, then the second part is not evaluated:
assertTrue(type(nan_value) is float and math.isnan(nan_value))
In the code above if the type of nan_value
is not float
then the and
clause is False
so math.isnan(nan_value)
is not evaluated and no TypeError
is generated.
Upvotes: 2