Open4

pytestのfixtureの使い方

snhr-1019snhr-1019

基本的な使い方

import pytest


class Sample:
    def __init__(self):
        self.message = "pytest sample"

@pytest.fixture(scope="function")
def foo() -> Sample:
    return Sample()

def test(foo: Sample): # 仮引数名と同名のfooメソッドが呼ばれる
    print(foo.message)  # -> pytest sample
snhr-1019snhr-1019

テストメソッドの仮引数との紐付け

逆にいうとタイプヒンティングを見ているわけではないので、型から特定できそうでも仮引数名とfixtureメソッド名が一致していなければエラー

import pytest


class Sample:
    def __init__(self):
        self.message = "pytest sample"

@pytest.fixture(scope="function")
def bar() -> Sample:
    return Sample()

def test(foo: Sample): # Error: fixture 'foo' not found
    print(foo.message)
snhr-1019snhr-1019

before_each, after_each的なことをしたい場合

returnではなくyieldを使う

import pytest


class Sample:
    def __init__(self):
        self.message = "pytest sample"

@pytest.fixture(scope="function")
def foo() -> Sample:
    print("before function")
    yield Sample()
    print("after function")

def test(foo: Sample):
    print(foo.message)
before function
pytest sample
after function

と表示される。

snhr-1019snhr-1019

conftest.pyに書くとfixtureを複数テスト横断で共有できる

fixtureはテストモジュール内で定義しても良いですが、複数のモジュールを横断して使用したいような場合は、conftest.pyにfixtureを定義することで、複数のモジュールを横断してfixtureを使用することができます。

conftest.pyはimportでの読み込みは不要で、自動的に読み込まれます。
conftest.pyは階層構造で処理され「conftest.pyが存在する階層を含むそれ以下の階層にしか適用されない」という特性があります。

https://zenn.dev/tk_resilie/articles/python_test_template#conftest.py