0

ERROR: test_task_check_success (tasks.tests.TaskCheckTestCase.test_task_check_success)

Traceback (most recent call last): File "C:\Users\gns03\OneDrive\바탕 화면\사전과제\tasks\tests.py", line 119, in test_task_check_success response = self.client.get(self.url, params=self.data1, **header, format='json') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 289, in get response = super().get(path, data=data, **extra) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 206, in get return self.generic('GET', path, **r) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 234, in generic return super().generic( ^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 609, in generic return self.request(**r) ^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 286, in request return super().request(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\test.py", line 238, in request request = super().request(**kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 891, in request self.check_exception(response) File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\test\client.py", line 738, in check_exception raise exc_value File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\decorators\csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\views\generic\base.py", line 104, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception
raise exc File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\OneDrive\바탕 화면\사전과제\tasks\views.py", line 69, in get task_instance = Task.objects.get(id=request.data.get('task')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\manager.py", line 87, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\gns03\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\db\models\query.py", line 637, in get raise self.model.DoesNotExist( tasks.models.Task.DoesNotExist: Task matching query does not exist.

views.py

class TaskCheckView(APIView):

    def get(self, request):
        

        try:
            task_instance = Task.objects.get(id=request.data.get('task'))
        except Task.DoesNotExist:
            return Response({
                'error_code': status.HTTP_404_NOT_FOUND,
                'error': '해당 업무를 찾을 수 없습니다.'}, 
                status=status.HTTP_404_NOT_FOUND)
        
 
        subtasks_related_to_task = SubTask.objects.filter(task=task_instance)

        subtasks_data = SubTaskSerializer(subtasks_related_to_task, many=True).data
        
        serializer = TaskCheckSerializer(data={
            'task_id': task_instance.id,
            'task_team': ','.join([str(team.id) for team in task_instance.team.all()]),
            'title': task_instance.title,
            'content': task_instance.content,
            'is_complete': task_instance.is_complete,
            'completed_data': task_instance.completed_data,
            'created_at': task_instance.created_at,
            'modified_at': task_instance.modified_at,
            'subtasks': subtasks_data
        })


        if serializer.is_valid():
            return Response({'data': serializer.data, 
                            'status': status.HTTP_200_OK}, 
                            status=status.HTTP_200_OK)
        
        return Response({'error_code': status.HTTP_400_BAD_REQUEST}, 
                        status=status.HTTP_400_BAD_REQUEST)
    
serializers.py 

class TaskCheckSerializer(serializers.Serializer):
    task_id = serializers.IntegerField()
    task_team = serializers.CharField()
    title = serializers.CharField()
    content = serializers.CharField()
    is_complete = serializers.BooleanField()
    completed_data = serializers.DateTimeField(allow_null=True)
    created_at = serializers.DateField()
    modified_at = serializers.DateField()
    subtasks = SubTaskSerializer(many=True)
tests.py

class TaskCheckTestCase(APITestCase):
    def setUp(self):
        self.url = '/task/detail/'
        self.user = User.objects.create(email='[email protected]', name='팀원1')
        self.user.set_password("qwer1234")
        self.user.save()
        self.token, created = Token.objects.get_or_create(user=self.user)

        self.team1 = Team.objects.create(team='team1')

        self.task = Task.objects.create(title='테스트 제목', content='테스트', create_user=self.user)
        self.task.team.set([self.team1.id])  
        self.subtask = SubTask.objects.create(task=self.task, team=self.team1)
        

        self.data1={
            'task': str(self.task.id)
        }

        self.data2={
            'task': '999'
        }

    def test_task_check_success(self):
        header = {'HTTP_AUTHORIZATION': f'Token {self.token}'}
        response = self.client.get(self.url, data=self.data1, **header, format='json') 
        self.assertEqual(response.status_code, status.HTTP_200_OK)

I have no problem searching the actual task ID on the server, but when I try to search the self.task I created in the test code, I get an error. What is the problem?

I'm not getting a 404 error, the reason I'm getting an error is because I'm clearing the try part of getting the instance and getting the message.

1 Answer 1

0

the problem in your test case lies in the way you are sending the data in the get request in your test case you are passing the data as a dictionary using the data parameter which sends the data in the request body however in your view you are trying to retrieve the task ID from the query parameters using request.data.get('task')

to fix this you should pass the task ID as a query parameter in the url instead of in the request body

you can modify your test case like this:

class TaskCheckTestCase(APITestCase):
     # rest of your code

     def test_task_check_success(self):
        header = {'HTTP_AUTHORIZATION': f'Token {self.token}'}
        response = self.client.get(f'{self.url}?task={self.task.id}', **header, format='json') 
        self.assertEqual(response.status_code, status.HTTP_200_OK))

in this modification I'm appending the task ID to the url as a query parameter and now in your view you can retrieve it using request.query_params.get('task')

so your view should looks like this:

class TaskCheckView(APIView):
    def get(self, request):
        try:
            task_instance = Task.objects.get(id=request.query_params.get('task'))
        except Task.DoesNotExist:
            return Response({
                'error_code': status.HTTP_404_NOT_FOUND,
                'error': '해당 업무를 찾을 수 없습니다.'
            }, status=status.HTTP_404_NOT_FOUND)
    
    #rest of your code

this should resolve the issue.

I hope this helps you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.