Skip to content

unittest: Detect duplicate method names #105560

Description

@vstinner

Currently, when an unittest.TestCase has two test methods with the same name, only the second one is run: the first one is silently ignored. In the past, the Python test suite had many bugs like that: see issue #60283. I just found a new bug today in test_sqlite3: issue #105557.

It would be nice to automatically detect when a test method is redefined. The problem is to avoid false alarms on method redefined on purpose: right now, I don't know if there are legit use cases like that.

Here is a prototype:

importinspectimportwarningsclassMyDict(dict):
def__init__(self, class_name):
self.class_name=class_namedef__setitem__(self, name, value):
# TestLoader.testMethodPrefix = 'test'ifname.startswith('test'):
try:
old_value=self[name]
exceptKeyError:
passelse:
ifinspect.isfunction(old_value):
warnings.warn(f"BUG: {self.class_name}.{name}() method redefined", stacklevel=2)
dict.__setitem__(self, name, value)
classMyMetaClass(type):
@classmethoddef__prepare__(metacls, class_name, bases, **kwds):
returnMyDict(class_name)
classTestCase(metaclass=MyMetaClass):
passclassTests(TestCase):
def__init__(self):
self.attr=1self.attr=2deftest_bug(self): # first defintionpassdeftest_bug(self): # second definionpassclassRealTests(Tests):
deftest_bug(self): # implementationprint("run tests")
tests=RealTests()

Output:

poc.py:36: UserWarning: BUG: Tests.test_bug() method redefined
def test_bug(self): # second definion

It only emits a warning on the second Tests.test_bug() method definition. It doesn't emit a warning when RealTests redefines test_bug(): is it a legit use case to override an "abstract" test method of a "base" test case class? This case can also be detected if needed.

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions