Search code examples
pytestassertpylintassertion

Recommented way to assert boolean value with pytest - related pylint warning


I would like to assert that an expression equals some boolean value:

assert result['foo'][0] == False
assert result['foo'][1] == True

However, pylint suggests to use is or 'not' instead of ==:

Comparison 'result['foo'][0] == True' should be 'result['foo'][0] is True' if checking for the singleton value False, or 'not result['a'][0]' if testing for falsiness (singleton-comparison)

If I use 'is' the test fails.

If I use 'not' I find the expression harder to read/interpret because it seems to be less explicit:

assert not result['foo'][0]
assert result['foo'][1]

a) Is the last way really the best practice to assert boolean expressions and I should get used to it?

b) Or should I disable the warning?

c) Or should I use something like

assertIsFalse(result['foo'][0])
assertIsTrue(result['foo'][1])

or

assert falsy(result['foo'][0])
assert truthy(result['foo'][1])

Further notes:

  1. The pytest documentation does not seem to have a recommendation on how to assert boolean values:

https://docs.pytest.org/en/7.1.x/how-to/assert.html

  1. Pytest does not seem to provide extra assertion methods like assertIsTrue or truthy:

https://docs.pytest.org/en/4.6.x/reference.html#functions

  1. Unittest provides methods assertTrue, assertFalse. However, that would require to derive from the unittest class.

https://www.pythontutorial.net/python-unit-testing/python-asserttrue/

  1. Numpy does not seem to include assertion methods for boolean values:

https://numpy.org/devdocs/reference/routines.testing.html#asserts


Solution

  • I wrote some custom helper functions to improve readability, based on the built in bool() function:

    def truthy(value):
        return bool(value)
    
    
    def falsy(value):
        return not bool(value)
    

    usage:

    assert falsy(result['foo'][0])
    assert truthy(result['foo'][1])
    

    https://www.geeksforgeeks.org/truthy-vs-falsy-values-in-python/