Testing Django Apps & APIs

🐍 DjangoLesson 13Advanced

Testing ensures software quality and prevents code regressions. Django provides a custom unit testing framework extending Python's built-in unit tests.

1 Writing Tests
Python — tests.py
from django.test import TestCase
from django.contrib.auth import get_user_model
from .models import Post

class PostModelTest(TestCase):
    def setUp(self):
        User = get_user_model()
        self.user = User.objects.create_user(username="testuser", password="password")
        self.post = Post.objects.create(title="Test Post", content="Post content", author=self.user)

    def test_post_creation(self):
        self.assertEqual(self.post.title, "Test Post")
        self.assertEqual(str(self.post), "Test Post")
2 Code Challenge
Challenge: Write a view validation test mapping endpoints to confirm unauthenticated clients receive 403 Forbidden errors when calling write actions.