我正在考虑将一些unittest.TestCase测试转换为Pytest测试,以利用Pytest的fixture。然而,unittest的一个特性是创建测试套件并运行它们的能力,这是我在Pytest中很难找到的等价物。我现在经常做这样的事情:
import unittest
class TestSomething(unittest.TestCase):
def test_1(self):
self.assertEqual("hello".upper(), "HELLO")
def test_2(self):
self.assertEqual(1+1, 2)
if __name__ == "__main__":
suite = unittest.TestSuite()
# suite.addTest(TestSomething('test_1'))
suite.addTest(TestSomething('test_2'))
runner = unittest.TextTestRunner()
runner.run(suite)通过使用addTest对各行进行注释,我可以轻松地选择要运行的测试。我该如何用Pytest做类似的事情呢?
发布于 2017-01-25 22:15:35
您可以使用-k参数来运行特定的测试。例如
# put this in test.py
import unittest
class TestSomething(unittest.TestCase):
def test_1(self):
self.assertEqual("hello".upper(), "HELLO")
def test_2(self):
self.assertEqual(1+1, 2)可以像这样运行TestSomething类中的所有测试:
py.test test.py -k TestSomething仅运行test_2
py.test test.py -k "TestSomething and test_2"documentation中的更多示例
发布于 2017-01-25 22:38:49
另一种方法是使用特殊的测试名称。这些可以在pytest.ini文件中进行配置。
# content of pytest.ini
# can also be defined in tox.ini or setup.cfg file, although the section
# name in setup.cfg files should be "tool:pytest"
[pytest]
python_files=check_*.py
python_classes=Check
python_functions=*_check另一种方法是在conftest.py中执行操作。在本例中,使用了collect_ignore配置变量。它是要忽略的测试路径的列表。在本例中,收集时总是忽略test_somthing.py。如果我们使用Python3进行测试,则忽略test_other_module_py2.py。
# content of conftest.py
import sys
collect_ignore = ["test_something/test_something.py"]
if sys.version_info[0] > 2:
collect_ignore.append("test_other/test_other_module_py2.py")从pytest 2.6开始,也可以从测试注册中省略类,如下所示:
# Will not be discovered as a test
class TestClass:
__test__ = False这些示例松散地取自pytest章节Changing standard (Python) test discovery的文档
发布于 2017-01-25 22:17:28
除了使用-k筛选器之外,您还可以命名要运行的特定测试类或用例。
py.test test.py::TestSomething::test_2将只运行test_2
https://stackoverflow.com/questions/41853509
复制相似问题