pytestのfixtureの使い方(scope、yield、conftest.py)とfixture not foundの原因

Python
スポンサーリンク

pytestのfixtureの使い方を、scope(作られる回数)、yield(後始末)、conftest.py(共有と見える範囲)の3つに分けてまとめた記事です。fixtureに print を入れて実行し、いつ作られていつ後始末されるかを、実際の出力で確かめました。fixture 'xxx' not found のエラーが出る原因と直し方も載せています。

結論

fixtureは、最初に使うテストの前に作られ、scope で決まる範囲が終わったときに後始末されます。下の表の「今回作られた回数」は、2つのファイル(1つ目のファイルにクラスのテスト2つと関数のテスト1つ、2つ目のファイルに関数のテスト2つ)の、計5つのテストで実行した結果です。

scope後始末されるとき今回作られた回数
"function"(既定)テストが1つ終わるたび5回(テストの数)
"class"クラスの最後のテストが終わったとき1回(クラスの数。使ったのはクラスの中の2つのテストだけ)
"module"ファイル(モジュール)の最後のテストが終わったとき2回(ファイルの数)
"session"すべてのテストが終わったとき1回
  • yield の前が準備、後が後始末です。後始末は、テストが失敗しても動きました。複数のfixtureの後始末は、作ったときと逆の順番でした。yield の前で例外が出たfixtureは、自分の後始末が動きません(そのfixtureが使っていた別のfixtureの後始末は動きました)。
  • fixtureの print は、pytest -s で表示されます。-s がなくても、失敗したテストでは、準備・実行・後始末ごとの出力が表示されます。どのfixtureがいつ作られたかは、pytest --setup-show で一覧できます。
  • 広い scope のfixtureから、狭い scope のfixtureは使えません(ScopeMismatch のエラー)。
  • conftest.py のfixtureは、そのフォルダと下のフォルダのテストから、importなしで使えます。上のフォルダの conftest.py は見えますが、隣のフォルダの conftest.py は見えません。

fixture 'xxx' not found が出た原因と直し方です。どれも、今回実際にエラーを起こし、直して通ることを確かめました。

原因直し方
隣のフォルダの conftest.py で定義している両方のテストから見える、上のフォルダの conftest.py に移す
別のテストファイル(test_*.py)で定義している同じフォルダの conftest.py に移す
ファイル名が conftest.py になっていない(例: confest.py)ファイル名を conftest.py にする

エラーの available fixtures: に、そのテストから見えるfixtureが並びます。使いたいfixtureがそこにあるかを見ると、原因を絞れます。

動作確認した環境

  • Python 3.15.2(Dockerイメージ python:3.15.2-slim、x86_64)
  • pytest 9.2.0(依存するパッケージも版を固定。下の requirements.txt)
  • Docker 29.7.2(Windows 11 の Docker Desktop、Linuxコンテナの設定)
  • 確認日: 2026年11月16日

この記事は、MacとWindowsの両方の読者を対象にしています。pytestはDockerのコンテナの中で動かすので、OSで変わるのは、フォルダをコンテナに渡す docker run の書き方と、Git Bashで必要な設定だけです。この記事のコマンドは、Claude(AI)が実行して確認しました。本文の出力は、Windows 11 のGit Bashから上から順に実行した結果です。PowerShellで実行した結果は、最後の章に載せました。Macでは確認していません。

--setup-show の出力は、pytest 9.1 でテスト名の後に空白が入るように変わっています(pytestの変更履歴)。ほかの版では、出力の形が少し違うことがあります。

準備

空のフォルダに、pytestを入れたイメージを作るための2つのファイルを置きます。まず requirements.txt です。pytestと、pytestが使うパッケージの版を固定しています。

pytest==9.2.0
iniconfig==2.3.1
packaging==26.3
pluggy==1.7.0
Pygments==2.21.0

次に Dockerfile です。

FROM python:3.15.2-slim
COPY requirements.txt /tmp/requirements.txt
RUN pip install --no-cache-dir --root-user-action=ignore -r /tmp/requirements.txt
WORKDIR /work

イメージを作ります。このコマンドはMacとWindowsで同じです(出力は省略)。

docker build -t pytest-demo .

