Pytest - Raggruppamento dei test
In questo capitolo impareremo come raggruppare i test usando i marcatori.
Pytest ci consente di utilizzare i marker sulle funzioni di test. I marcatori vengono utilizzati per impostare varie caratteristiche / attributi per testare le funzioni. Pytest fornisce molti marcatori integrati come xfail, skip e parametrize. Oltre a ciò, gli utenti possono creare i propri nomi di marker. I marcatori vengono applicati sui test utilizzando la sintassi indicata di seguito:
@pytest.mark.<markername>Per usare i marker, dobbiamo import pytestmodulo nel file di test. Possiamo definire i nostri nomi di marker per i test ed eseguire i test con quei nomi di marker.
Per eseguire i test contrassegnati, possiamo utilizzare la seguente sintassi:
pytest -m <markername> -v-m <markername> rappresenta il nome del marker dei test da eseguire.
Aggiorna i nostri file di prova test_compare.py e test_square.pycon il seguente codice. Stiamo definendo 3 marker– great, square, others.
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 < 200test_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 == 11Ora per eseguire i test contrassegnati come others, esegui il seguente comando:
pytest -m others -vVedi il risultato sotto. Ha eseguito i 2 test contrassegnati comeothers.
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
==========================Allo stesso modo, possiamo eseguire test anche con altri marker: ottimo, confronta