vscode-python 在错误的目录中运行 pytest,导致相对路径变得混乱

r-b*_*eer 10 python-3.x vscode-python

使用 pytest 和 vscode-python 我想运行之前使用 unittest 框架实现的测试。

因此,我在相应的目录中使用 pytest 成功运行了测试tests

pytest
Run Code Online (Sandbox Code Playgroud)

我还设置了 vscode-python 并成功测试了几乎所有测试。

但是,这些从子目录加载数据的测试tests/data会失败,因为 vscode-python 似乎从测试目录之外的另一个目录运行 pytest tests

abc/
|-- tests/
    |-- test_function.py
    |-- data/
Run Code Online (Sandbox Code Playgroud)

如何设置 vscode-python,以便成功读取已实施的测试中的所有数据文件?

GJo*_*Joe 12

导航到“设置”(在 macOS 上的 VS Code 1.35.0 中):

菜单“代码”>>“首选项”>>“设置”

在“设置”窗格中,搜索“python.testing.cwd”。

文档说“cwd”“为单元测试指定一个可选工作目录。”

对于您的设置,生成“python.testing.cwd”相对路径的一种方法是:

  1. 在 VS Code 编辑器中打开“abc/tests/data/”下的数据文件之一
  2. 右键单击编辑器中打开文件的选项卡,然后从下拉菜单中选择“复制相对路径”
  3. 将该相对路径粘贴到“python.testing.cwd”配置字段中(并在保存之前对其进行适当编辑)

或者,您可能想要研究使用一个或多个VS Code 变量指定路径。

参考:

  1. [ https://code.visualstudio.com/docs/python/unit-testing#_test-configuration-settings]
  2. [ https://code.visualstudio.com/docs/editor/variables-reference]