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

Pytest without arguments has wrong working directory

我正在尝试使用 pytest 来自动化我的测试过程。我在名为 test 的文件夹中有几个文件的测试用例(test_methodA.pytest_methodB.py 等),该文件夹本身位于我项目的顶级目录中。这些测试都是 运行ning 在单个文件中包含的程序上 - 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')

将解析您正在执行代码的目录的路径。这意味着当来自另一个目录的 运行ning 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:
    ...