为什么 py.test
会在那里运行 TestFoo.test_foo()
测试?我知道它运行 TestBar.test_foo()
。
test_foo.py
的内容:
import unittest
class TestFoo(unittest.TestCase):
def test_foo(self):
print "in test_foo"
test_bar.py
的内容:
from test_foo import TestFoo
class TestBar(TestFoo):
def test_bar(self):
print "in test_bar"
输出:
[999]anarcat@marcos:t$ pytest -v
no test dir found testing here: /tmp/t
=========================== test_bar.py ============================
test_bar (test_bar.TestBar) ... in test_bar
ok
test_foo (test_bar.TestBar) ... in test_foo
ok
test_foo (test_foo.TestFoo) ... in test_foo
ok
=========================== test_foo.py ============================
test_foo (test_foo.TestFoo) ... in test_foo
ok
*******************************************************************************
Ran 4 test cases in 0.00s (0.00s CPU)
All 2 modules OK
如果 TestBar
与 TestFoo
放在同一个文件中,则 TestFoo.test_foo()
测试只运行一次:
import unittest
class TestFoo(unittest.TestCase):
def test_foo(self):
print "in test_foo"
class TestBar(TestFoo):
def test_bar(self):
print "in test_bar"
输出:
[1001]anarcat@marcos:t$ pytest -v
no test dir found testing here: /tmp/t
=========================== test_foo.py ============================
test_bar (test_foo.TestBar) ... in test_bar
ok
test_foo (test_foo.TestBar) ... in test_foo
ok
test_foo (test_foo.TestFoo) ... in test_foo
ok
*******************************************************************************
Ran 3 test cases in 0.00s (0.00s CPU)
All 1 modules OK
py.test 不应该忽略在导入后面发现的测试吗?
最佳答案
解决这个问题的一个简单方法是导入模块而不是导入测试类。
import test_foo
class TestBar(test_foo.TestFoo):
def test_bar(self):
print "in test_bar"
这将允许您访问 TestFoo
类,而无需运行两次测试。
关于python - import 在 pytest 中运行两次测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32960334/