def test__find_by_token(self):
        # Arrange
        user_orm = User.objects.create(username='******', email='*****@*****.**', password='******')
        token = Token.objects.get(user=user_orm).key
        expected_user_profile = UserProfileRepo().get(user_orm.id)

        # Act
        user_profile_repo = UserProfileRepo()
        actual_user_profile = user_profile_repo.find_by_token(token)

        # Assert
        compare(expected_user_profile, actual_user_profile)
Beispiel #2
0
    def setUpTestData(cls):
        movie_orm_1 = MovieORM.objects.create(
            title='bomonka1', year=2001, director='me',
            poster_url='https://bmstu.ru',video_url='https://bmstu.ru/poster.png'
        )

        subtitle_orm1 = SubtitleORM.objects.create(quote = "Monday is a bad day!!!",
                                                   start_time = time(hour=0, minute=0, second=37, microsecond=673000),
                                                   end_time = time(hour=0, minute=0, second=39, microsecond=673000),
                                                   movie = movie_orm_1)
        subtitle_orm2 = SubtitleORM.objects.create(quote = "Also Monday is a good day",
                                                   start_time = time(hour=0, minute=1, second=37, microsecond=673000),
                                                   end_time = time(hour=0, minute=0, second=59, microsecond=673001),
                                                   movie = movie_orm_1)

        cls.movie_1 = MovieRepo().get(movie_orm_1.id)
        cls.sub_1 = SubtitleRepo().get(subtitle_orm1.id)
        cls.sub_2 = SubtitleRepo().get(subtitle_orm2.id)

        cls.match = Match(
            quote='test quote',
            movie=cls.movie_1,
            subtitles=[cls.sub_1, cls.sub_2]
        )

        user_orm = User.objects.create(username='******', email='*****@*****.**', password='******')
        cls.user_profile = UserProfileRepo().get(user_orm.id)
Beispiel #3
0
    def setUpTestData(cls):
        user_1 = User.objects.create(username="******",
                                     email="*****@*****.**",
                                     password="******")

        movie_orm_1 = MovieORM.objects.create(title='kino1',
                                              year=1,
                                              director='me',
                                              poster_url='123',
                                              video_url='123')

        sub_orm_1_movie_1 = SubtitleORM.objects.create(
            quote='Such a nice weather',
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=movie_orm_1)

        sub_orm_2_movie_1 = SubtitleORM.objects.create(
            quote='There are lots of misspelling errrorrs',
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=movie_orm_1)

        sub_orm_3_movie_1 = SubtitleORM.objects.create(
            quote='new history match',
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=movie_orm_1)

        cls.user_profile_1 = UserProfileRepo().get(user_1.id)
        cls.movie_1 = MovieRepo().get(movie_orm_1.id)
        cls.sub_1_movie_1 = SubtitleRepo().get(sub_orm_1_movie_1.id)
        cls.sub_2_movie_1 = SubtitleRepo().get(sub_orm_2_movie_1.id)
        cls.sub_3_movie_1 = SubtitleRepo().get(sub_orm_3_movie_1.id)
    def setUpTestData(cls):
        cls.user = User.objects.create(
            username='******', email='*****@*****.**', password='******'
        )

        cls.user_profile_orm = UserProfileORM.objects.get(user=cls.user)  

        cls.movie_orm = MovieORM.objects.create(
            title='bomonka', year=2001, director='me',
            poster_url='https://bmstu.ru',video_url='https://bmstu.ru/poster.png'
        )

        cls.sub_orm_1 = SubtitleORM.objects.create(
            quote="Test Quote #1 ...",
            start_time=time(hour=0, minute=0, second=34, microsecond=420000),
            end_time=time(hour=0, minute=0, second=37,microsecond=420000),
            movie=cls.movie_orm
        )

        cls.sub_orm_2 = SubtitleORM.objects.create(
            quote="Test Quote #2 ...",
            start_time=time(hour=0, minute=1, second=34,microsecond=420000),
            end_time=time(hour=0, minute=1, second=37, microsecond=420000),
            movie=cls.movie_orm
        )

        cls.user_profile = UserProfileRepo().get(cls.user.id)
        cls.movie = MovieRepo().get(cls.movie_orm.id)
        cls.sub_1 = SubtitleRepo().get(cls.sub_orm_1.id)
        cls.sub_2 = SubtitleRepo().get(cls.sub_orm_2.id)
Beispiel #5
0
    def post(self, request, username):
        """
        **post** - запрос на добавление матча в историю пользователя
        """

        try:
            token = request.COOKIES['token']
        except KeyError:
            # **Возвращаемый результат**
            """
            Пользователь не авторизован

            - код 401 

            """
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        try:
            data = dict(request.data)
            movie_id = request.data['movie_id']
            quote = request.data['quote']
            subtitle_ids = data['subtitle_ids']
        except KeyError:
            """
            Невалидные данные о структуре Match, присланные клиентом

            - код 400 

            """
            return Response(status=status.HTTP_400_BAD_REQUEST)

        user_profile = UserProfileRepo().find_by_token(token)
        if user_profile is None:
            return Response(status=status.HTTP_401_UNAUTHORIZED)

        subtitle_repo = SubtitleRepo()
        
        subtitle_ids = [int(sub_id) for sub_id in subtitle_ids]

        movie = MovieRepo().get(movie_id)
        subtitles = [subtitle_repo.get(id) for id in subtitle_ids]
        match = Match(
            quote=quote,
            movie=movie,
            subtitles=subtitles
        )

        usecase = UpdateUserHistoryUsecase(user_profile, match, MatchRepo())
        usecase.execute()

        """
        Успешное выполнение дополнения истории пользователя:

        - код 200

        """
        return Response(status=status.HTTP_200_OK)
    def filter_by_user(self, user_profile: UserProfile) -> List[Match]:
        user_profile_orm = UserProfileRepo().Mapper.from_domain(user_profile)
        query = MatchORM.objects.filter(user_profile=user_profile_orm)
        query = query.order_by('-id')

        result_query = []
        for match in query:
            result_query.append(self.Mapper.to_domain(match))

        return result_query
Beispiel #7
0
    def post(self, request, format=None):
        # **Возвращаемый результат**
        try:
            email = request.data['email']
            password = request.data['password']
            """
            Некорректные формат запроса:
            
            - код 400
            
            - текст ошибки
            
            """

        except KeyError:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        login_usecase = UserLoginUseCase(user_profile_repo=UserProfileRepo(),
                                         authorizer=TokenAuthorizer(),
                                         email=email,
                                         password=password)

        try:
            result = login_usecase.execute()
            """
            Успешная авторизация:
            
            - код 200
            
            - логин авторизованного пользователя
            
            - почта авторизованного пользователя
            
            """
            response = Response(status=status.HTTP_200_OK,
                                data={
                                    'username': result['username'],
                                    'email': result['email']
                                })
            response.set_cookie(key='token', value=result['token'])
            """
            Некорректный пароль:
            
            - код 401
            
            - текст ошибки
            
            """
        except (IncorrectPassword, UserDoesNotExists):
            response = Response(
                status=status.HTTP_401_UNAUTHORIZED,
                data='Не существует пользователя с такой почтой или паролем')

        return response
    def test__execute__empty_history(self):
        # Arrange
        expected_matches = []

        # Act
        usecase = ShowUserHistoryUsecase(user_profile=self.user_profile_3,
                                         user_profile_repo=UserProfileRepo(),
                                         match_repo=MatchRepo())

        actual_matches = usecase.execute()

        compare(expected_matches, actual_matches)
    def filter_by_movie_and_user(self, movie: Movie,
                                 user_profile: UserProfile) -> List[Match]:
        movie_orm = MovieRepo().Mapper.from_domain(movie)
        user_profile_orm = UserProfileRepo().Mapper.from_domain(user_profile)

        query = MatchORM.objects.filter(movie=movie_orm,
                                        user_profile=user_profile_orm)
        result_query = []
        for match in query:
            result_query.append(self.Mapper.to_domain(match))

        return result_query
    def test__execute(self):
        # Arrange
        expected_matches = [self.match_2, self.match_1]

        # Act
        usecase = ShowUserHistoryUsecase(user_profile=self.user_profile_1,
                                         user_profile_repo=UserProfileRepo(),
                                         match_repo=MatchRepo())

        actual_matches = usecase.execute()

        # Assert
        compare(expected_matches, actual_matches)
Beispiel #11
0
    def get(self, request, username):
        user_profile = UserProfileRepo().find_by_username(username)
        # **Возвращаемый результат**
        if user_profile is None:
            """
            Отсутствие пользователя с заданными данными:
            
            - код 404
            
            - текст ошибки
            
            """
            return Response(
                status=status.HTTP_404_NOT_FOUND,
                data='Пользователь не найден'
            )

        show_history_usecase = ShowUserHistoryUsecase(
            user_profile=user_profile,
            user_profile_repo=UserProfileRepo(),
            match_repo=MatchRepo()
        )

        history = show_history_usecase.execute()

        history_dict = [match.to_dict() for match in history]

        """
        Успешное получение истории:
            
        - код 200
            
        - словарь с данными о просмотренных фильмах и цитатах
            
        """
        return Response(
            status=status.HTTP_200_OK,
            data=history_dict
        )
        def to_domain(match_orm: MatchORM) -> Match:
            movie_domain = MovieRepo.Mapper.to_domain(match_orm.movie)

            subtitles_domain = []
            for sub in match_orm.subtitles.all().order_by('-id'):
                subtitles_domain.append(SubtitleRepo.Mapper.to_domain(sub))

            user_profile = UserProfileRepo().get(
                match_orm.user_profile.user.id)

            match_domain = Match(id=match_orm.id,
                                 quote=match_orm.quote,
                                 user_profile=user_profile,
                                 movie=movie_domain,
                                 subtitles=subtitles_domain)

            return match_domain
 def setUpTestData(cls):
     cls.user_orm_1 = User.objects.create(username="******",
                                          email="*****@*****.**",
                                          password="******")
     repo = UserProfileRepo()
     cls.user_profile_domain = repo.get(cls.user_orm_1.id)
    def setUpTestData(cls):
        user_1 = User.objects.create(username="******",
                                     email="*****@*****.**",
                                     password="******")

        user_2 = User.objects.create(username="******",
                                     email="*****@*****.**",
                                     password="******")

        user_3 = User.objects.create(username="******",
                                     email="*****@*****.**",
                                     password="******")

        user_profile_orm_1 = UserProfileORM.objects.get(user=user_1)
        user_profile_orm_2 = UserProfileORM.objects.get(user=user_2)
        user_profile_orm_3 = UserProfileORM.objects.get(user=user_3)

        movie_orm_1 = MovieORM.objects.create(title='kino1',
                                              year=1,
                                              director='me',
                                              poster_url='123',
                                              video_url='123')

        movie_orm_2 = MovieORM.objects.create(title='kino2',
                                              year=1,
                                              director='notme',
                                              poster_url='1234',
                                              video_url='1234')

        movie_orm_3 = MovieORM.objects.create(title='kino3',
                                              year=1,
                                              director='notme',
                                              poster_url='12345',
                                              video_url='12348')

        sub_orm_1_movie_1 = SubtitleORM.objects.create(
            quote='Such a nice weather',
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=movie_orm_1)

        sub_orm_2_movie_1 = SubtitleORM.objects.create(
            quote='There are lots of misspelling errrorrs',
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=movie_orm_1)

        sub_orm_1_movie_2 = SubtitleORM.objects.create(
            quote='Static variable as local persist...',
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=movie_orm_2)

        match_1 = MatchORM.objects.create(movie=movie_orm_1,
                                          user_profile=user_profile_orm_1)
        match_1.subtitles.set([sub_orm_1_movie_1, sub_orm_2_movie_1])

        match_2 = MatchORM.objects.create(movie=movie_orm_2,
                                          user_profile=user_profile_orm_1)
        match_2.subtitles.set([sub_orm_1_movie_2])

        match_3 = MatchORM.objects.create(movie=movie_orm_1,
                                          user_profile=user_profile_orm_2)
        match_3.subtitles.set([sub_orm_1_movie_1, sub_orm_2_movie_1])

        cls.user_profile_1 = UserProfileRepo().get(user_1.id)
        cls.user_profile_2 = UserProfileRepo().get(user_2.id)
        cls.user_profile_3 = UserProfileRepo().get(user_3.id)

        cls.movie_1 = MovieRepo().get(movie_orm_1.id)
        cls.movie_2 = MovieRepo().get(movie_orm_2.id)
        cls.movie_3 = MovieRepo().get(movie_orm_3.id)

        cls.sub_1_movie_1 = SubtitleRepo().get(sub_orm_1_movie_1.id)
        cls.sub_2_movie_1 = SubtitleRepo().get(sub_orm_2_movie_1.id)
        cls.sub_1_movie_2 = SubtitleRepo().get(sub_orm_1_movie_2.id)

        cls.match_1 = MatchRepo().get(match_1.id)
        cls.match_2 = MatchRepo().get(match_2.id)
        cls.match_3 = MatchRepo().get(match_3.id)
Beispiel #15
0
 def setUpTestData(cls):
     cls.authorizer = TokenAuthorizer()
     cls.user_profile_repo = UserProfileRepo()
    def test__filter_by_user(self):
        # Arrange
        _user1 = User.objects.create(username='******', email='*****@*****.**', password='******')
        _user2 = User.objects.create(username='******', email='*****@*****.**', password='******')
        _user3 = User.objects.create(username='******', email='*****@*****.**', password='******')

        user1 = UserProfileORM.objects.get(user=_user1)
        user2 = UserProfileORM.objects.get(user=_user2)
        user3 = UserProfileORM.objects.get(user=_user3)

        movie1 = MovieORM.objects.create(title='m1', year=2001, director='dir',
                                         poster_url='http://123', video_url='http://321')

        movie2 = MovieORM.objects.create(title='m2', year=2003, director='dir',
                                         poster_url='http://1234', video_url='http://3214')

        sub1 = SubtitleORM.objects.create(
            quote='test quote',
            start_time=datetime.now(), end_time=datetime.now(),
            movie=movie1
        )

        sub2 = SubtitleORM.objects.create(
            quote='sec quote',
            start_time=datetime.now(), end_time=datetime.now(),
            movie=movie1
        )

        sub3 = SubtitleORM.objects.create(
            quote='third quote',
            start_time=datetime.now(), end_time=datetime.now(),
            movie=movie1
        )

        match1 = MatchORM.objects.create(movie=movie1, user_profile=user1)
        match1.subtitles.set([sub1, sub2])
        match2 = MatchORM.objects.create(movie=movie1, user_profile=user2)
        match2.subtitles.set([sub3])
        match3 = MatchORM.objects.create(movie=movie2, user_profile=user1)
        match3.subtitles.set([sub1, sub2])

        match_repo = MatchRepo()
        expected_query_1 = [
            match_repo.get(id=match3.id),
            match_repo.get(id=match1.id),
        ]

        expected_query_2 = [
            match_repo.get(id=match2.id)
        ]

        # Act
        user_repo = UserProfileRepo()
        user_domain_1 = user_repo.get(user1.id)
        user_domain_2 = user_repo.get(user2.id)

        actual_query_1 = match_repo.filter_by_user(user_profile=user_domain_1)
        actual_query_2 = match_repo.filter_by_user(user_profile=user_domain_2)

        # Assert
        compare(expected_query_1, actual_query_1)
        compare(expected_query_2, actual_query_2)
Beispiel #17
0
    def post(self, request, format=None):
        # **Возвращаемый результат**
        try:
            username = request.data['username']
            email = request.data['email']
            password = request.data['password']
            repeated_password = request.data['repeatedPassword']
            """
            Некорректные формат запроса:
            
            - код 400
            
            - текст ошибки
            
            """

        except KeyError:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        """
        Некорректный повторный ввод пароля:
            
        - код 406
            
        - текст ошибки
            
        """
        if password != repeated_password:
            return Response(status=status.HTTP_406_NOT_ACCEPTABLE,
                            data='Пароли не совпадают')

        registration_usecase = UserRegistrationUseCase(
            user_profile_repo=UserProfileRepo(),
            authorizer=TokenAuthorizer(),
            username=username,
            password=password,
            email=email)

        try:
            result = registration_usecase.execute()
            """
            Успешная регистрация:
            
            - код 200
            
            - логин зарегистрированного пользователя
            
            - почта зарегистрированного пользователя
            
            """

            response = Response(status=status.HTTP_200_OK,
                                data={
                                    'username': result['username'],
                                    'email': result['email']
                                })
            response.set_cookie(key='token', value=result['token'])
            """
            Совпадение данных с существующим пользователем:
            
            - код 409
            
            - текст ошибки
            
            """

        except UserAlreadyExists:
            response = Response(status=status.HTTP_409_CONFLICT,
                                data='Пользователь уже существует')

        return response
Beispiel #18
0
 def get_token(self, user_profile: UserProfile) -> str:
     user_profile_orm = UserProfileRepo().Mapper.from_domain(user_profile)
     token = Token.objects.get(user=user_profile_orm.user)
     return token.key