テストは、このフォルダをコンテナの /work に渡して実行します。WindowsのGit Bashで実行する場合は、先に export MSYS_NO_PATHCONV=1 を実行してください。Git Bashは、/work のような引数をWindowsのパスに変換することがあり、Dockerの公式ドキュメントでもこの設定が案内されています。本文の確認でも、Git Bashでこの設定をして実行しました。

Macのターミナル(zsh、bash)とWindowsのGit Bashでは、次のように書きます。

docker run --rm -v "$PWD:/work" pytest-demo pytest -v basic

WindowsのPowerShellでは、$PWD を ${PWD} にします。

docker run --rm -v "${PWD}:/work" pytest-demo pytest -v basic

以下では、$ の行に、Git Bash(Mac)の形で実行したコマンドを書きます。pytest から後ろは、PythonにpytestをインストールしてMacやWindowsで直接実行するときも同じです(この形では確認していません。pytest 9.2.0 はPython 3.10以上が必要です)。

fixtureの基本

@pytest.fixture をつけた関数がfixtureです。テストの関数の引数に、fixtureと同じ名前を書くと、pytestがfixtureを実行して、その戻り値を渡します。basic/test_basic.py です。

import pytest


@pytest.fixture
def user():
    print("\nuser を作る")
    return {"name": "alice"}


def test_rename(user):
    user["name"] = "bob"
    assert user["name"] == "bob"


def test_name(user):
    assert user["name"] == "alice"

-v は、テストの名前を1つずつ表示するオプションです。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest -v basic
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /usr/local/bin/python3.15
cachedir: .pytest_cache
rootdir: /work
collecting ... collected 2 items

basic/test_basic.py::test_rename PASSED                                  [ 50%]
basic/test_basic.py::test_name PASSED                                    [100%]

============================== 2 passed in 0.09s ===============================

fixtureの print は表示されません。pytestは、テスト中の出力を取り込んでいて、テストが成功したときは表示しないためです。-s(--capture=no の短縮形)をつけると表示されます。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest -v -s basic
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /usr/local/bin/python3.15
cachedir: .pytest_cache
rootdir: /work
collecting ... collected 2 items

basic/test_basic.py::test_rename 
user を作る
PASSED
basic/test_basic.py::test_name 
user を作る
PASSED

============================== 2 passed in 0.07s ===============================

「user を作る」が2回出ています。scope を指定しないfixtureは、テストごとに作り直されます。1つ目のテストで名前を bob に変えても、2つ目のテストには新しい {"name": "alice"} が渡されたので、2つ目のテストも通りました。

yieldで後始末する

return の代わりに yield を使うと、yield の後に後始末を書けます。テストには yield の値が渡り、テストが終わると yield の後が実行されます。yield_demo/test_yield.py では、user が db を使い、2つ目のテストはわざと失敗させています。

import pytest


@pytest.fixture
def db():
    print("\n[db] 接続する")
    yield "db"
    print("\n[db] 切断する")


@pytest.fixture
def user(db):
    print("\n[user] 作る")
    yield {"name": "alice"}
    print("\n[user] 消す")


def test_ok(user):
    print("\n[test_ok] 実行")
    assert user["name"] == "alice"


def test_fail(user):
    print("\n[test_fail] 実行")
    assert user["name"] == "bob"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest -v -s yield_demo
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /usr/local/bin/python3.15
cachedir: .pytest_cache
rootdir: /work
collecting ... collected 2 items

yield_demo/test_yield.py::test_ok 
[db] 接続する

[user] 作る

[test_ok] 実行
PASSED
[user] 消す

[db] 切断する

yield_demo/test_yield.py::test_fail 
[db] 接続する

[user] 作る

[test_fail] 実行
FAILED
[user] 消す

[db] 切断する


=================================== FAILURES ===================================
__________________________________ test_fail ___________________________________

user = {'name': 'alice'}

    def test_fail(user):
        print("\n[test_fail] 実行")
>       assert user["name"] == "bob"
E       AssertionError: assert 'alice' == 'bob'
E         
E         - bob
E         + alice

yield_demo/test_yield.py:25: AssertionError
=========================== short test summary info ============================
FAILED yield_demo/test_yield.py::test_fail - AssertionError: assert 'alice' =...
========================= 1 failed, 1 passed in 0.11s ==========================

