在共享仓库中锚定一个绝对路径到父目录。

问题描述 投票:0回答:1

我在一个共享的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,测试可以正确地找到数据。然而在共享的repo中却不能接受,因为绝对路径对我的系统来说是唯一的。 我试过使用相对路径,但Pycharm调用pytest的方式让我得到了一条 FileNotFound 除非我只从顶层的 test/ 目录。

哪些是首选的使用方式?Pathos.pathlib.abspath 模块,以便始终能够找到 sample_data.json 不管python3是从哪个目录调用的? 或者,换一种方式,你能动态地创建相对于项目根目录的绝对路径吗?

python-3.x pycharm pytest absolute-path
1个回答
1
投票

你可以直接使用你的 conftest.py 作为路径计算的基础(前提是相对于项目根的位置是固定的)。

conftest_path = Path(__file__)
data_path = conftest_path.parent.parent / 'data'
© www.soinside.com 2019 - 2024. All rights reserved.