Pytest: Python में टेस्टिंग की संपूर्ण गाइड
Pytest का परिचय
सॉफ्टवेयर डेवलपमेंट में टेस्टिंग एक बेहद ज़रूरी हिस्सा है। अच्छे टेस्ट के बिना कोड की विश्वसनीयता और बदलावों के बाद उसकी स्थिरता सुनिश्चित करना मुश्किल है। Pytest एक आधुनिक, शक्तिशाली और उपयोग में आसान फ्रेमवर्क है जो Python में ऑटोमैटिक टेस्टिंग को बहुत सरल बनाता है।
Pytest ने अपने सरल सिंटैक्स, शानदार एक्सटेंशन क्षमताओं और मजबूत फिक्स्चर सिस्टम की वजह से डेवलपर्स के बीच काफी लोकप्रियता हासिल की है। यह मानक unittest मॉड्यूल की तुलना में उपयोग और टेस्ट डेवलपमेंट की गति में काफी बेहतर है।
Pytest की स्थापना और सेटअप
pip के माध्यम से इंस्टॉलेशन
pip install pytest
इंस्टॉलेशन की जाँच
pytest --version
पहला सरल टेस्ट
test_example.py नामक फ़ाइल बनाएँ:
def test_addition():
assert 2 + 2 == 4
def test_string_operations():
text = "Hello, World!"
assert "Hello" in text
assert len(text) == 13
टेस्ट चलाना
pytest
Pytest अपने आप सभी टेस्ट फ़ाइलों और फंक्शनों को ढूँढ लेगा जो नामकरण के नियमों का पालन करते हैं।
टेस्ट की संरचना और संगठन
नामकरण के नियम
Pytest टेस्ट को स्वचालित रूप से खोजने के लिए इन नियमों का उपयोग करता है:
- टेस्ट फ़ाइलें:
test_*.pyया*_test.py - टेस्ट फंक्शन:
def test_...() - टेस्ट क्लासेस:
class Test...(बिना__init__मेथड के) - क्लास में टेस्ट मेथड:
def test_...()
टेस्ट संरचना का आयोजन
project/
├── src/
│ ├── calculator.py
│ └── utils.py
├── tests/
│ ├── test_calculator.py
│ ├── test_utils.py
│ └── conftest.py
└── pytest.ini
विभिन्न पैरामीटर के साथ टेस्ट चलाना
# सभी टेस्ट चलाएँ
pytest
# किसी विशेष डायरेक्टरी में टेस्ट चलाएँ
pytest tests/
# किसी विशेष फ़ाइल को चलाएँ
pytest test_calculator.py
# किसी विशेष टेस्ट को चलाएँ
pytest test_calculator.py::test_add
# क्लास में टेस्ट चलाएँ
pytest test_calculator.py::TestCalculator
# क्लास के किसी विशेष मेथड को चलाएँ
pytest test_calculator.py::TestCalculator::test_multiply
टेस्ट लिखने की मूल बातें
जाँच के लिए assert का उपयोग
Pytest शर्तों की जाँच के लिए Python के मानक assert ऑपरेटर का उपयोग करता है:
def test_basic_assertions():
# समानता की जाँच
assert 2 + 2 == 4
# असमानता की जाँच
assert 3 * 3 != 8
# शामिल होने की जाँच
assert "Python" in "Python testing"
# डेटा प्रकार की जाँच
assert isinstance(42, int)
# सत्यता की जाँच
assert bool([1, 2, 3])
# असत्यता की जाँच
assert not bool([])
एक्सेप्शन का परीक्षण
import pytest
def divide(a, b):
if b == 0:
raise ValueError("Division by zero is not allowed")
return a / b
def test_division_by_zero():
with pytest.raises(ValueError):
divide(10, 0)
def test_exception_message():
with pytest.raises(ValueError, match="Division by zero"):
divide(10, 0)
def test_exception_type():
with pytest.raises(ZeroDivisionError):
1 / 0
क्लासेस में टेस्ट का आयोजन
class TestCalculator:
def test_addition(self):
assert 2 + 3 == 5
def test_subtraction(s