Test functions that return non-None should raise a warning/error
See original GitHub issueConsider this test:
# The function we're testing
def foo(a: int, b: int) -> int:
return a * 3 + b
@pytest.mark.parametrize(['a', 'b', 'result'], [
[1, 2, 5],
[2, 3, 8],
[5, 3, 18],
])
def test_foo(a, b, result):
return foo(a, b) == result
Did you spot the error? The second parametrization has a typo, 2 * 3 + 3
is 9, not 8. But this test actually doesn’t test anything, because it returns the assertion rather than asserting it. This is a common enough mistake, and it wouldn’t normally be a problem except that it can silently cause false positives in test suites.
I propose that test functions that return anything except None fail with a message that cues users that they probably meant to assert rather than return. This feature could be disabled (or enabled, if there are backwards-compatibility issues) via a config flag if necessary.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:1
- Comments:20 (18 by maintainers)
Top Results From Across the Web
Raise exception vs. return None in functions? - python
Raise an exception. And yes, re-raising a more appropriate exception is fine. ... example function when returning None will be:
Read more >warn_no_return = False: handle implicit "return None" (not ...
I think it should maybe only warn if the return type does not include None (i.e. uses typing.Optional). Given t_mypy.py: import typing def...
Read more >warnings — Warning control — Python 3.11.1 documentation
Python programmers issue warnings by calling the warn() function defined in this module. (C programmers use PyErr_WarnEx() ; see Exception Handling for details ......
Read more >Python's assert: Debug and Test Your Code Like a Pro
In this tutorial, you'll learn how to use Python's assert statement to document, debug, and test code in development.
Read more >Does code throw an error, warning, message, or ... - testthat
In the 3rd edition, these functions match (at most) a single condition. All additional and non-matching (if regexp or class are used) conditions...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
interestingly enough,
unittest
in cpython now warns in this situation: https://github.com/python/cpython/pull/27748my note is about refactoring to common functions instead of running other test functions