Тестирование аутентификации jwt с использованием django-тестирования или django rest Framework тестирования - PullRequest
0 голосов
/ 22 октября 2018

приведенный ниже код является функцией для аутентификации jwt.эта функция принимает имя пользователя и пароль в качестве параметра и дает нам токен jwt, а также сохраняет необходимые данные в полезной нагрузке.

views.py

@csrf_exempt
@api_view(['POST'])
@permission_classes([AllowAny, ])
def authenticate_user(request):
    try:

        username = request.data['username']
        password = request.data['password']
        user = authenticate(request, username=username, password=password)
        print("meh2")
        if user is not None:
            try:
                payload = jwt_payload_handler(user)
                token = jwt.encode(payload, settings.SECRET_KEY)
                user_details = {}
                user_details['user_id'] = user.id
                user_details['email'] = user.email
                user_details['first_name'] = user.first_name
                user_details['second_name'] = user.last_name
                user_details['token'] = token
                role = UserPermission.objects.get(user_id=user.id)
                user_details['role'] = role.emp_role.role_name
                if user_details['role'] == 'Student':
                    student_obj = Student.objects.get(user_id=user.id)
                    grade_id = student_obj.grade_id
                    grade_chapter_list = []
                    user_details['grade_id'] = grade_id
                    chap_obj = Chapter.objects.filter(grade_id=grade_id)
                    for i in chap_obj:
                        sub = {}
                        sub['grade_id'] = i.grade_id
                        sub['grade'] = i.grade.grade
                        sub['subject_id'] = i.subject_id
                        sub['subject_name'] = i.subject.subject_name
                        sub['section_id'] = student_obj.section_id
                        sub['section_name'] = student_obj.section.section_name

                        sub['branch_id'] = student_obj.branch_id
                        sub['branch_name'] = student_obj.branch.branch_name

                        grade_chapter_list.append(sub)
                    user_details['grdsub'] = grade_chapter_list

                elif user_details['role'] == 'Teacher':

                    dum = SchoolStaff.objects.get(user_id=user.id)
                    all_sub = dum.subjects.all()
                    sub = []
                    for subject in all_sub:
                        sub.append({"name":subject.subject_name, "id": subject.id})
                    user_details['subjects'] = sub

                    all_map = dum.mappings.all()
                    mappi = []
                    for i in all_map:
                        dict = {}
                        dict["grade_id"] = i.grade_id
                        dict["grade_name"] = i.grade.grade
                        dict["branch_id"] = i.branch_id
                        dict["branch_name"] = i.branch.branch_name
                        dict["section_id"] = i.section_id
                        dict["section_name"] = i.section.section_name

                        mappi.append(dict)

                    op = []
                    print(mappi, sub, "klmwmkkmkkkkkkkkkkkkkkkkkkkk")
                    for subject in sub:
                        for m in mappi:
                            n = m.copy()
                            n["subject_name"] = subject["name"]
                            n["subject_id"] = subject["id"]
                            op.append(n)

                    user_details['classes'] = json.dumps(op)
                    #
                    # all_section = dum.sections.all()
                    # sec = []
                    # for s in all_section:
                    #     sec.append(s)
                    # user_details['sections'] = sec
                    # user_details['branch'] = dum.branch_id
                elif user_details['role'] in check:
                    dum = AcademicStaff.objects.get(user_id=user.id)
                    all_sub = dum.subjects.all()
                    sub = []
                    for subject in all_sub:
                        sub.append(subject.subject_name)
                    user_details['subjects'] = sub
                    all_grades = dum.grades.all()
                    gra = []
                    for g in all_grades:
                        gra.append(g)
                    user_details['grade'] = gra
                    all_section = dum.sections.all()
                    sec = []
                    for s in all_section:
                        sec.append(s)
                    user_details['sections'] = sec
                    all_branches = dum.branchs_assigned.all()
                    branch = []
                    for b in all_branches:
                        branch.append(b)
                    user_details['branch'] = branch
                else :
                    return Response("permission denied")

                print("meh3")
                return Response(user_details, status=status.HTTP_200_OK)
            except Exception as e:
                raise e
        else:
            res = {'error': 'can not authenticate with the given credentials or the account has been deactivated'}
            return Response(res, status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        res = {'error': 'please provide an email and a password'}
        return Response(res)

как я напишу тест.py для вышеупомянутой функции, использующей тестирование django или тестирование остаточной структуры django.

Я не могу написать фрагмент в test.py, чтобы проверить эту функцию abive view.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...