出力から、次のことが分かります。

  • 準備は、使われる側の db が先で、user が後です。後始末は逆で、user が先、db が後です。
  • 失敗した test_fail の後でも、「消す」と「切断する」が出ています。テストが失敗しても、yield の後は実行されます。
  • 後始末の print は、PASSED や FAILED の後に出ます。

-s をつけなくても、失敗したテストの出力は表示される

同じテストを -s なしで実行すると、失敗したテストだけ、出力が準備(setup)、実行(call)、後始末(teardown)に分けて表示されました。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest yield_demo
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 2 items

yield_demo/test_yield.py .F                                              [100%]

=================================== FAILURES ===================================
__________________________________ test_fail ___________________________________

user = {'name': 'alice'}

    def test_fail(user):
        print("\n[test_fail] 実行")
>       assert user["name"] == "bob"
E       AssertionError: assert 'alice' == 'bob'
E         
E         - bob
E         + alice

yield_demo/test_yield.py:25: AssertionError
---------------------------- Captured stdout setup -----------------------------

[db] 接続する

[user] 作る
----------------------------- Captured stdout call -----------------------------

[test_fail] 実行
--------------------------- Captured stdout teardown ---------------------------

[user] 消す

[db] 切断する
=========================== short test summary info ============================
FAILED yield_demo/test_yield.py::test_fail - AssertionError: assert 'alice' =...
========================= 1 failed, 1 passed in 0.10s ==========================

yield の前で失敗すると、そのfixtureの後始末は動かない

fixtureの準備の途中(yield の前)で例外が出た場合です。setup_error/test_setup_error.py です。

import pytest


@pytest.fixture
def db():
    print("\n[db] 接続する")
    yield "db"
    print("\n[db] 切断する")


@pytest.fixture
def user(db):
    print("\n[user] 作る途中で失敗する")
    raise RuntimeError("user を作れなかった")
    yield {"name": "alice"}
    print("\n[user] 消す")


def test_error(user):
    print("\n[test_error] 実行")
$ docker run --rm -v "$PWD:/work" pytest-demo pytest -v -s setup_error
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /usr/local/bin/python3.15
cachedir: .pytest_cache
rootdir: /work
collecting ... collected 1 item

setup_error/test_setup_error.py::test_error 
[db] 接続する

[user] 作る途中で失敗する
ERROR
[db] 切断する


==================================== ERRORS ====================================
_________________________ ERROR at setup of test_error _________________________

db = 'db'

    @pytest.fixture
    def user(db):
        print("\n[user] 作る途中で失敗する")
>       raise RuntimeError("user を作れなかった")
E       RuntimeError: user を作れなかった

setup_error/test_setup_error.py:14: RuntimeError
=========================== short test summary info ============================
ERROR setup_error/test_setup_error.py::test_error - RuntimeError: user を作れ...
=============================== 1 error in 0.12s ===============================

テストは実行されず、結果は FAILED ではなく ERROR(準備での失敗)になりました。user の「消す」は出ていませんが、準備が終わっていた db の「切断する」は出ています。pytestの公式ドキュメントでも、yield の前で例外が出たfixtureは後始末が実行されず、すでに準備が終わったほかのfixtureは通常どおり後始末される、と説明されています。1つのfixtureで状態を変える操作を2つ以上すると、途中で失敗したときに前の操作が片付かないので、公式ドキュメントでは、状態を変える操作を1つのfixtureに1つずつにする形がすすめられています。

scopeで作られる回数を変える

@pytest.fixture(scope="module") のように scope を指定すると、fixtureを作り直す範囲が変わります。scope ごとに1つずつfixtureを作り、作った回数を表示するようにしました。fixtureは scope/conftest.py に置きます(conftest.py は後の章で説明します。ここでは、同じフォルダの2つのテストファイルから使うために置いています)。

import pytest

count = {"session": 0, "module": 0, "class": 0, "function": 0}


def make(scope):
    count[scope] += 1
    n = count[scope]
    print(f"\n[{scope}] 作る({n}回目)")
    return n


@pytest.fixture(scope="session")
def session_fx():
    n = make("session")
    yield n
    print(f"\n[session] 後始末({n}回目)")


@pytest.fixture(scope="module")
def module_fx():
    n = make("module")
    yield n
    print(f"\n[module] 後始末({n}回目)")


