[Tutor] unitest with random inputs

Peter Otten __peter__ at web.de
Wed Jul 19 11:43:59 EDT 2017


Sydney Shall wrote:

> I am learning to use unittest.
> 
> I have written a program that runs as it should.
> 247 tests give me a satisfactory answer.
> 
> I have now added one more test and I get an error which I do not
> understand.
> 
> The two relevant tests are:
> 
>   def test_type_capitalsadvanced(self):
>          self.assertEqual(type(self.capitalsadvanced), numpy.ndarray)
> 
>   def test_zero_in_capitalsadvanced(self):
>          self.assertIn(self.capitalsadvanced, 0.0)
> 
> The error message is:
> 
> Traceback (most recent call last):
>    File
> 
"/Users/sydney/Capital/Capital_with_productivity/Current_Versions/testPOCWP_V2.py",
> line 320, in test_zero_in_capitalsadvanced
>      self.assertIn(self.capitalsadvanced, 0.0)
>    File "/Users/sydney/anaconda/lib/python3.6/unittest/case.py", line
> 1077, in assertIn
>      if member not in container:
> TypeError: argument of type 'float' is not iterable
> 
> Final output from the tests is :
> 
> Ran 247 tests in 1.179s
> 
> FAILED (failures=9, errors=1)
> 
> The failures all arise from a 'nan'.

I don't think so. To fix the traceback shown above you have to swap the 
arguments in assertIn():

    def test_zero_in_capitalsadvanced(self):
        self.assertIn(0.0, self.capitalsadvanced)

Digression: once this is done you may still get failures when searching for 
NaN in a sequence as it does not compare equal to itself:

>>> nan = float("nan")
>>> nan == nan
False
>>> a = numpy.array([nan])
>>> nan in a
False

This is how it should be (*), but unfortunately Python's builtin 
list/set/dict/tuple all assume that obj is obj implies obj == obj which 
makes the result of containment test hard to predict:

>>> nan in [nan]
True
>>> nan in [float("nan")]
False


(*) See for example 
<https://en.wikipedia.org/wiki/Floating-point_arithmetic>:
"every NaN compares unequal to every value, including itself"

> It is this problem that I am trying to resolve.
> 
> My problem is that the first test tells me correctly that the object
> capitalsadvanced is a numpy.ndarray. But the second test error message
> says it is a float.
> 
> I should add that the program creates the initial data set by making use
> of the random function which is given a mean to work with. Thus each
> test run will be with different input data. But repeated tests show the
> same errors.
> 
> When I run the same tests with predetermined, fixed data I get no errors
> and no 'nan' errors.
> 
> Any guidance will be very welcome.
> 
> 




More information about the Tutor mailing list