You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pytest未识别pytest.ini中注册的自定义标记问题排查

pytest自定义标记警告问题解决

项目目录结构

.
├── app
│   ├── __init__.py
│   ├── app.py
│   └── inner
│       └── __init__.py
├── pytest.ini
└── tests
    ├── __init__.py
    └── test_app.py

pytest.ini配置内容

[pytest]
markers =
    exception

测试用例代码

import pytest
import socket  # 需导入socket模块才能使用socket.gaierror()

@pytest.mark.exception(socket.gaierror())
def test_two_equals_two():
    assert 2 == 2

运行警告信息

PytestUnknownMarkWarning: Unknown pytest.mark.exception - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/how-to/mark.html
@pytest.mark.exception(socket.gaierror())

问题原因

  1. 你在pytest.ini中仅注册了无参数的exception标记,但测试用例里给标记传递了参数socket.gaierror(),pytest无法识别带参数的标记版本,因此抛出警告。
  2. 若注册无参数标记后仍出现警告,大概率是pytest.ini配置未生效——比如文件位置错误、格式缩进不规范,或是缓存干扰了配置加载。

解决办法

针对带参数标记的场景

要使用带参数的自定义标记,需在项目中创建conftest.py文件(推荐放在tests目录下),通过pytest钩子函数注册带参数的标记定义:

# tests/conftest.py
import pytest

def pytest_configure(config):
    # 注册带参数的exception标记,冒号后是标记说明(可选)
    config.addinivalue_line(
        "markers", "exception(exc): 标记测试用例关联特定异常"
    )

完成后再运行pytest -v,带参数的@pytest.mark.exception就不会触发警告。

针对无参数标记仍警告的场景

如果是注册无参数标记后仍报错,按以下步骤排查:

  • 确认pytest.ini放在项目根目录(和tests、app文件夹同级),pytest只会自动加载根目录的配置文件;
  • 检查pytest.ini中markers下的标记缩进是否正确(每行标记前用空格或制表符缩进,保持格式统一);
  • 清除pytest缓存后重试:执行命令 pytest --cache-clear -v。

内容的提问来源于stack exchange,提问作者Łukasz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 22:41:22