@pytest.fixture(scope="class")
def class_fx():
    n = make("class")
    yield n
    print(f"\n[class] 後始末({n}回目)")


@pytest.fixture
def function_fx():
    n = make("function")
    yield n
    print(f"\n[function] 後始末({n}回目)")

scope/test_a.py には、クラスのテストを2つと、関数のテストを1つ書きます。class_fx を使うのはクラスのテストだけです。

class TestA:
    def test_a1(self, session_fx, module_fx, class_fx, function_fx):
        pass

    def test_a2(self, session_fx, module_fx, class_fx, function_fx):
        pass


def test_a3(session_fx, module_fx, function_fx):
    pass

scope/test_b.py には、関数のテストを2つ書きます。

def test_b1(session_fx, module_fx, function_fx):
    pass


def test_b2(session_fx, module_fx, function_fx):
    pass
$ docker run --rm -v "$PWD:/work" pytest-demo pytest -v -s scope
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0 -- /usr/local/bin/python3.15
cachedir: .pytest_cache
rootdir: /work
collecting ... collected 5 items

scope/test_a.py::TestA::test_a1 
[session] 作る(1回目)

[module] 作る(1回目)

[class] 作る(1回目)

[function] 作る(1回目)
PASSED
[function] 後始末(1回目)

scope/test_a.py::TestA::test_a2 
[function] 作る(2回目)
PASSED
[function] 後始末(2回目)

[class] 後始末(1回目)

scope/test_a.py::test_a3 
[function] 作る(3回目)
PASSED
[function] 後始末(3回目)

[module] 後始末(1回目)

scope/test_b.py::test_b1 
[module] 作る(2回目)

[function] 作る(4回目)
PASSED
[function] 後始末(4回目)

scope/test_b.py::test_b2 
[function] 作る(5回目)
PASSED
[function] 後始末(5回目)

[module] 後始末(2回目)

[session] 後始末(1回目)


============================== 5 passed in 0.11s ===============================
  • function: テストごとに作られ、5回になりました。
  • class: TestA の2つのテストで1回だけ作られ、test_a2 の後に後始末されました。
  • module: ファイルごとに作られ、2回になりました。test_a.py の最後のテストの後に後始末され、test_b.py の最初のテストの前に2回目が作られています。
  • session: 全体で1回だけ作られ、最後のテストの後に後始末されました。

引数に書いた順番(session_fx, module_fx, ...)と関係なく、pytestの公式ドキュメントでは、1つのテストが使うfixtureは、広い scope のものから先に作られると説明されています。今回の出力も、session、module、class、functionの順でした。公式ドキュメントでは、ほかに "package"(パッケージのフォルダごと)もありますが、今回は確かめていません。

–setup-show で作られた順番を一覧する

print を入れなくても、--setup-show をつけると、fixtureの準備(SETUP)と後始末(TEARDOWN)が表示されます。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest --setup-show scope
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 5 items

scope/test_a.py 
SETUP    S session_fx
    SETUP    M module_fx
      SETUP    C class_fx
        SETUP    F function_fx
        scope/test_a.py::TestA::test_a1 (fixtures used: class_fx, function_fx, module_fx, session_fx) .
        TEARDOWN F function_fx
        SETUP    F function_fx
        scope/test_a.py::TestA::test_a2 (fixtures used: class_fx, function_fx, module_fx, session_fx) .
        TEARDOWN F function_fx
      TEARDOWN C class_fx
        SETUP    F function_fx
        scope/test_a.py::test_a3 (fixtures used: function_fx, module_fx, session_fx) .
        TEARDOWN F function_fx
    TEARDOWN M module_fx
scope/test_b.py 
    SETUP    M module_fx
        SETUP    F function_fx
        scope/test_b.py::test_b1 (fixtures used: function_fx, module_fx, session_fx) .
        TEARDOWN F function_fx
        SETUP    F function_fx
        scope/test_b.py::test_b2 (fixtures used: function_fx, module_fx, session_fx) .
        TEARDOWN F function_fx
    TEARDOWN M module_fx
TEARDOWN S session_fx

============================== 5 passed in 0.12s ===============================

