gpt4 book ai didi

python - 没有参数的 Pytest 有错误的工作目录

转载 作者:行者123 更新时间:2023-12-04 16:00:04 25 4
gpt4 key购买 nike

我正在尝试使用 pytest 来自动化我的测试过程。我在名为 test_methodA.py 的文件夹中有几个文件的测试用例( test_methodB.pytest 等)。 ,它本身在我的项目的顶级目录中。这些测试都在包含在单个文件中的程序上运行 - program.py .此 program.py文件也在顶级目录中,文件夹中的配置文件也是如此confs它需要正常运行。

当我使用我的测试文件之一的参数从顶级目录运行 pytest 时:

$ pytest test/test_methodA.py

程序运行正常并通过测试。但是,如果我只运行 pytest 而不带参数:
$ pytest

我所有的测试都失败了,因为我的程序的初始化方法抛出了 FileNotFoundError尝试访问配置文件时。

我已经尝试过这种行为,并确定直接原因是 pytest 使用了不正确的工作目录(项目顶级目录上一级的目录)。例如,如果我这样做
$ cd test
$ pytest

所有的测试工作正常。我还通过打印其中一项测试来证实了这一点 os.getcwd()到控制台。

项目中涉及的目录不包含 __init__.py文件,我为此问题找到的大多数搜索结果都集中在该文件上。这个问题还有什么其他原因?

最佳答案

您的问题是在打开文件时使用相对路径:

open('file/path.yml', 'r')

将解析您正在执行代码的目录的路径。这意味着运行时 program.py来自另一个目录将导致 FileNotFoundError因为脚本将在错误的目录中查找配置文件。您可以通过更改目录并尝试运行脚本来轻松测试:
$ cd /tmp
$ python /path/to/program.py
Traceback (most recent call last):
File "/path/to/program.py", line 1, in <module>
with open('file/path.yaml') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'file/path.yaml'

您可以通过构建相对于 program.py 的路径来解决这个问题。脚本( __file__ 是正在执行的 python 文件的名称):
import os

parent_dir = os.path.dirname(__file__)
file = os.path.join(parent_dir, 'file', 'path.yaml')
with open(file, 'r') as fp:
...

如果您使用 Python 3.4 或更新版本,则使用 pathlib 更优雅地解析路径。 :
# program.py
import pathlib

parent_dir = pathlib.Path(__file__).parent
file = parent_dir / 'file' / 'path.yaml'

with file.open('r') as fp:
...

关于python - 没有参数的 Pytest 有错误的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50766119/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com