Django Unit Test
🧩 Syntax:
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Code # Import your Code model from the appropriate location
class CodeModelTest(TestCase):
def setUp(self):
# Create a user for testing
self.user = User.objects.create_user(username='testuser', password='testpassword')
def test_question_max_length(self):
# Create a Code instance with a question exceeding the maximum length
code = Code.objects.create(
user=self.user,
question='a' * 10001, # Exceeds the maximum length of 10000
code_response='Some code response',
language='Python'
)
# Attempt to save the Code instance
with self.assertRaises(Exception) as context:
code.save()
# Check if the expected validation error message is in the error message
self.assertIn('question', str(context.exception))
self.assertIn('Ensure this value has at most 10000 characters', str(context.exception))
def test_question_valid_length(self):
# Create a Code instance with a valid question length
code = Code.objects.create(
user=self.user,
question='a' * 5000, # Valid length
code_response='Some code response',
language='Python'
)
# Save the Code instance
code.save()
# Retrieve the saved instance from the database
saved_code = Code.objects.get(pk=code.pk)
# Check if the question field matches the original value
self.assertEqual(saved_code.question, 'a' * 5000)