在使用 pytest
时,如果你想要精准地运行指定的测试文件,可以通过以下几种方式来实现:
你可以直接在命令行中指定要运行的测试文件的路径。pytest
会自动识别并运行该文件中的所有测试用例。
pytest path/to/your/test_file.py
例如,如果你有一个测试文件 test_example.py
,你可以这样运行:
pytest tests/test_example.py
-k
选项运行特定测试函数如果你只想运行某个测试文件中的特定测试函数,可以使用 -k
选项来指定测试函数的名称。
pytest path/to/your/test_file.py -k "test_function_name"
例如,如果你想运行 test_example.py
文件中的 test_addition
函数,可以这样运行:
pytest tests/test_example.py -k "test_addition"
::
语法运行特定测试类或方法如果你在测试文件中定义了测试类,并且只想运行某个类或类中的某个方法,可以使用 ::
语法。
pytest path/to/your/test_file.py::TestClassName
或者运行类中的某个方法:
pytest path/to/your/test_file.py::TestClassName::test_method_name
例如,假设 test_example.py
文件中有一个 TestMath
类,其中有一个 test_subtraction
方法,你可以这样运行:
pytest tests/test_example.py::TestMath::test_subtraction
-m
选项运行标记的测试如果你在测试文件中使用了 @pytest.mark
来标记某些测试,可以使用 -m
选项来运行这些标记的测试。
pytest path/to/your/test_file.py -m "mark_name"
例如,如果你在 test_example.py
中标记了 @pytest.mark.slow
,你可以这样运行:
pytest tests/test_example.py -m "slow"
pytest.ini
配置文件如果你经常需要运行特定的测试文件或测试集合,可以在项目根目录下创建一个 pytest.ini
文件,并在其中配置默认的测试路径或标记。
[pytest]
addopts = tests/test_example.py
这样,每次运行 pytest
时,都会默认运行 tests/test_example.py
文件中的测试。
通过以上几种方式,你可以精准地运行指定的测试文件、测试类或测试方法。根据你的需求选择合适的方式来运行测试,可以提高测试的效率和准确性。