0
0
Djangoframework~10 mins

Testing models in Django - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AHttpResponse
BModel
CTestCase
DView
Attempts:
3 left
💡 Hint
Common Mistakes
Importing Model instead of TestCase
Importing HttpResponse which is for views
Importing View which is unrelated to testing
2fill in blank
medium

Complete 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'
Amodel_test
Bcheck_model
Crun_test
Dtest_model_creation
Attempts:
3 left
💡 Hint
Common Mistakes
Not starting method name with 'test_'
Using generic names like 'run_test' which Django won't detect
3fill in blank
hard

Fix 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'
Acreate
Bget
Cfilter
Dall
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'get' which looks for existing objects
Using 'filter' which returns a queryset, not a single object
4fill in blank
hard

Fill 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'
Aall
Bcount
Cfilter
Dget
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'
5fill in blank
hard

Fill 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'
Auser
B'carol'
C__str__
Dusername
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