如何修复 Python unittest __init__() takes 1 positional argument but 2 were given
问题:
你正在尝试使用 unittest 包运行 Python 单元测试,但你看到此不明确的堆栈跟踪:
traceback.txt
Traceback (most recent call last):
File "/usr/lib/python3.7/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.7/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/lib/python3.7/unittest/__main__.py", line 18, in <module>
main(module=None)
File "/usr/lib/python3.7/unittest/main.py", line 100, in __init__
self.parseArgs(argv)
File "/usr/lib/python3.7/unittest/main.py", line 124, in parseArgs
self._do_discovery(argv[2:])
File "/usr/lib/python3.7/unittest/main.py", line 244, in _do_discovery
self.createTests(from_discovery=True, Loader=Loader)
File "/usr/lib/python3.7/unittest/main.py", line 154, in createTests
self.test = loader.discover(self.start, self.pattern, self.top)
File "/usr/lib/python3.7/unittest/loader.py", line 349, in discover
tests = list(self._find_tests(start_dir, pattern))
File "/usr/lib/python3.7/unittest/loader.py", line 414, in _find_tests
yield from self._find_tests(full_path, pattern, namespace)
File "/usr/lib/python3.7/unittest/loader.py", line 406, in _find_tests
full_path, pattern, namespace)
File "/usr/lib/python3.7/unittest/loader.py", line 460, in _find_test_path
return self.loadTestsFromModule(module, pattern=pattern), False
File "/usr/lib/python3.7/unittest/loader.py", line 124, in loadTestsFromModule
tests.append(self.loadTestsFromTestCase(obj))
File "/usr/lib/python3.7/unittest/loader.py", line 93, in loadTestsFromTestCase
loaded_suite = self.suiteClass(map(testCaseClass, testCaseNames))
File "/usr/lib/python3.7/unittest/suite.py", line 24, in __init__
self.addTests(tests)
File "/usr/lib/python3.7/unittest/suite.py", line 57, in addTests
for test in tests:
TypeError: __init__() takes 1 positional argument but 2 were given解决方案
你至少有一个类似这样的测试用例:
bad_test.py
class MyTest(unittest.TestCase):
def __init__(self):
self.x = 1.0
def test_stuff(self):
assert(self.x == 1.0)使用 unittest 时不能以这种方式覆盖 __init__(...)。你需要改用 setUp()。
通常,只需将 def __init__(self): 替换为 def setUp(self): 即可。unittests 会自动调用 setUp()。
我们的示例将看起来像这样:
good_test.py
class MyTest(unittest.TestCase):
def setUp(self):
self.x = 1.0
def test_stuff(self):
assert(self.x == 1.0)如果错误仍然存在,检查你是否有更多覆盖 __init__() 方法的测试用例。
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow