Fixtures autouse

Introduktion till testning i Python

Alexander Levin

Data Scientist

Autouse-argumentet

  • Ett valfritt booleskt argument till en fixture
  • Kan skickas till fixture-dekoratorn
  • När autouse=True körs fixture-funktionen oavsett om den efterfrågas
  • Minskar antalet redundanta fixture-anrop
Introduktion till testning i Python

När ska det användas

När vi behöver tillämpa vissa miljöförberedelser eller ändringar för alla tester.

Till exempel när vi vill garantera att alla tester:

  • Har samma data
  • Har samma anslutningar (data, API m.m.)
  • Har samma miljökonfiguration
  • Har en monitor, loggning eller profilering

Alla sådana fall bör hanteras med "autouse"-argumentet.

Introduktion till testning i Python

Autouse-exempel

Exempel på en fixture med "autouse":

import pytest
import pandas as pd

# Autoused fixture
@pytest.fixture(autouse=True)
def set_pd_options():
    pd.set_option('display.max_columns', 5000)

# Test function
def test_pd_options():
    assert pd.get_option('display.max_columns') == 5000
Introduktion till testning i Python

Felaktigt autouse-exempel

Felaktigt exempel på en fixture med "autouse":

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture(autouse=True)
def wrong_fixture():
    return [1,2,3,4,5]

# Test function
def test_type():
    assert type(wrong_fixture) == list

Korrigerat exempel på fixture:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture
def correct_fixture():
    return [1,2,3,4,5]

# Test function
def test_type(correct_fixture):
    assert type(correct_fixture) == list
Introduktion till testning i Python

Autouse-exempel: utdata

Utdata från exemplet:

autouse-exempelns utdata

Introduktion till testning i Python

Sammanfattning

  • Definition av autouse: Ett valfritt booleskt argument till en fixture-dekorator
  • Användning: @pytest.fixture(autouse=True)
  • Fördel: Minskar antalet redundanta fixture-anrop och gör koden enklare
  • Egenskap: autouse=True kör fixture-funktionen oavsett om den efterfrågas
  • När ska det användas: när vi behöver tillämpa vissa miljöförberedelser eller ändringar
  • Användningsexempel:
    • Läsa och förbereda data för alla tester
    • Konfigurera anslutningar och miljöparametrar
    • Implementera en monitor, logger eller profilerare
Introduktion till testning i Python

Nu kör vi en övning!

Introduktion till testning i Python

Preparing Video For Download...