S、M、C、F は、scope の頭文字(session、module、class、function)です(pytestのソースで、scope の名前の1文字目を大文字にして表示しています)。字下げは scope の広さに合わせて深くなり、テストの行の (fixtures used: ...) に、そのテストが使ったfixtureが並びます。行の最後の . は、テストが通ったことを表します。

広いscopeのfixtureから狭いscopeのfixtureは使えない(ScopeMismatch)

fixtureの引数にも、ほかのfixtureを書けます。ただし、session のfixtureから function のfixtureを使うと、エラーになります。mismatch/test_mismatch.py です。

import pytest


@pytest.fixture
def user():
    return {"name": "alice"}


@pytest.fixture(scope="session")
def client(user):
    return f"client for {user['name']}"


def test_client(client):
    assert client == "client for alice"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest mismatch
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 1 item

mismatch/test_mismatch.py E                                              [100%]

==================================== ERRORS ====================================
________________________ ERROR at setup of test_client _________________________
ScopeMismatch: You tried to access the function scoped fixture user with a session scoped request object. Requesting fixture stack:
mismatch/test_mismatch.py:9:  def client(user)
Requested fixture:
mismatch/test_mismatch.py:4:  def user()
=========================== short test summary info ============================
ERROR mismatch/test_mismatch.py::test_client - Failed: ScopeMismatch: You tri...
=============================== 1 error in 0.08s ===============================

client は全体で1つだけ作られるのに、user はテストごとに作り直されるので、組み合わせられません。公式ドキュメントでも、広い scope のfixtureを使うのはよいが、逆はできない、と説明されています。使われる側の user を @pytest.fixture(scope="session") にすると、通りました。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest mismatch
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 1 item

mismatch/test_mismatch.py .                                              [100%]

============================== 1 passed in 0.09s ===============================

反対に、client の scope="session" を外して、両方をテストごとに作る直し方もあります(こちらは確かめていません)。どちらにするかは、作り直すと困るもの(時間のかかる接続など)かどうかで決めます。

conftest.pyでfixtureを共有する

fixtureを conftest.py という名前のファイルに書くと、importしなくても、同じフォルダと下のフォルダのテストから使えます。次のようにファイルを置きました。

share/
├── conftest.py        db を定義
├── api/
│   ├── conftest.py    api_client を定義
│   └── test_api.py
└── web/
    └── test_web.py

share/conftest.py です。

import pytest


@pytest.fixture
def db():
    return "test-db"

share/api/conftest.py です。上のフォルダの db を使っています。

import pytest


@pytest.fixture
def api_client(db):
    return f"api-client({db})"

share/api/test_api.py です。

def test_api(db, api_client):
    assert api_client == "api-client(test-db)"

share/web/test_web.py です。web のテストからも api_client を使おうとしています。

def test_web_db(db):
    assert db == "test-db"


def test_web_api(api_client):
    assert api_client == "api-client(test-db)"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest share
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 3 items

share/api/test_api.py .                                                  [ 33%]
share/web/test_web.py .E                                                 [100%]

==================================== ERRORS ====================================
________________________ ERROR at setup of test_web_api ________________________
file /work/share/web/test_web.py, line 5
  def test_web_api(api_client):
E       fixture 'api_client' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, db, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

/work/share/web/test_web.py:5
=========================== short test summary info ============================
ERROR share/web/test_web.py::test_web_api
========================== 2 passed, 1 error in 0.17s ==========================

api のテストは、上の share/conftest.py の db と、同じフォルダの api_client の両方を使えました。web のテストは、上の db は使えました(available fixtures: に db があります)が、隣の api フォルダの api_client は見つかりませんでした。公式ドキュメントでも、テストはfixtureを上のフォルダへ向かって探し、下(や隣)のフォルダは探さない、と説明されています。available fixtures: のほかの名前は、pytestに最初から入っているfixtureです。

エラーの最後にあるように、pytest --fixtures にフォルダを指定すると、そこから見えるfixtureを一覧できます。下は、share/web を指定したときの出力の最後の部分です(前半の、pytestに最初から入っているfixtureの説明は省略しました)。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest --fixtures share/web
(省略)
------------------------ fixtures defined from conftest ------------------------
db -- share/conftest.py:4
    no docstring available


============================ no tests ran in 0.09s =============================

web からも api_client を使うなら、両方から見える share/conftest.py に移します。share/api/conftest.py は消し、share/conftest.py を次のようにしました。

