我想检查响应对象是否包含具有特定值的标签。如果条件满足,我可以查看为特定标签添加值。这当然是有效的,因为我手动进行了检查,但是我想为此进行测试。
我尝试使用assertContain和assertIn,但是它不起作用,或者我使用了这个错误:
class TaskIndexAPI(APITestCase):
def setUp(self):
user = User.objects.create_user(
username='TestUser',
password='test1234'
)
Task.objects.create(
name='Task for test',
creator=user,
status='Unauthenticated',
completion_date=date(2019, 4, 9),
description='This is description for test purposes',
warning_if_delayed=''
)
def test_check_if_delayed(self):
response = self.client.get(reverse('tasks_index'), format='json')
self.assertContains(response, 'This task is delayed')
def test_check_if_delayed(self):
response = self.client.get(reverse('tasks_index'), format='json')
self.assertIn('This task is delayed', response)
这是为对象标签添加价值的视图片段:
class UserTasksAPIView(APIView):
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
return Task.objects.filter(creator=self.request.user)
def check_if_tasks_are_delayed(self, queryset):
checked_tasks = queryset
for task in checked_tasks:
if task.completion_date <= date.today() and status == 'Unfinished':
task.warning_if_delayed = 'This task is delayed'
task.save()
else:
task.warning_if_delayed = ''
task.save()
return checked_tasks
def get(self, request):
user_tasks = self.get_queryset()
tasks = self.check_if_tasks_are_delayed(user_tasks)
serializer = UserTasksSerializer(tasks, many=True)
return Response(serializer.data)