メモの日々


2023年08月15日(火) [長年日記]

[python] pytestのパラメータ化テストでパラメータ名に日本語を使用する設定

pytestでParametrizing fixturesを使った次のテストを実行すると、パラメータの識別子として表示させたい日本語部分がエスケープされてしまった。

import pytest

data = [
    ("テスト", "データ1"),
    ("テスト", "データ2"),
    ("テスト", "データ3"),
]

def data_name(d):
    return f"{d[0]}-{d[1]}"

@pytest.fixture(params=data, ids=data_name)
def parameter(request):
    return request.param

def test_sample(parameter):
    assert True
$ pytest -v test_1.py
=============================== test session starts ===============================
platform linux -- Python 3.11.1, pytest-7.3.1, pluggy-1.0.0 -- /home/kenichi/.anyenv/envs/pyenv/versions/3.11.1/bin/python3.11
cachedir: .pytest_cache
rootdir: /home/kenichi/work/python/pytest
collected 3 items

test_1.py::test_sample[\u30c6\u30b9\u30c8-\u30c7\u30fc\u30bf1] PASSED       [ 33%]
test_1.py::test_sample[\u30c6\u30b9\u30c8-\u30c7\u30fc\u30bf2] PASSED       [ 66%]
test_1.py::test_sample[\u30c6\u30b9\u30c8-\u30c7\u30fc\u30bf3] PASSED       [100%]

================================ 3 passed in 0.01s ================================

調べると、

に次の説明があった。

pytest by default escapes any non-ascii characters used in unicode strings for the parametrization because it has several downsides. If however you would like to use unicode strings in parametrization and see them in the terminal as is (non-escaped), use this option in your pytest.ini:

[pytest]
disable_test_id_escaping_and_forfeit_all_rights_to_community_support = True

Keep in mind however that this might cause unwanted side effects and even bugs depending on the OS used and plugins currently installed, so use it at your own risk.

リスクはあるようだが、pytest.iniを用意してそこに上記の設定を書くことで、次のように日本語が表示されるようになった。

$ pytest -v test_1.py
=============================== test session starts ===============================
platform linux -- Python 3.11.1, pytest-7.3.1, pluggy-1.0.0 -- /home/kenichi/.anyenv/envs/pyenv/versions/3.11.1/bin/python3.11
cachedir: .pytest_cache
rootdir: /home/kenichi/work/python/pytest
configfile: pytest.ini
collected 3 items

test_1.py::test_sample[テスト-データ1] PASSED                               [ 33%]
test_1.py::test_sample[テスト-データ2] PASSED                               [ 66%]
test_1.py::test_sample[テスト-データ3] PASSED                               [100%]

================================ 3 passed in 0.01s ================================