简体   繁体   中英

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

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/

pytest is using assertion directly so you don't have to learn about function names and existence and directly use what the language offer and display error nicely. So, if you want to test for falsyness/trutheyness with pytest you do this::

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

If you want to check that something is literally False or True then you do this::

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

Creating a function that does something that already exists in python because you're not familiar with it, is not a good practice. Use the tools of the language everyone familiar with python is already using. Otherwise reading your codebase will have a cost of entry for things that you invented and that no one is familiar with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM