Aplicarea markerilor de test

Introducere în testarea în Python

Alexander Levin

Data Scientist

Prezentare generală a markerilor de test

  • Cazul de utilizare 1: omiterea testului dacă condiția este îndeplinită
  • Cazul de utilizare 2: testul este așteptat să eșueze

  • Marker de test - o etichetă a unui test din biblioteca pytest

  • Permite specificarea comportamentului pentru anumite teste prin etichetarea lor
Introducere în testarea în Python

Sintaxa markerilor

  • Decorator - un șablon de proiectare în Python care permite adăugarea de funcționalitate nouă unui obiect existent fără a-i modifica structura
  • Sintaxa markerilor de test începe cu decoratorul @pytest.mark:
import pytest

def get_length(string):
    return len(string)

# The test marker syntax
@pytest.mark.skip
def test_get_len():
    assert get_length('123') == 3
Introducere în testarea în Python

Markerii skip și skipif

  • Folosiți @pytest.mark.skip - când doriți ca un test să fie omis în orice situație
  • Folosiți @pytest.mark.skipif - când doriți ca un test să fie omis dacă o condiție dată este True
Introducere în testarea în Python

Exemplu marker skip

  • Folosiți @pytest.mark.skip - când doriți ca un test să fie omis necondiționat.
import pytest
def get_length(string):
    return len(string)

# The skip marker example
@pytest.mark.skip
def test_get_len():
    assert get_length('123') == 3
Introducere în testarea în Python

Exemplu marker skip: rezultat

  • Rezultatul cu un test omis:

Exemplu pytest.mark.skip

Introducere în testarea în Python

Exemplu marker skipif

  • Folosiți @pytest.mark.skipif - când doriți ca un test să fie omis dacă condiția dată este True.
import pytest
def get_length(string):
    return len(string)

# The skipif marker example
@pytest.mark.skipif('2 * 2 == 5')
def test_get_len():
    assert get_length('abc') == 3
Introducere în testarea în Python

Exemplu marker skipif: rezultat

  • Rezultatul unui test omis condiționat:

Exemplu pytest.mark.skipif

Introducere în testarea în Python

Markerul xfail

  • Folosiți @pytest.mark.xfail - când vă așteptați ca un test să eșueze
import pytest

def gen_sequence(n):
    return list(range(1, n+1))

# The xfail marker example
@pytest.mark.xfail
def test_gen_seq():
    assert gen_sequence(-1)
Introducere în testarea în Python

Markerul xfail: rezultat

  • Rezultatul unui test pentru care se așteaptă eșec:

Exemplu pytest.mark.xfail

Introducere în testarea în Python

Rezumat

Marker de test:

  • Este un atribut al unui test din biblioteca pytest
  • Specifică comportamentul pentru anumite teste
  • Sintaxa începe cu @pytest.mark.name_of_the_marker
  • Implementări predefinite în pytest:
    • @pytest.mark.xfail
    • @pytest.mark.skip
    • @pytest.mark.skipif
Introducere în testarea în Python

Să exersăm!

Introducere în testarea în Python

Preparing Video For Download...