victory的博客

长安一片月,万户捣衣声

0%

pytest | 如何调用pytest

如何调用pytest

pytest支持命令行参数选择特定的tests去执行,以下是常见的一些选择方法。

1
2
3
4
5
6
7
# run tests in a module
# 运行测试文件中的所有符合pytest测试发现规则的测试用例(测试文件中符合test_*()的函数、TestXxx类中的测试用例)
pytest test_mod.py

# run tests in a directory
# 运行testing目录下的所有文件名符合test_*.py或*_test.py的测试文件中的测试用例
pytest testing/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# run tests by keyword expressions
pytest -k "MyClass and not method"
# 通过关键词表达式指定pytest运行的测试用例,pytest会在testpaths或者当前目录下找到类名为TestMyClass的类中的方法名不带method的方法去执行。如下示例,运行pytest -k "MyClass and not method"会执行test_a方法而不会运行test_method_add()方法

# 编写测试文件test_keyword_exp.py
def add(a, b):
return a + b


class TestMyClass:
def test_a(self):
assert "a" == "a"

def test_method_add(self):
assert add(1, 2) == 3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# run tests by collection arguments

# To run a specific test within a module
# 运行test_mod.py测试文件中的test_func测试用例
pytest tests/test_mod.py::test_func

# To run all tests in a class:
# 运行test_mod.py测试文件中的TestClass类中的测试用例
pytest tests/test_mod.py::TestClass

# Specifying a specific test method:
# 运行test_mod.py测试文件中的TestClass类中的test_method测试用例
pytest tests/test_mod.py::TestClass::test_method

# Specifying a specific parametrization of a test:
# 运行test_mod.py测试文件中的带参数的test_func测试用例
pytest tests/test_mod.py::test_func[x1,y2]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Run tests by marker expressions
# 运行带有@pytest.mark.slow装饰器的测试
pytest -m slow

# 以下示例中,pytest将运行test_a测试用例,而不会运行test_b测试用例
import pytest

class TestMarkDecoration:
@pytest.mark.slow
def test_a(self):
assert 1 == 1

@pytest.mark.quick
def test_b(self):
assert 2 == 2
1
2
3
# run tests from packages
pytest --pyargs pkg.testing
# 这将导入pkg.testing,并使用其文件系统位置从中查找和运行测试