5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【初心者向け】【Pytest】フィクスチャは引数配置順に実行されることに気を付けよう

Last updated at Posted at 2023-08-16

初めに

冷静に考えると当然だけど、他のUnitテストフレームワークには無い要素なので記事化しました。

フィクスチャは引数配置の順番に実行される

今回例題とするコードはこんなものになります。

フィクスチャは引数配置順に実行されます。

そのためフィクスチャを利用するテストtestFixtureの引数をinit_strs, add_b順に並べるとフローチャート通りに実行されテストが通ります。

import pytest

strs: list[str] = ["A"]

@pytest.fixture
def init_strs():
    strs.clear()

@pytest.fixture
def add_b():
    strs.append("B")

def testFixture(init_strs, add_b):
    assert strs == ["B"]

しかしadd_b, init_strsの順に並べるとテストが通らなくなります。

フィクスチャの実行順が逆になり、先に文字列リストに「B」を入れて中身が空になります。

def testFixture(add_b, init_strs):
    assert strs == ["B"]
================================================================================================== FAILURES ================================================================================================== 
________________________________________________________________________________________________ testFixture _________________________________________________________________________________________________ 

add_b = None, init_strs = None

    def testFixture(add_b, init_strs):
>       assert strs == ["B"]
E       AssertionError: assert [] == ['B']
E         Right contains one more item: 'B'
E         Use -v to get more diff

test_main.py:18: AssertionError
------------------------------------------------------------------------------------------- Captured stdout setup -------------------------------------------------------------------------------------------- 
['A', 'B']
[]
========================================================================================== short test summary info =========================================================================================== 
FAILED test_main.py::testFixture - AssertionError: assert [] == ['B']
============================================================================================= 1 failed in 0.09s ==============================================================================================

最後に

他のUnitテストフレームワークではモック関数をテスト関数内で任意実行するのに対して、Pytestは引数配置順で自動実行されるため仕事で戸惑いました。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?