选项 A — 最小解决方案
在项目的根目录下,创建一个名为tests.py其中包含以下内容
import os, pathlib
import pytest
os.chdir( pathlib.Path.cwd() / 'Tests' )
pytest.main()
然后你可以使用命令python tests.py
运行测试。
选项 B — 使用批处理/bash 测试运行程序
对于那些喜欢使用batch/bash运行脚本的人,我们可以更改batch/bash中的目录,然后调用运行pytest框架的Python脚本。为此,请在项目文件夹中创建以下脚本。
test.bat(适用于 Windows)
@echo off
cd /d %~dp0Tests
python %~dp0Tests/runner.py %*
cd /d %~dp0
test.sh(对于Linux)
cd $PWD/Tests
python runner.py $@
cd $PWD
然后在 Tests 文件夹中创建一个名为跑步者.py与以下
import pathlib, sys
import pytest
cwd = pathlib.Path.cwd()
# Add the project's root directory to the system path
sys.path.append(str( cwd.parent ))
# This is optional, but you can add a lib directory
# To the system path for tests to be able to use
sys.path.append(str( cwd / 'lib' ))
pytest.main()
如果您的目录结构在 Tests 文件夹中包含某种类型的 lib 文件夹,我们可以通过创建一个pytest.ini配置文件包含以下内容。
[pytest]
norecursedirs = lib
在这种情况下,您的目录/文件结构最终将是:
root
├── test.bat
├── test.sh
├── Main
└── Tests
├── runner.py
├── pytest.ini # Optional pytest config file
├── lib # Optional, contains helper modules for the tests
├── tests # Tests go here
└── # Or, in the OPs case, you could also place all of your tests here
补充评论
上面的方法不是运行 pytest 的典型方法,但我更喜欢使用pytest.main()
因为它使我们能够:
- 有任何目录结构。
- 在测试运行程序启动之前执行代码。
- 您仍然可以传入命令行选项,它的行为与您运行
pytest
直接命令。