Fixtures autouse

Python में Testing का परिचय

Alexander Levin

Data Scientist

Autouse argument

  • किसी fixture का एक वैकल्पिक boolean argument
  • Fixture डेकोरेटर को पास किया जा सकता है
  • जब autouse=True हो, तो fixture फ़ंक्शन बिना अनुरोध के भी चलता है
  • फ़ालतू fixture कॉल्स कम करने में मदद करता है
Python में Testing का परिचय

कब उपयोग करें

जब हमें कुछ environment तैयारियाँ या बदलाव सभी tests पर लागू करने हों।

उदाहरण, जब हम यह सुनिश्चित करना चाहें कि सभी tests:

  • एक जैसा data रखें
  • समान connections हों (data, API, आदि)
  • एक जैसी environment configuration हो
  • monitor, logging, या profiling सक्षम हो

ऐसे सभी मामलों में "autouse" argument उपयोग करें।

Python में Testing का परिचय

Autouse उदाहरण

एक "autoused" fixture का उदाहरण:

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
Python में Testing का परिचय

Autouse गलत उदाहरण

गलत "autoused" fixture का उदाहरण:

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

सुधारा हुआ 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
Python में Testing का परिचय

Autouse उदाहरण: आउटपुट

उदाहरण का आउटपुट:

autouse example output

Python में Testing का परिचय

सारांश

  • autouse की परिभाषा: किसी fixture डेकोरेटर का वैकल्पिक boolean argument
  • उपयोग: @pytest.fixture(autouse=True)
  • फायदा: अनावश्यक fixture कॉल्स घटते हैं, कोड सरल होता है
  • विशेषता: autouse=True पर fixture फ़ंक्शन अनुरोध के बिना भी चलता है
  • कब उपयोग करें: जब कुछ environment तैयारियाँ या बदलाव लागू करने हों
  • उपयोग के उदाहरण:
    • सभी tests के लिए data पढ़ना और तैयार करना
    • connections और environment पैरामीटर्स कॉन्फ़िगर करना
    • monitor, logger, या profiler लागू करना
Python में Testing का परिचय

अभ्यास करते हैं!

Python में Testing का परिचय

Preparing Video For Download...