Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the Django test case class.
Django
from django.test import [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Model instead of TestCase
Importing HttpResponse which is for views
Importing View which is unrelated to testing
✗ Incorrect
The TestCase class is used to write tests in Django.
2fill in blank
mediumComplete the code to define a test method inside a Django test case.
Django
class MyModelTest(TestCase): def [1](self): pass
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Not starting method name with 'test_'
Using generic names like 'run_test' which Django won't detect
✗ Incorrect
Test methods in Django must start with test_ to be recognized.
3fill in blank
hardFix the error in the test method to correctly create a model instance.
Django
def test_create_user(self): user = User.objects.[1](username='alice') self.assertEqual(user.username, 'alice')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' which looks for existing objects
Using 'filter' which returns a queryset, not a single object
✗ Incorrect
Use create to make a new model instance in the database during tests.
4fill in blank
hardFill both blanks to assert that the model instance count is 1 after creation.
Django
def test_user_count(self): User.objects.create(username='bob') count = User.objects.[1]().[2]() self.assertEqual(count, 1)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' which returns a single object, not a queryset
Using 'filter' without conditions returns a queryset but less clear than 'all'
✗ Incorrect
Use all() to get all objects and count() to count them.
5fill in blank
hardFill all three blanks to test that a model's string representation matches the username.
Django
def test_str_method(self): user = User.objects.create(username='carol') self.assertEqual(str([1]), [2]) self.assertEqual(user.[3](), 'carol')
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the username attribute instead of the user object in str()
Not quoting the expected string value
Calling 'username' instead of '__str__' method
✗ Incorrect
Convert the user object to string, compare to username string, and call the __str__ method.