What is pytest-django and how does it compare to Django's built-in test runner? pytest-django क्या है और यह Django के बिल्ट-इन टेस्ट रनर से कैसे तुलना करता है?
Django's built-in test runner, based on unittest, requires tests as class methods inheriting from TestCase, with setup/teardown handled through class methods like setUp(). pytest-django is a plugin that lets you write Django tests using plain pytest functions and fixtures instead, which many teams find more concise and flexible.
Key advantages include pytest's powerful fixture system for reusable setup with explicit dependencies, parametrized tests (@pytest.mark.parametrize) for running the same test logic across many inputs without duplicated methods, better assertion introspection (detailed failure diffs without needing assertEqual variants), and access to the broader pytest plugin ecosystem (coverage, parallelization with pytest-xdist, etc.).
import pytest
@pytest.mark.django_db
def test_product_creation():
product = Product.objects.create(name="Phone", price=500)
assert product.name == "Phone"
@pytest.mark.parametrize("price,expected", [(0, False), (100, True)])
def test_is_valid_price(price, expected):
assert Product(price=price).is_valid_price() == expectedDjango का बिल्ट-इन टेस्ट रनर, जो unittest पर आधारित है, टेस्ट को TestCase से इनहेरिट करने वाले क्लास मेथड्स के रूप में चाहता है। pytest-django एक प्लगइन है जो आपको इसके बजाय सादे pytest फंक्शन्स और फिक्स्चर्स का उपयोग करके Django टेस्ट लिखने देता है।
मुख्य फायदों में pytest की शक्तिशाली फिक्स्चर प्रणाली, पैरामीट्राइज्ड टेस्ट (@pytest.mark.parametrize), बेहतर असर्शन इंट्रोस्पेक्शन, और व्यापक pytest प्लगइन इकोसिस्टम तक पहुँच शामिल है।
import pytest
@pytest.mark.django_db
def test_product_creation():
product = Product.objects.create(name="Phone", price=500)
assert product.name == "Phone"Was this answer clear?