pytest文档41-参数化 ids 用例描述为中文时控制台输出unicode编码问题(pytest_collection_modifyitems)

前言

使用 pytest.mark.parametrize 参数化的时候,加 ids 参数用例描述有中文时,在控制台输出会显示unicode编码,中文不能正常显示。
使用 pytest_collection_modifyitems 钩子函数,对输出的 item.name 和 item.nodeid 重新编码。

问题描述

参数化 ids 用例描述有中文

import pytest


# test_ids.py
import pytest
# 作者:上海-悠悠


def login(username, password):
    '''登录'''
    # 返回
    return {"code": 0, "msg": "success!"}


# 测试数据
test_datas = [
    ({"username": "yoyo1", "password": "123456"}, "success!"),
    ({"username": "yoyo2", "password": "123456"}, "success!"),
    ({"username": "yoyo3", "password": "123456"}, "success!"),
]


@pytest.mark.parametrize("test_input,expected",
                         test_datas,
                         ids=[
                             "输入正确账号,密码,登录成功",
                             "输入错误账号,密码,登录失败",
                             "输入正确账号,密码,登录成功",
                         ]
                         )
def test_login(test_input, expected):
    '''测试登录用例'''
    # 获取函数返回结果
    result = login(test_input["username"], test_input["password"])
    # 断言
    assert result["msg"] == expected

cmd终端运行 pytest test_ids.py -v

注意 [\u8f93\u5165\u6b63 …] 这种不叫乱码,这叫 unicode 编码

pytest_collection_modifyitems

在项目的根目录写个 conftest.py 文件,加以下代码

def pytest_collection_modifyitems(items):
    """
    测试用例收集完成时,将收集到的item的name和nodeid的中文显示在控制台上
    :return:
    """
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        print(item.nodeid)
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")

cmd 控制台重新运行

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值