import 在 pytest 中运行两次测试

import runs tests twice in pytest

为什么 py.test 运行 TestFoo.test_foo() 在那里测试?我明白了 运行s 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

如果TestBarTestFoo放在同一个文件中,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 忽略导入背后的测试吗?

没有。它没有忽略导入的好方法。测试运行器简单地枚举模块中定义的名称并执行看起来像测试的名称。例如,如果您导入第一个 test_bar.pydir 模块,它会同时定义 TestFooTestBar。测试运行器看到两个测试并执行它们。

同样,TestBar 有两种方法 - test_bartest_foo。测试运行器不区分测试 class 定义的名称和从基础 classes.

继承的名称

解决这个问题的一个简单方法是导入模块而不是导入测试 class。

import test_foo

class TestBar(test_foo.TestFoo):
    def test_bar(self):
        print "in test_bar"

这将允许您访问 TestFoo class 而无需两次测试 运行。

from test_foo import TestFoo :- 这句话将使 TestFoo class 可用于 test_bar.py

class TestBar(TestFoo): 这使得 TestBar Class extends TestFoo....

test_bar.py

的内容

这是因为你正在导入 class

class TestFoo(unittest.TestCase): def test_foo(自我): 打印 ("in test_foo")

class 测试栏(TestFoo): #这是因为你正在扩展 TestFoo 因此它的功能也可用于 TestBar def test_foo(自我): 打印 ("in test_foo")

def test_bar(self):
    print ("in test_bar")

现在 crystal 清楚如果你 运行 这个特定模块的输出是什么..