Django में Testing का परिचय
Django को automated tests क्यों चाहिए
जैसे-जैसे एक project बढ़ता है, हर change के बाद manually हर page पर click करके जाना impossible हो जाता है। Automated tests सेकंडों में चलते हैं और आपके लिए behavior जांचते हैं, इसलिए bugs deployment से पहले पकड़े जाते हैं, बाद में नहीं।
उदाहरण: Why Django needs automated tests
As a project grows, it becomes impossible to manually click through every page after every change. Automated tests run in seconds and check behavior for you, so bugs are caught before deployment instead of after.
python manage.py test
⚠️ Run this in your own terminal or Node.js environment.
Tests कहां रहते हैं
एक नया बनाया गया Django app एक tests.py file के साथ आता है। बड़े apps अक्सर इसे कई files वाले एक tests/ package से replace करते हैं, लेकिन Django का test runner दोनों को अपने आप discover करता है जब तक file और method names test से शुरू हों।
उदाहरण: Where tests live
startapp scaffolds tests.py automatically inside every new app — cat prints its default starting content, ready for you to add test classes to.
python manage.py startapp myapp
cat myapp/tests.py
⚠️ Run this in your own terminal or Node.js environment.
एक test क्या जांचता है
एक test आपके code के किसी part को known input के साथ call करता है और assert करता है कि output वही है जो आपने expect किया। अगर assertion fail हो, test runner exactly report करता है कि कौन सा test टूटा और क्यों।
उदाहरण: What a test checks
A test calls some part of your code with known input and asserts the output matches what you expect. If the assertion fails, the test runner reports exactly which test broke and why.
from django.test import TestCase
class MathCheckTests(TestCase):
def test_addition_is_correct(self):
self.assertEqual(2 + 2, 4)
{# Django-only code -- models.py/views.py/urls.py/settings.py
snippets, or template markup using Django template tags/variables
-- can't run standalone via Judge0 or the browser preview, since
it needs a real Django project. Only this course's pure-Python
examples (example_lang == 'python', no Django imports) are
actually runnable, so those still get the button below. #}
- Tests पूरी तरह skip करना क्योंकि app browser में 'ठीक दिखता है', फिर अगले change से इसे चुपचाप break करना।
- Tests को optional documentation मानना बजाय code के जिसे चलाया जाना चाहिए और passing रखा जाना चाहिए।
- एक साथ सब कुछ जांचने वाला एक बड़ा test लिखना बजाय छोटे focused tests के।
- Django Python के unittest module पर बना एक built-in testing framework ship करता है।
- Tests हर app की tests.py file में (या एक tests/ package में) रहते हैं और अपने आप discover होते हैं।
- Automated tests regressions को जल्दी पकड़ते हैं, असली users को एक bug दिखने से पहले।
- हर serious Django project अपने test suite को codebase का हिस्सा मानता है, afterthought नहीं।
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: