【Python】単体試験 / pytest ~ 基本編 / Fixture ~

■ はじめに

https://dk521123.hatenablog.com/entry/2020/12/13/224810

の続き。

PyTest の Fixture(フィクスチャ)について、学ぶ。

目次

【1】Fixture(フィクスチャ)
【2】Scope(スコープ)
【3】サンプル

【1】Fixture(フィクスチャ)

* PyTest の 前処理 と 後処理
 => テスト前後のイベントハンドラ的なもの

使用用途

* テスト時の初期化・後処理

【2】Scope(スコープ)

* Fixture には、Scope という概念があり
 PyTest の 粒度を制御する。
# スコープ 説明
1 function テストケースごとに1回実行(デフォルト)
2 class テストクラス全体で1回実行
3 module テストファイル全体で1回実行
4 session テスト全体で1回だけ実行

【3】サンプル

フォルダ構成

project
 + project_a
    + hello.py
 + tests
    + test_hello.py

./project_a/hello.py (テスト対象)

class Hello:
  def __init__(self, name):
    self._name = name

  def say_hello(self, is_world=False):
    if is_world:
      return "Hello world!!"
    else:
      return f"Hello, {self._name}"

  def say_hi(self):
    return f"Hi, {self._name}"

./tests/test_hello.py (テストコード)

import pytest

from project_a.hello import Hello


@pytest.fixture(scope='function')
def fixture_function():
  print('function')

  # 初期化
  hello = Hello("Mike")
  return hello

@pytest.fixture(scope='class')
def fixture_class():
  print('class')

@pytest.fixture(scope='module')
def fixture_module():
    print('module')


@pytest.fixture(scope='session')
def fixture_session():
    print('session')

# フィクスチャを利用するテストケース
def test_say_hi(
    fixture_function,
    fixture_class,
    fixture_module,
    fixture_session):
    assert fixture_function.say_hi() == 'Hi, Mike'

def test_say_hello(
    fixture_function,
    fixture_class,
    fixture_module,
    fixture_session):
    assert fixture_function.say_hello() == 'Hello, Mike'


class TestHello:
  def test_say_hello_is_world_false(self,
    fixture_function,
    fixture_class,
    fixture_module,
    fixture_session):
    assert fixture_function.say_hello(False) == 'Hello, Mike'

  def test_say_hello_is_world_true(self,
    fixture_function,
    fixture_class,
    fixture_module,
    fixture_session):
    assert fixture_function.say_hello(True) == 'Hello world!!'

実行および出力結果

# オプション「-s」:print(標準出力)を出力
project/project_a>pytest -q ./tests/test_hello.py -s

session
module
class
function
.class
function
.class
function
.function
.
4 passed in 0.06s

参考文献

https://qiita.com/_akiyama_/items/9ead227227d669b0564e

関連記事

単体試験 / pytest ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2020/12/13/224810
単体試験 / pytest ~ 基本編 / pytest-mock ~
https://dk521123.hatenablog.com/entry/2021/11/25/131615