安装pytest

确保已安装Python环境(建议3.7+版本)。通过pip直接安装最新版pytest:

pip install -U pytest

验证安装是否成功:

pytest --version

创建项目结构

新建一个项目目录,建议按以下结构组织文件:

project/
├── src/               # 源代码目录(可选)
├── tests/             # 测试代码目录
│   ├── __init__.py    # 标识为Python包
│   └── test_sample.py # 示例测试文件
└── pytest.ini         # 配置文件(可选)

编写测试用例

在test_sample.py中编写简单测试:

def func(x):
    return x + 1

def test_answer():
    assert func(3) == 5  # 故意失败用例

运行测试

在项目根目录执行:

pytest

或指定具体测试文件:

pytest tests/test_sample.py

配置pytest(可选)

创建pytest.ini文件定制行为:

[pytest]
python_files = test_*.py
testpaths = tests
addopts = -v --color=yes

常用插件推荐

  1. pytest-cov: 测试覆盖率

    pip install pytest-cov
    pytest --cov=src
    
  2. pytest-xdist: 并行测试

    pip install pytest-xdist
    pytest -n 4
    
  3. pytest-html: 生成HTML报告

    pip install pytest-html
    pytest --html=report.html
    
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