Django 单元测试用例
Django Unit Test Case
您好,我是 Django 单元测试的新手,因为我正在使用 modelviewset 开发 Django Rest Framework。我需要测试几个模型、序列化器、视图和 url。我不确定如何执行它。因为我遵循了一些文档。但还是不清楚。这是我的代码
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
我写了一些测试用例,但遇到了一些错误。 django.urls.exceptions.NoReverseMatch: Reverse for 'UserAPI' not found. 'UserAPI' is not a valid view function or pattern name.
我不确定我在模型中做错了什么。所以请需要你的帮助。谢谢
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
如图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'
您当时似乎想使用的 url 名称是 user-list
,但由于您使用的是 basename='users'
,所以应该是 users-list
,所以:
def test_user_view(self):
response = self.client.get(reverse('users-list'))
# ...
您好,我是 Django 单元测试的新手,因为我正在使用 modelviewset 开发 Django Rest Framework。我需要测试几个模型、序列化器、视图和 url。我不确定如何执行它。因为我遵循了一些文档。但还是不清楚。这是我的代码
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
我写了一些测试用例,但遇到了一些错误。 django.urls.exceptions.NoReverseMatch: Reverse for 'UserAPI' not found. 'UserAPI' is not a valid view function or pattern name.
我不确定我在模型中做错了什么。所以请需要你的帮助。谢谢
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
如图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'
您当时似乎想使用的 url 名称是 user-list
,但由于您使用的是 basename='users'
,所以应该是 users-list
,所以:
def test_user_view(self):
response = self.client.get(reverse('users-list'))
# ...