unittest: TestLoader.discover() returns tests in package/__init__.py
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 36k
- PR merge metrics
- PR metrics pending
Description
According to the docs:
TestLoader.discover(start_dir, pattern='test*.py', top_level_dir=None)
Find all the test modules by recursing into subdirectories from the specified start directory, and return a TestSuite object containing them. Only test files that match pattern will be loaded.
However, tests are also loaded from __init__.py. This does not match the pattern test*.py.
To reproduce, create package/__init__.py with the following contents:
import unittest
class Test(unittest.TestCase):
def test(self):
self.fail('')
Then run python3 -m unittest. The expected output is Ran 0 tests. But it actually is:
F
======================================================================
FAIL: test (package.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "package/__init__.py", line 5, in test
self.fail('')
AssertionError
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
So the test was discovered, despite being located in a file that does not match the pattern test*.py.
The same happens when the TestCase subclass is imported in any __init__.py file.
I tested the above with Python 3.9.2. It does not happen for me with Python 2.7.18.
Linked PRs
- gh-100487
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
Reproduce the issue with a package/init.py containing the shown TestCase and run python3 -m unittest; begin at the TestLoader.discover() entry point. Done means tests in files that do not match the test*.py pattern, including package/init.py, are not discovered; check linked PR gh-100487 for work already underway.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing-qa
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 25/100