Beispiel #1
0
def PostAnswer(request):
    """!@brief Function for posting an answer which is part of the request body
    @details this function extracts the answer details from the request body, then creates a new entry in the answer table with the corresponding details. It also creates a notification for a user whose question has been provided an answer and increase the field numAnswers for that question by 1
    @post New entries have been created in the answer table as well as the notification table along with an update in th question table to accomodate for the new changes
    @return returns the updated question object
    """
    serializer = AnswerSerializer(data=request.data)
    if serializer.is_valid():
        ans = serializer.validated_data
        sender = ans['user']
        question = ans['question']
        receiver = question.user
        answer = Answer(user=sender,
                        username=sender.name,
                        userdepartment=sender.department,
                        userbio=sender.bio,
                        userdegree=sender.degree,
                        userspecialization=sender.specialization,
                        content=ans['content'],
                        question=question)
        answer.save()
        notification = Notification(receiver=receiver,
                                    sender=sender,
                                    sendername=sender.name,
                                    question=question,
                                    code=3)
        notification.save()
        #print(question.numAnswers)
        question.numAnswers = question.numAnswers + 1
        question.save()
        return QuestionResponse(sender.id, question.id)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #2
0
    def test_partial_update_answer(self):
        A_ID = 8
        Q_ID = 2
        U_ID = 4
        U_NAME = "user_" + str(U_ID)
        U_PASS = "******" + str(U_ID)
        A_VOTES = 10
        A_HTML = '<p> Updated answer. </p>'

        url = '/api/update/answer'
        data = {'id': A_ID, 'votes': A_VOTES, 'html': A_HTML}

        # Test login
        success = self.client.login(username=U_NAME, password=U_PASS)
        self.assertTrue(success)

        # Perform update
        response = self.client.post(url, data, format='json')

        # Test status code
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Test can be serialized.
        serializer = AnswerSerializer(data=response.data)
        self.assertTrue(serializer.is_valid(), msg=serializer.errors)

        # Test response data
        self.assertEqual(response.data['id'], A_ID)
        self.assertEqual(response.data['question'], Q_ID)
        self.assertEqual(response.data['user']['id'], U_ID)
        self.assertEqual(response.data['user']['username'], U_NAME)
        self.assertEqual(response.data['votes'], A_VOTES)
        self.assertEqual(response.data['html'], A_HTML)
Beispiel #3
0
    def test_new_answer_inserted_correctly(self):
        Q_ID = 1
        U_ID = 3
        U_NAME = "user_" + str(U_ID)
        A_HTML = '<p> Hello! This is a test. </p>'

        url = '/api/submit/answer/'
        data = {
            'question': str(Q_ID),
            'user': {
                'id': U_ID,
                'username': U_NAME
            },
            'html': A_HTML
        }
        response = self.client.post(url, data, format='json')

        # Test response says answer created successfully.
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # Test response data can be serialized.
        serializer = AnswerSerializer(data=response.data)
        self.assertTrue(serializer.is_valid(), msg=str(serializer.errors))

        # Test response data is correct.
        self.assertEqual(response.data['id'], 5)
        self.assertEqual(response.data['question'], Q_ID)
        self.assertEqual(response.data['user']['id'], U_ID)
        self.assertEqual(response.data['user']['username'], U_NAME)
        self.assertEqual(response.data['votes'], 0)
        self.assertEqual(response.data['html'], A_HTML)
Beispiel #4
0
def QuestionResponse(userid, questionid):
    """@brief Function for getting the particular question for a logged in user
    @details It takes a question id and a user id as input and outputs the question along with a list of all the answers for this question and all the votes which are given for some answer of this question
    @param userid the user id in db
    @param questionid the question id in db
    @return the question along with a list of answers for the question and a list of votes by the user on answer for this question
    """

    question = Question.objects.filter(id=questionid)
    qdata = QuestionSerializer(question, many=True)

    answers = Answer.objects.filter(question=questionid)
    answer_list = answers.values_list('id', flat=True).order_by('id')
    adata = AnswerSerializer(answers, many=True)

    uservotes = Vote.objects.filter(user=userid)
    ans_list = uservotes.values_list('answer', flat=True).order_by('answer')
    alist = [ans for ans in answer_list if ans in ans_list]
    votes = uservotes.filter(answer__in=alist)
    vdata = VoteSerializer(votes, many=True)

    return Response({
        "Question": qdata.data,
        "Answers": adata.data,
        "Votes": vdata.data,
    })
Beispiel #5
0
def get_answers(request, question_id):
    try:
        question = Question.objects.get(id=question_id)
        answers = Answer.objects.filter(question=question)
        serializer = AnswerSerializer(answers)
        return Response(serializer.data, status=status.HTTP_200_OK)
    except Exception as e:
        return Response({}, status=status.status.HTTP_400_BAD_REQUEST)
Beispiel #6
0
 def test_get_answers(self):
     question = self.questions[-1]
     response = self.client.get(
         reverse('api:answers', kwargs={'pk': question.pk}))
     answers = Answer.objects.filter(question=question).order_by(
         '-rating', '-created_at').all()
     serializer = AnswerSerializer(answers, many=True)
     self.assertEqual(response.status_code, status.HTTP_200_OK)
     self.assertEqual(response.data['results'], serializer.data)
Beispiel #7
0
    def test_get_answers_correctly(self):
        Q_ID = 3
        response = self.client.get('/api/' + str(Q_ID) + '/answer')

        # Test response says GET request succeeded.
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Test response data can be serialized.
        serializer = AnswerSerializer(data=response.data, many=True)
        self.assertTrue(serializer.is_valid(), msg=str(serializer.errors))

        # Test response data is correct.
        for i in range(0, 4):
            data = response.data[i]
            r_user_id = data['user']['id']
            self.assertEqual(data['id'], Q_ID * 4 + i)
            self.assertEqual(data['question'], Q_ID)
            self.assertEqual(data['user']['id'], i)
            self.assertEqual(data['user']['username'], "user_" + str(i))
            self.assertEqual(data['votes'], 0)
            self.assertEqual(data['html'], "<p> This is a dummy answer <\p>")
Beispiel #8
0
def add_answer(request, user_id, question_id):

    mentor = Mentor.objects.get(id=user_id)
    question = Question.objects.get(id=question_id)
    answer = Answer()
    answer.author = mentor
    answer.question = question
    answer.title = request.data['title']
    answer.description = request.data['description']
    answer.language = request.data['language']
    answer.save()
    return Response(AnswerSerializer(answer).data,
                    status=status.HTTP_201_CREATED)
Beispiel #9
0
 def favorites(self, request, pk=None):
     profile = self.get_object()
     if profile is None:
         return error('no profile found')
     answers = profile.favorites.all()
     page = self.paginate_queryset(answers)
     if page is not None:
         for answer in page:
             ApiCli.process_answer(answer, request.user)
         serializer = AnswerSerializer(page,
                                       many=True,
                                       context={'request': request})
         temp = self.get_paginated_response(serializer.data)
         return success(temp.data)
     return error('no more data')
Beispiel #10
0
 def create(self, request, *args, **kwargs):
     serializer = self.get_serializer(data=request.data)
     if serializer.is_valid():
         question = serializer.validated_data['question']
         if question.answers.filter(author=request.user).exists():
             return error('你已经回答过该问题了')
         answer = self.perform_create(serializer)
         answer.userSummary = request.user.profile
         answer.has_favorite = False
         answer.has_approve = False
         answer.has_against = False
         answer.comment_count = answer.comments.count()
         seri = AnswerSerializer(answer, context={'request': request})
         return success(seri.data)
     key = list(serializer.errors.keys())[0]
     return error(key + ': ' + serializer.errors[key][0])
Beispiel #11
0
def RemoveAnswer(request, answerid):
    a = Answer.objects.get(id=answerid)
    ajson = AnswerSerializer(a)
    a.delete()
    return Response(ajson.data)
Beispiel #12
0
 def test_contains_expected_fields(self):
     serializer = AnswerSerializer(instance=self.answer,
                                   context={'request': self.request})
     expected_keys = ['id', 'user', 'votes', 'created', 'text']
     self.assertCountEqual(serializer.data.keys(), expected_keys)
Beispiel #13
0
 def get_related_serialized_data(self, question, user_id):
     answers = Answer.objects.filter(question=question)
     serializer = AnswerSerializer(answers,
                                   many=True,
                                   context={"user_id": user_id})
     return serializer.data