pytest の fixture で関数を inject する方法

Published at: 2022/12/28


pytest で関数を inject したくなったときにどうしたら良いかについて、その方法3パターン。 どれがベストという話はあまり見当らなかったので、適当なものを利用すれば良さそう。

パターン1: ラムダを返す

@pytest.fixture
def multiply_by_2():
    return lambda n: n * 2

def test_multiply_by_2(multiply_by_2):
    assert multiply_by_2(3) == 6

パターン2: static method を持つクラスを helpers として返す

class Helpers:
    @staticmethod
    def multiply_by_2(n):
        return n * 2

    @staticmethod
    def multiply_by_3(n):
        return n * 3

@pytest.fixture
def helpers():
    return Helpers

def test_multiply_by_2(helpers):
    assert helpers.multiply_by_2(3) == 6

参考記事

python - Create and import helper functions in tests without creating packages in test directory using py.test - Stack Overflow

stackoverflow.com

パターン3: 関数内関数

@pytest.fixture
def multiply_by_2():
    def _multiply_by_2(n):
        return n * 2
    return _multiply_by_2

def test_multiply_by_2(multiply_by_2):
    assert multiply_by_2(3) == 6

Tags: pytestpython