pythondjango-modelsdjango-rest-frameworkdjango-viewsdjango-unittest

Django Unit Test Case


Hello I'm a newbie to Django Unit test as I'm working on Django Rest Framework using modelviewset. I need to test few models, serializers, views & urls. I'm not sure how to perform it. As I have followed few documentations. But still not clear. Here's my code

models.py

class User(AbstractUser):
    """This Class is used to extend the in-build user model """
    ROLE_CHOICES = (('CREATOR','CREATOR'),('MODERATOR','MODERATOR'),('USERS','USERS'))
    GENDER_CHOICES = (('MALE','MALE'),('FEMALE',"FEMALE"),('OTHER','OTHER'))
    date_of_birth = models.DateField(verbose_name='Date of Birth', null=True)
    profile_image = models.ImageField(upload_to='media/profile_images', verbose_name='Profile Image', default='media/profile_images/default.webp', blank=True)
    bio = models.TextField(verbose_name='Bio')
    role = models.CharField(max_length=10, verbose_name='Role', choices=ROLE_CHOICES, default='USERS')
    gender = models.CharField(max_length=6, verbose_name='Gender', choices=GENDER_CHOICES)

serializers.py

class UserSerializer(serializers.ModelSerializer):
    following = serializers.SerializerMethodField(read_only=True)
    followers = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = User
        fields = ('first_name','last_name','username','password','email','date_of_birth',
                  'profile_image','bio','role','gender', 'following','followers')
        extra_kwargs = {'is_active':{'write_only':True},
                        'password':{'write_only':True}}

views.py

class UserAPI(viewsets.ModelViewSet):
    serializer_class = UserSerializer
    queryset = User.objects.all()
    permission_classes = [permissions.IsAuthenticated, TokenHasReadWriteScope]

urls.py

router = DefaultRouter()
router.register('users', views.UserAPI, basename='users'),
router.register('following', views.FollowingAPI, basename='following'),


urlpatterns = router.urls

I have written few test cases but getting some errors. django.urls.exceptions.NoReverseMatch: Reverse for 'UserAPI' not found. 'UserAPI' is not a valid view function or pattern name. I'm not sure what wrong i have done even in model. So please need your help. Thank you

tests.py

class UserTests(TestCase):

    def setUp(self):
        User.objects.create(
            first_name='John',last_name='Cena',username='john.cena',
            email='john@wwf.com',date_of_birth='1994-12-12', bio='Hello I am John',
            role='MODERATOR',gender='MALE',
        )


    def test_users_model(self):
        first_name = User.objects.get(first_name='John')
        last_name = User.objects.get(last_name='Cena')
        self.assertEquals(first_name.get_username(), "john.cena")

    def test_user_view(self):
        response = self.client.get(reverse('UserAPI'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'john.cena')

    def test_user_urls(self):
        pass

Solution

  • As shown in the docs:

    router.register(r'users', UserViewSet)
    
    The example above would generate the following URL patterns:
    
    URL pattern: ^users/$ Name: 'user-list'
    URL pattern: ^users/{pk}/$ Name: 'user-detail'
    URL pattern: ^accounts/$ Name: 'account-list'
    URL pattern: ^accounts/{pk}/$ Name: 'account-detail'
    

    The url name you seem to want to use then is user-list, but since you used basename='users' it would be users-list so:

        def test_user_view(self):
            response = self.client.get(reverse('users-list'))
            # ...