import在pytes中运行两次测试

2024-10-05 10:18:10 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么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的内容:

^{pr2}$

输出:

[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.测试忽略进口背后的测试?在


Tags: inpytestimportself内容foodef
3条回答

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

import test_foo

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

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

不,它没有一个好办法来忽视进口。测试运行程序只需枚举模块中定义的名称,并执行看起来像测试的名称。例如,如果导入第一个测试_棒.pydir模块,它同时定义TestFoo和{}。测试运行程序可以看到并执行这两个测试。在

类似地,TestBar有两个方法test_bar和{}。测试运行程序不区分由测试类定义的名称和从基类继承的名称。在

from test_foo import TestFoo:—这句话将使TestFoo类可用于测试_棒.py在

以及

类TestBar(TestFoo):这使得TestBar类扩展了TestFoo。。。。在

试验内容_棒.py在

这是因为你正在导入类

类TestFoo(unittest.TestCase): def test_foo(自我): 打印(“在测试中”)

类TestBar(TestFoo): #这是因为u正在扩展TestFoo,因此TestBar也可以使用它的函数 def test_foo(自我): 打印(“在测试中”)

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

现在很清楚,如果你运行这个特定的模块,输出会是什么。。在

相关问题 更多 >

    热门问题