[TIP] assertions with numpy bool and pep8 advice

Brianna Laugher brianna.laugher at gmail.com
Thu Jun 19 22:08:22 PDT 2014


...That last example should of course be

@py.test.mark.parametrize(('vals', 'expected'), [
    ([3, 4, 5], False),
    ([5, 6, 7], True),
    ])
def test_foo4(vals, expected):
    a = foo(vals)
    assert a is expected




On 20 June 2014 15:06, Brianna Laugher <brianna.laugher at gmail.com> wrote:

> Hello,
>
> Has anyone encountered the problem that a numpy bool False 'is' not a
> 'bool' False?
>
> import py
> import numpy as np
>
> def foo(vals):
>     mean = np.mean(vals)
>     return mean > 5
>
> def test_foo():
>     a = foo([3, 4, 5])
>     assert a is False
>
> def test_foo2():
>     a = foo([3, 4, 5])
>     assert not a
>
> def test_foo3():
>     a = foo([3, 4, 5])
>     assert a == False
>
>
> test_foo fails, test_foo2 and test_foo3 pass. And I get the lovely
> mystifying traceback
>
> Traceback (most recent call last):
>   File "/workspace/test_foo.py", line 12, in test_foo
>     assert a is False
> AssertionError: assert False is False
>
> However, pep8 doesn't like the style of foo3:
>
>  E712 comparison to False should be 'if cond is False:' or 'if not cond:'
>
> The style of foo2 is usually fine to use, but sometimes I have tests where
> I want to be more explicit, e.g.
>
> @py.test.mark.parametrize(('vals', 'expected'), [
>     ([3, 4, 5], False),
>     ([5, 6, 7], True),
>     ])
> def test_foo4(vals, expected):
>     a = foo(vals)
>     assert a is False
>
>
> I was totally surprised to realise that I was getting back some numpy bool
> object anyway and not just a regular False. It seems like a bit of a
> gotcha, luckily our code base does not contain many 'if x is True/False'
> formulations but it could cause quite subtle bugs.
> Just wondering if anyone has advice here.
>
> thanks,
> Brianna
>
> --
> They've just been waiting in a mountain for the right moment:
> http://modernthings.org/
>



-- 
They've just been waiting in a mountain for the right moment:
http://modernthings.org/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20140620/944033b0/attachment.htm>


More information about the testing-in-python mailing list