python - import 在 pytest 中运行两次测试

标签 python unit-testing pytest

为什么 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

如果 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 不应该忽略在导入后面发现的测试吗?

最佳答案

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

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/

相关文章:

python - Django 1.8 python : can't open file 'manage.py' : [Errno 2] No such file or directory

Python Split() 和 re.split()

ruby-on-rails - 非 ActiveRecord 模型的机械师

python - 在python中获取 float 的小数部分

python - 使用 beautifulsoup 提取 url 和标题

unit-testing - 使用 reCaptcha 测试表单提交的安全和标准方法是什么?

unit-testing - 您如何使用规范编写参数化测试?

python - 测试需要用户输入的 Python 函数()

python - python中有什么方法可以找出调用其他方法的方法吗?

python - 如何使用输入调用测试函数?