Pytest-grouping-the-tests

提供:Dev Guides
移動先:案内検索

Pytest-テストのグループ化

この章では、マーカーを使用してテストをグループ化する方法を学習します。

Pytestでは、テスト機能でマーカーを使用できます。 マーカーは、さまざまな機能/属性を設定して機能をテストするために使用されます。 Pytestは、xfail、skip、およびparametrizeなどの多くの組み込みマーカーを提供します。 それとは別に、ユーザーは独自のマーカー名を作成できます。 マーカーは、以下に示す構文を使用してテストに適用されます-

@pytest.mark.<markername>

マーカーを使用するには、テストファイルにpytestモジュールを*インポートする必要があります。 テストに対して独自のマーカー名を定義し、それらのマーカー名を持つテストを実行できます。

マークされたテストを実行するには、次の構文を使用できます-

pytest -m <markername> -v

-m <markername>は、実行するテストのマーカー名を表します。

テストファイル test_compare.py および test_square.py を次のコードで更新します。 3つのマーカーを定義しています* –すばらしい、正方形、その他*。

test_compare.py

import pytest
@pytest.mark.great
def test_greater():
   num = 100
   assert num > 100

@pytest.mark.great
def test_greater_equal():
   num = 100
   assert num >= 100

@pytest.mark.others
def test_less():
   num = 100
   assert num < 200

test_square.py

import pytest
import math

@pytest.mark.square
def test_sqrt():
   num = 25
   assert math.sqrt(num) == 5

@pytest.mark.square
def testsquare():
   num = 7
   assert 7*7 == 40

@pytest.mark.others
   def test_equality():
   assert 10 == 11

今*その他*としてマークされたテストを実行するには、次のコマンドを実行します-

pytest -m others -v

以下の結果を参照してください。 others とマークされた2つのテストを実行しました。

test_compare.py::test_less PASSED
test_square.py::test_equality FAILED
============================================== FAILURES
==============================================
___________________________________________ test_equality
____________________________________________
   @pytest.mark.others
   def test_equality():
>  assert 10 == 11
E  assert 10 == 11
test_square.py:16: AssertionError
========================== 1 failed, 1 passed, 4 deselected in 0.08 seconds
==========================

同様に、他のマーカーでもテストを実行できます。