import pytest


@pytest.fixture
def db():
    return "test-db"


@pytest.fixture
def api_client(db):
    return f"api-client({db})"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest share
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 3 items

share/api/test_api.py .                                                  [ 33%]
share/web/test_web.py ..                                                 [100%]

============================== 3 passed in 0.16s ===============================

fixture ‘xxx’ not found のほかの原因

隣のフォルダの conftest.py のほかに、次の2つでも同じエラーになりました。

別のテストファイルで定義したfixtureを使っている

other_file/test_login.py で定義した token を、同じフォルダの other_file/test_logout.py から使う例です。まず test_login.py です。

import pytest


@pytest.fixture
def token():
    return "dummy-token"


def test_login(token):
    assert token == "dummy-token"

次に test_logout.py です。

def test_logout(token):
    assert token == "dummy-token"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest other_file
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 2 items

other_file/test_login.py .                                               [ 50%]
other_file/test_logout.py E                                              [100%]

==================================== ERRORS ====================================
________________________ ERROR at setup of test_logout _________________________
file /work/other_file/test_logout.py, line 1
  def test_logout(token):
E       fixture 'token' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

/work/other_file/test_logout.py:1
=========================== short test summary info ============================
ERROR other_file/test_logout.py::test_logout
========================== 1 passed, 1 error in 0.13s ==========================

テストファイルに書いたfixtureは、そのファイルのテストからは使えますが、ほかのテストファイルからは見えません。token の定義を test_login.py から消し、other_file/conftest.py に移すと、両方のテストが通りました。

import pytest


@pytest.fixture
def token():
    return "dummy-token"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest other_file
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 2 items

other_file/test_login.py .                                               [ 50%]
other_file/test_logout.py .                                              [100%]

============================== 2 passed in 0.11s ===============================

ファイル名が conftest.py になっていない

typo/ フォルダに、token を定義したファイルを confest.py(t が1つ足りない)という名前で置き(中身は上の other_file/conftest.py と同じ)、typo/test_typo.py から使った例です。

def test_typo(token):
    assert token == "dummy-token"
$ docker run --rm -v "$PWD:/work" pytest-demo pytest typo
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 1 item

typo/test_typo.py E                                                      [100%]

==================================== ERRORS ====================================
_________________________ ERROR at setup of test_typo __________________________
file /work/typo/test_typo.py, line 1
  def test_typo(token):
E       fixture 'token' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, capteesys, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, subtests, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

/work/typo/test_typo.py:1
=========================== short test summary info ============================
ERROR typo/test_typo.py::test_typo
=============================== 1 error in 0.09s ===============================

confest.py は、pytestが自動で読み込む conftest.py でも、テストファイル(既定では test_*.py か *_test.py)でもないので、読み込まれず、中身が正しくても使われません。ファイル名を conftest.py に直すと通りました。

$ docker run --rm -v "$PWD:/work" pytest-demo pytest typo
============================= test session starts ==============================
platform linux -- Python 3.15.2, pytest-9.2.0, pluggy-1.7.0
rootdir: /work
collected 1 item

typo/test_typo.py .                                                      [100%]

============================== 1 passed in 0.09s ===============================

WindowsのPowerShellで実行する場合

Windows 11 のPowerShell 7.6 から、同じ docker build と、pytest -v -s scope、pytest share を実行しました。ファイルの改行はCRLF(Windowsのエディタで保存したとき)にして試しています。ビルドは通り、2つのコマンドの出力は、実行時間を除いて本文と同じでした。conftest.py のエラーの部分です。

PS> docker run --rm -v "${PWD}:/work" pytest-demo pytest share
(省略)
share/api/test_api.py .                                                  [ 33%]
share/web/test_web.py .E                                                 [100%]

==================================== ERRORS ====================================
________________________ ERROR at setup of test_web_api ________________________
file /work/share/web/test_web.py, line 5
  def test_web_api(api_client):
E       fixture 'api_client' not found
(省略)
========================== 2 passed, 1 error in 0.21s ==========================

Windows PowerShell 5.1 と、Macのターミナルでは確認していません。Macでも同じ docker のコマンドを使う想定です。

参考

スポンサーリンク
Python
スポンサーリンク
シェアする
hayoをフォローする

コメント

タイトルとURLをコピーしました