我正在使用 python pytest 来运行我的单元测试。 我的项目文件夹是:
Main
- 包含数据文件:A.txt
Main\Tests
- 我运行 pytest 的文件夹
Main\Tests\A_test
- 包含测试文件的文件夹
A_test 文件夹中的测试使用文件 A.txt
(位于 Main 文件夹中)。
我的问题是,当我运行 py.test 时,测试失败,因为它找不到 A.txt
。
我发现是因为pytest在运行测试时使用了路径Main\Test
,而不是将路径改为Main\Tests\A_test
(我是在测试文件中打开 A.txt
时使用相对路径)
我的问题:有没有办法让 pytest 将目录更改为它为每个测试执行的测试文件夹?这样测试中的相对路径仍然有效吗?
还有其他通用的方法可以解决吗? (我不想将所有内容都更改为绝对路径或类似的东西,这也是一个例子,在现实生活中我有数百个测试)。
谢谢,
诺姆
最佳答案
选项 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 文件夹中,使用以下内容创建一个名为 runner.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 忽略它。
[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
命令完全相同。
关于python - 在子文件夹中使用 pytest where test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47498390/