pytest 找不到文件?直接在 pytest.ini 配置根目录 + 路径(最简单方案)

在 pytest.ini 里配置项目根目录 / 路径,让 pytest 执行用例时永远能找到文件 ,pytest 专用、最标准、最省事的配置方法,不用自己写复杂代码!

一、核心结论

✅ pytest.ini 可以配置项目根目录、测试数据目录、报告目录等所有路径 ✅ 配置后,无论在哪执行 pytest,都不会报 FileNotFound✅ 不用写死绝对路径,自动适配所有电脑


二、最简可用:pytest.ini 完整配置

直接在你项目根目录 创建 / 修改 pytest.ini:

ini

复制代码
[pytest]
# 1. 配置项目根目录(自动识别,不用改)
pythonpath = .
# 2. 自定义你的测试文件根路径(可写多个)
test_data_path = data
report_path = reports
case_path = test_cases

# 其他 pytest 基础配置(可保留)
addopts = -v
testpaths = test_cases

这三行就是关键!

ini

复制代码
pythonpath = .                # 把项目根目录加入 Python 路径
test_data_path = data         # 测试数据文件夹
report_path = reports         # 报告文件夹
case_path = test_cases        # 用例文件夹

三、Python /pytest 中读取 pytest.ini 里的路径

直接用pytest 内置配置读取,任何测试用例里都能用:

python

运行

复制代码
import pytest
import os

# 读取 pytest.ini 中的路径
def test_demo():
    # 1. 获取项目根目录
    root_dir = os.getcwd()  # 因为配置了 pythonpath = . 所以永远正确
    
    # 2. 读取 pytest.ini 里自定义的路径
    data_dir = pytest.config.getini("test_data_path")
    report_dir = pytest.config.getini("report_path")

    # 3. 拼接绝对路径(永远不会找不到文件)
    data_file = os.path.join(root_dir, data_dir, "test.xlsx")

    print("文件路径:", data_file)

用法示例(再也不会错)

python

运行

复制代码
# 读取 data 目录下的文件 → 100% 找到
file = os.path.join(os.getcwd(), pytest.config.getini("test_data_path"), "user.json")
with open(file) as f:
    data = f.read()

四、最关键的一行(解决 99% 路径错误)

ini

复制代码
[pytest]
pythonpath = .

作用: 把项目根目录 加入 Python 搜索路径无论你在哪个子目录执行 pytest 命令os.getcwd() 永远 = 项目根目录所有相对路径直接生效


五、你的项目结构推荐(标准结构)

plaintext

复制代码
你的项目/
├─ pytest.ini       # 配置文件
├─ test_cases/      # 用例
├─ data/            # 测试数据
└─ reports/         # 报告

配置后执行:

bash

运行

复制代码
pytest

所有文件都能找到!


六、终极万能方案(复制即用)

1. pytest.ini

ini

复制代码
[pytest]
pythonpath = .
test_data = data
report = reports
testpaths = test_cases
addopts = -v --alluredir=reports

2. conftest.py(pytest 全局文件)

python

运行

复制代码
import os
import pytest

@pytest.fixture(scope="session")
def project_root():
    """项目根目录"""
    return os.getcwd()

@pytest.fixture(scope="session")
def data_path(project_root):
    """测试数据路径"""
    data_dir = pytest.config.getini("test_data")
    return os.path.join(project_root, data_dir)

3. 测试用例中使用

python

运行

复制代码
def test_read_file(data_path):
    file_path = os.path.join(data_path, "test.json")
    with open(file_path, "r") as f:
        data = f.read()
    assert data is not None

总结(你只需要记住 2 步)

  1. pytest.ini 加一行:pythonpath = .
  2. 用 os.getcwd() 获取项目根目录
  3. 所有文件路径 = 根目录 + 相对路径(永不报错)
相关推荐
卷无止境25 分钟前
mathmodel-figure-templates 以及两个上手案例
后端·python
fengci.33 分钟前
CTF2MISC中等部分
开发语言·前端·学习
锋行天下1 小时前
服务器 Python 2.7 装不了 langgraph-cli?用本地生成 Dockerfile 曲线救国
人工智能·后端·python
一条大祥脚1 小时前
深入理解 PyTorch FlexAttention:从 Score Mod 到 Mask Mod 的稀疏加速之道
人工智能·pytorch·python·注意力机制·flex attention·可编程注意力
xys_6782 小时前
JavaEE通关手册:初识Java
java·开发语言
2601_967980112 小时前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
长沙三为智能科技3 小时前
GEO与传统SEO的5个关键差异:排名与被引用、关键词与答案型的全维度对比
python·aigc·seo·ai搜索·geo优化
ShineWinsu3 小时前
对于Qt:QTableWidget常见属性以及QTableWidgetItem类的解析
开发语言·c++·qt·gui·客户端·表格·qtablewidget
量化分析码农4 小时前
【Python量化趋势跟踪实战 02】突破买入总被假突破坑:通道系统与入场时机
python
Agent世界4 小时前
多平台登录态巡检:cookie 判据为什么会撒谎
python