🥒

pytest で Allure を使って AAA スタイルを書きやすくする

に公開

はじめに

pytest および Allure のインストール方法や基本的な使い方については、本記事には記載しません。

Arrange-Act-Assert スタイルでテストを書きたい

Arrange-Act-Assert (AAA) スタイルは、テストコードを読みやすく、理解しやすくするための一般的なテストの記述パターンです。以下の例のように、テストコード内に# Arrange: add items to shopping cartなどと「この部分で準備してますよ」とコメントで表現したりします。書かないよりは、書いた方が良いけど、より「ここからここまでが準備」などがわかりやすく書きたいですし、また、せっかく書くならテストコードを読む時以外にも利益があると嬉しいです。

def test_addition():
    # Arrange: define variables
    a = 1
    b = 2

    # Act
    result = a + b

    # Assert
    assert result == 3

Allure の導入

そこで導入したのが、Allure が提供する Test steps という機能です。本来、機能により、テストコードのデバックの容易性とテストレポートの可読性を向上させることが期待できます。
以下の例は、Allure の Test steps を使って、AAA スタイルのテストコードを書いたものです。

import allure

def test_addition():
    with allure.step("Arrange: define variables"):
        a = 1
        b = 2

    with allure.step("Act: calculate the sum of a and b"):
        result = a + b

    with allure.step("Assert: check if the result is correct"):
        assert result == 3

ここで、allure.step を用いて、テストコードを各ステップに分割しています。これにより、テストの各部分が明確になり、テストレポートでも各ステップが表示されるため、テストの流れを視覚的に把握しやすくなります。

一方で、allure.step を使って、with allure.step("Arrange: ..."):のように逐一記述するのは、面倒です。そこで、このallure.stepのAPIに少し手を加えることで、AAA スタイルのテストコードを書きやすくさせます。

allure.step の拡張

以下のように、allure.step を拡張して、AAA スタイルのテストコードを書きやすくします。

aaa.py
from contextlib import contextmanager

import allure


@contextmanager
def arrange(description: str):
    with allure.step(f"Arrange: {description}"):
        yield


@contextmanager
def act(description: str):
    with allure.step(f"Act: {description}"):
        yield


@contextmanager
def assertion(description: str):
    with allure.step(f"Assert: {description}"):
        yield

@contextlib.contextmanagerを使うことで、allure.stepのエイリアスを作成しています。これにより、with arrange("add items to shopping cart"):のように、AAA スタイルのテストコードを書くことができます。

from .aaa import arrange, act, assertion

def test_addition():
    with arrange("define variables"):
        a = 1
        b = 2
    with act("calculate the sum of a and b"):
        result = a + b
    with assertion("check if the result is correct"):
        assert result == 3

上記のようにテストコードがよりすっきりと書けるようになります。

ちなみに、allure.step の拡張として、Given-When-Then スタイル(Gherkinスタイル)でテストコードを書くこともできます。以下のように、allure.step の拡張を行います。

gherkin.py
from contextlib import contextmanager

import allure

@contextmanager
def given(description: str):
    with allure.step(f"Given: {description}"):
        yield

@contextmanager
def when(description: str):
    with allure.step(f"When: {description}"):
        yield

@contextmanager
def then(description: str):
    with allure.step(f"Then: {description}"):
        yield

テストレポートへの効果

Allure により出力されるレポートは以下のようになります。

screenshot ot report

なお、他のAllureのAPIを使うことで、よりレポート出力する情報を増やすこともできます。
Improving readability of your test reportsやImproving navigation in your test reportを参考にすると良いです。

おわりに

Allure の Test steps を使うことで、AAA スタイルのテストコードをより書きやすくする方法の紹介でした。これにより、テストコードの書きやすさと読みやすさを確保しつつ、テストレポートもより理解しやすくできます。

GitHubで編集を提案

Discussion