在共享仓库中锚定父目录的绝对路径

anchoring an absolute path to parent directory in shared repo

我正在处理共享存储库并通过 pycharm 使用 pytest 并且有一个看起来像这样的测试目录结构:

├── data
│   ├── sample_data.json
│   ├── real_data.json
│   └── __init__.py
├── my_project
│   ├── __init__.py
│   └── main.py
└── tests
    ├── conftest.py
    ├── test0.py
    ├── test_class1
    │   ├── __init__.py
    │   ├── test1.py
    │   ├── test2.py
    │   └── test3.py
    └── test_class2
        ├── __init__.py
        ├── test4.py
        ├── test5.py
        └── test6.py

我的 conftest 使用如下方式传播样本数据:

# conftest.py
from pathlib import Path

data_path = Path("/home/myusername/projects/my_project/data") # the problem line
sample_data = data_path.joinpath("sample_data.json") # json filetype is irrelevant

propagate_data(sample_data)

这很好用,允许我从测试目录的任何级别调用 pytest,并且测试可以正确找到数据。但是,它在共享仓库中是不可接受的,因为绝对路径对我的系统来说是唯一的。我试过使用相对路径,但是 Pycharm 调用 pytest 的方式我得到一个 FileNotFound 除非我只从顶级 test/ 目录进行 运行 测试。

无论从哪个目录调用 python3,使用 Pathos.pathlib.abspath 模块始终能够找到 sample_data.json 的首选方法是什么?或者,换句话说,您可以动态创建相对于项目根目录的绝对路径吗?

您可以只使用您的 conftest.py 位置作为路径计算的基础(前提是它的位置相对于项目根目录是固定的):

conftest_path = Path(__file__)
data_path = conftest_path.parent.parent / 'data'