pytest-dev / pytest-dev/pytest
Let pytest.warns check the warning's stacklevel
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 14.5k
- Forks
- 3.4k
- Avg merge
- 2d 9h
- Merged PRs (30d)
- 35
Description
This is a feature request for adding a check_stacklevel flag to pytest.warns. This helps library authors test that warnings point back to the user's source code, rather than some internal method.
An example: f is the public API exposed to users. g is some internal function that emits a warning.
import warnings
import pytest
def g(x):
# some internal function
warnings.warn("warning from g")
def f(x):
# the public API
g(x)
def test_foo():
# proposal for new argument: check_stacklevel
with pytest.warns(UserWarning, match="from g", check_stacklevel=True):
f(2)
if __name__ == '__main__':
f(2)
Ideally, test_foo would fail because the warning message points back to line 7, which is inside g
test_it.py:7: UserWarning: warning from g
warnings.warn("warning from g")
The test would succeed if the warning pointed back to the call f(2), inside the test. This would require setting stacklevel=2 inside g.
Pandas added this check a couple years ago, and we've been quite happy with it: https://github.com/pandas-dev/pandas/blob/af602c5b702366d8b978ed04cafa371d63f6c32f/pandas/util/testing.py#L2707-L2718
It requires a frame hack, but a small one. Having it be a flag is necessary, in case an internal function is called from two places with different stacklevels. In pandas, we like the default of True. Perhaps this could be handled similarly to strict for xfails.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by locating pytest.warns and review how warning records expose their originating frame. Compare the requested check_stacklevel behavior with the linked pandas approach, then add coverage for warnings emitted from an internal function and verify that correctly targeted warnings pass while internal frames fail.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100