在子文件夹中使用 pytest where test

新手上路,请多包涵

我正在使用 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 将目录更改为它为每个测试执行的测试文件夹?这样测试中的相对路径仍然有效吗?

有没有其他通用的方法来解决它? (我不想将所有内容都更改为绝对路径或类似的东西,这也是一个例子,在现实生活中我有数百个测试)。

谢谢,

诺姆

原文由 Noam 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 733
2 个回答

好吧,我有点解决了,不确定这是最好的方法,但它正在工作:

在每个测试中:

  1. 我检查测试是从它的目录还是从 \Main\Tests
  2. 如果它是从 \Main\Tests 执行的,那么我 chdir\Main\Tests\A_test

我在 def setUpClass 方法下执行此操作。

例如:

 @classmethod
def setUpClass(cls):
    if (os.path.exists(os.path.join(os.curdir, "A_test"))):
        os.chdir("A_test")

这使得测试通过无论是从 Tests 文件夹(使用pytest)还是从 A_test 文件夹(通过pycharm)执行

原文由 Noam 发布,翻译遵循 CC BY-SA 3.0 许可协议

选项 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()

如果您的目录结构在您的测试文件夹中包含某种类型的 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 命令完全相同。

原文由 hostingutilities.com 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题