Introduktion till testning i Python
Alexander Levin
Data Scientist
autouse=True körs fixture-funktionen oavsett om den efterfrågasNä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:
Alla sådana fall bör hanteras med "autouse"-argumentet.
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
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
Utdata från exemplet:

autouse: Ett valfritt booleskt argument till en fixture-dekorator@pytest.fixture(autouse=True)autouse=True kör fixture-funktionen oavsett om den efterfrågasIntroduktion till testning i Python