Ejemplo n.º 1
0
    def test_save__new(self):
        # Arrange
        expected_movie_data = {
            'title': self.title,
            'year': self.year,
            'director': self.director,
            'poster_url': self.poster_url,
            'video_url': self.video_url
        }

        # Act
        movie = Movie(title=self.title,
                      year=self.year,
                      director=self.director,
                      poster_url=self.poster_url,
                      video_url=self.video_url)

        movie_repo = MovieRepo()
        actual_movie = movie_repo.save(movie)
        actual_movie_data = {
            'title': actual_movie.title,
            'year': actual_movie.year,
            'director': actual_movie.director,
            'poster_url': actual_movie.poster_url,
            'video_url': actual_movie.video_url
        }

        # Assert
        self.assertDictEqual(expected_movie_data, actual_movie_data)
Ejemplo n.º 2
0
    def test_get_movie(self):
        # Arrange

        movie_orm = MovieORM.objects.create(title=self.title,
                                            year=self.year,
                                            director=self.director,
                                            poster_url=self.poster_url,
                                            video_url=self.video_url)
        id = movie_orm.id
        expected_movie = {
            'id': id,
            'title': self.title,
            'year': self.year,
            'director': self.director,
            'poster_url': self.poster_url,
            'video_url': self.video_url
        }
        movie_repo = MovieRepo()

        # Act
        movie_orm = movie_repo.get(id)
        actual_movie = {
            'id': movie_orm.id,
            'title': movie_orm.title,
            'year': movie_orm.year,
            'director': movie_orm.director,
            'poster_url': movie_orm.poster_url,
            'video_url': movie_orm.video_url
        }

        # Assert
        self.assertDictEqual(expected_movie, actual_movie)
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # pylint: disable-msg=C0103
        self.HOST = 'http://movie-quotes.ru'
        self.STATIC_PATH = '/static/'

        self._movie_repo = MovieRepo()
        self._subtitle_repo = SubtitleRepo()
Ejemplo n.º 4
0
    def test_save__try_to_update_with_none_values(self):
        #
        #   In database fields with new values which are equal to None
        #   should not be overwritten because of the fact, that client tends to
        #   send back to server only a small part of object's data, such as ID.

        # Arrange
        movie_orm = MovieORM.objects.create(title=self.title,
                                            year=self.year,
                                            director=self.director,
                                            poster_url=self.poster_url,
                                            video_url=self.video_url)

        existed_movie = MovieRepo().get(movie_orm.id)

        expected_movie_data = {
            'title': self.title,
            'year': self.year,
            'director': self.director,
            'poster_url': self.poster_url,
            'video_url': self.video_url
        }

        # Act
        movie_repo = MovieRepo()

        existed_movie.title = None
        existed_movie.year = None
        existed_movie.director = None
        existed_movie.poster_url = None

        actual_movie = movie_repo.save(existed_movie)

        actual_movie_data = {
            'title': actual_movie.title,
            'year': actual_movie.year,
            'director': actual_movie.director,
            'poster_url': actual_movie.poster_url,
            'video_url': actual_movie.video_url
        }

        # Assert
        self.assertDictEqual(expected_movie_data, actual_movie_data)

        # Chech immutabilty direct in orm object
        actual_movie_orm = MovieORM.objects.get(pk=movie_orm.id)
        actual_movie_orm_data = {
            'title': actual_movie_orm.title,
            'year': actual_movie_orm.year,
            'director': actual_movie_orm.director,
            'poster_url': actual_movie_orm.poster_url,
            'video_url': actual_movie_orm.video_url
        }

        self.assertDictEqual(expected_movie_data, actual_movie_orm_data)
    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)
Ejemplo n.º 6
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')

        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_1)

        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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
    def test__deserialize_movie_and_update_from_repo(self):
        # Arrange
        incomplete_movie_json = f'{{"id": "{self.movie_1.id}", \
"title": "{self.movie_1.title}", \
"director": "{self.movie_1.director}", \
"url": "{self.movie_1.video_url}"}}'

        # Act
        movie_serializer = MovieSerializer()
        incomplete_movie = movie_serializer.deserialize(incomplete_movie_json)

        movie_repo = MovieRepo()
        actual_movie = movie_repo.save(incomplete_movie)

        # Assert
        compare(self.movie_1, actual_movie)
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
    def setUpTestData(cls):
        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')

        cls.movie_1 = MovieRepo().get(cls.movie_orm_1.id)
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
    def test_scenario(self):
        # *********************** Populate the database *******************
        movie_LOTR = MovieRepo().save(
            Movie(title='The Lord of the Rings',
                  year=2001,
                  director='Peter Jackson',
                  poster_url='http://someurl/',
                  video_url='http://anotherurl/'))

        subtitles_LOTR = SubtitleParser.parse(
            os.path.dirname(__file__) + '/res/LOTR.en.srt')

        subtitle_repo = SubtitleRepo()
        for sub in subtitles_LOTR:
            sub.movie = movie_LOTR
            subtitle_repo.save(sub)
        # -----------------------------------------------------------------

        # Arrange
        search_quote = "Run, Frodo"
        expected_json = [{
            "quote":
            search_quote,
            "movie": {
                "id": "1",
                "title": 'The Lord of the Rings',
                "year": "2001",
                "director": "Peter Jackson",
                "poster": 'http://someurl/',
                "url": 'http://anotherurl/'
            },
            "quotes": [{
                "id": "652",
                "quote": "Run, Frodo!",
                "time": "00:56:54.940000"
            }, {
                "id": "1712",
                "quote": "Run, Frodo. Go!",
                "time": "03:06:04.190000"
            }]
        }]

        request_data = {"quote": search_quote}

        # Act
        resp = self.client.post('/api/v0/movies/quote/',
                                request_data,
                                format='json')

        # Assert
        self.assertEqual(resp.status_code, status.HTTP_200_OK)
        self.assertEqual(expected_json, resp.data)
Ejemplo n.º 14
0
    def test__deserialize_match(self):
        # Arrange
        expected_match = Match(quote='Monday', movie=self.movie_1, subtitles=[self.sub_1, self.sub_2])

        match_json = f'{{"quote": "Monday", "movie_id": "{self.movie_1.id}", "subtitles": [\
{{ "id": "{self.sub_1.id}" }}, {{ "id": "{self.sub_2.id}" }} ]}}'

        # Act
        match_serializer = MatchSerializer()
        actual_match = match_serializer.deserialize(match_json)

        actual_match.movie = MovieRepo().get(actual_match.movie.id)
        actual_match.subtitles = [SubtitleRepo().get(sub.id) for sub in actual_match.subtitles]

        # Assert
        compare(expected_match, actual_match)
    def setUpTestData(cls):
        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')

        cls.subtitle_orm1 = SubtitleORM.objects.create(
            quote="Monday is a bad day!!!",
            start_time=datetime.now(),
            end_time=datetime.now(),
            movie=cls.movie_orm_1)

        cls.movie_1 = MovieRepo().get(cls.movie_orm_1.id)
        cls.subtitle_1 = SubtitleRepo().get(cls.subtitle_orm1.id)
Ejemplo n.º 16
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'
        )


        sub_orm_1_movie_1 = SubtitleORM.objects.create(
            quote='Such a nice weather',
            start_time=time(hour=0, minute=0, second=37, microsecond=673000),
            end_time=datetime.now(),
            movie=movie_orm_1
        )
        
        cls.movie_1 = MovieRepo().get(movie_orm_1.id)
        cls.sub_1 = SubtitleRepo().get(sub_orm_1_movie_1.id)
Ejemplo n.º 17
0
    def handle(self, *args, **options):
        movie_orm_lotr = MovieORM.objects.create(
            title='Lord of the Rings',
            year=2001,
            director='Peter Jackson',
            poster_url='https://someurl.ru',
            video_url='http://videourl.com'
        )
        movie_lotr = MovieRepo().save(movie_orm_lotr)

        subtitle_repo = SubtitleRepo()
        subtitles_lotr = SubtitleParser.parse(os.path.dirname(__file__) + '/res/LOTR.ru.srt')
        for sub in subtitles_lotr:
            sub.movie = movie_lotr
            subtitle_repo.save(sub)

        self.stdout.write(f'Added {len(subtitles_lotr)} subtitles for movie {movie_lotr.title}')
Ejemplo n.º 18
0
    def test_save__update(self):
        # Arrange
        movie_orm = MovieORM.objects.create(title=self.title,
                                            year=self.year,
                                            director=self.director,
                                            poster_url=self.poster_url,
                                            video_url=self.video_url)

        existed_movie = MovieRepo().get(movie_orm.id)

        title_new_value = 'The Departed'
        year_new_value = 2006
        director_new_value = 'Martin Scorsese'

        expected_movie_data = {
            'title': title_new_value,
            'year': year_new_value,
            'director': director_new_value,
            'poster_url': self.poster_url,
            'video_url': self.video_url
        }

        # Act
        existed_movie.title = title_new_value
        existed_movie.year = year_new_value
        existed_movie.director = director_new_value

        movie_repo = MovieRepo()
        actual_movie = movie_repo.save(existed_movie)
        actual_movie_data = {
            'title': actual_movie.title,
            'year': actual_movie.year,
            'director': actual_movie.director,
            'poster_url': actual_movie.poster_url,
            'video_url': actual_movie.video_url
        }

        self.assertDictEqual(expected_movie_data, actual_movie_data)
Ejemplo n.º 19
0
    def save(self, match: Match) -> Match:
        """
        Saves given match object if it exists in database,
        othervise creates a new
        """
        if match.id is None:
            saved_match = self._create(match)
        else:
            if MatchORM.objects.filter(pk=match.id).exists():
                match.movie = MovieRepo().save(match.movie)

                subtitle_repo = SubtitleRepo()
                for sub in match.subtitles:
                    sub = subtitle_repo.save(sub)

                match_orm = MatchORM.objects.get(pk=match.id)
                match_orm.quote = set_if_not_none(match_orm.quote, match.quote)
                match_orm.save()
            else:
                saved_match = self._create(match)

        return saved_match
Ejemplo n.º 20
0
    def _create(self, match: Match) -> Match:
        if match.user_profile is None:
            raise NoUserDefinedForMatch()

        movie = MovieRepo().save(match.movie)
        movie_orm = MovieRepo.Mapper.from_domain(movie)

        subtitle_repo = SubtitleRepo()
        subtitles = [subtitle_repo.save(sub) for sub in match.subtitles]
        subtitles_orm = [
            SubtitleRepo.Mapper.from_domain(sub) for sub in subtitles
        ]

        user_profile_orm = UserProfileRepo.Mapper.from_domain(
            match.user_profile)

        created_match = MatchORM.objects.create(quote=match.quote,
                                                user_profile=user_profile_orm,
                                                movie=movie_orm)

        created_match.subtitles.set(subtitles_orm)
        created_match.save()

        return self.Mapper.to_domain(created_match)
    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)
    def setUpTestData(cls):
        # Movies
        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')

        cls.movie_orm_2 = MovieORM.objects.create(
            title='bomonka2',
            year=1000,
            director='me',
            poster_url='https://bmstu.ru',
            video_url='https://bmstu.ru/poster.png')

        cls.movie_orm_3 = MovieORM.objects.create(
            title='bomonka3',
            year=3000,
            director='me',
            poster_url='https://bmstu.ru',
            video_url='https://bmstu.ru/poster.png')

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

        # Subs for movie №1
        cls.sub_orm_1_movie_1 = SubtitleORM.objects.create(
            quote="Friend! Hello! .... Bruh!? (hello: 1/3)",
            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_1)

        cls.sub_orm_2_movie_1 = SubtitleORM.objects.create(
            quote="Oh God, when this project will be done :( ... (God: 1/2)",
            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_1)

        cls.sub_orm_3_movie_1 = SubtitleORM.objects.create(
            quote=
            "Hello, mr. Rossinsky! mr. Saliery sends his regards (hello: 2/3)",
            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_1)

        # subs for movie №2
        cls.sub_orm_4_movie_2 = SubtitleORM.objects.create(
            quote=
            "God bles aMuuuuuuuuuurica. This is the state of freedom. (God: 2/2)",
            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_2)

        cls.sub_orm_5_movie_2 = SubtitleORM.objects.create(
            quote="Test Quote. Hello, another test (hello: 3/3)",
            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_2)

        cls.sub_orm_6_movie_2 = SubtitleORM.objects.create(
            quote="But who is Joe Biden???",
            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_2)

        cls.sub_1_movie_1 = SubtitleRepo().get(cls.sub_orm_1_movie_1.id)
        cls.sub_2_movie_1 = SubtitleRepo().get(cls.sub_orm_2_movie_1.id)
        cls.sub_3_movie_1 = SubtitleRepo().get(cls.sub_orm_3_movie_1.id)

        cls.sub_4_movie_2 = SubtitleRepo().get(cls.sub_orm_4_movie_2.id)
        cls.sub_5_movie_2 = SubtitleRepo().get(cls.sub_orm_5_movie_2.id)
        cls.sub_6_movie_2 = SubtitleRepo().get(cls.sub_orm_6_movie_2.id)
Ejemplo n.º 23
0
    def test_scenario(self):
        # /********************* Populate the database *******************\
        movie_LOTR = MovieRepo().save(
            Movie(title='The Lord of the Rings',
                  year=2001,
                  director='Peter Jackson',
                  poster_url='http://someurl/',
                  video_url='http://anotherurl/'))

        subtitles_LOTR = SubtitleParser.parse(
            os.path.dirname(__file__) + '/res/LOTR.en.srt')

        subtitle_repo = SubtitleRepo()
        for sub in subtitles_LOTR:
            sub.movie = movie_LOTR
            subtitle_repo.save(sub)
        # \----------------------------------------------------------------/

        # /-------------------- User registration -------------------------\
        # Arrange
        request_data = {
            'username': '******',
            'email': '*****@*****.**',
            'password': '******',
            'repeatedPassword': '******'
        }

        expected_response_status = status.HTTP_200_OK
        expected_response = {
            'username': '******',
            'email': '*****@*****.**'
        }

        # Act
        response = self.client.post('/api/v0/session/registration/',
                                    request_data)

        # Assert
        self.assertEqual(expected_response_status, response.status_code)
        self.assertTrue('token' in response.cookies)
        self.assertEqual(expected_response, response.data)
        # \----------------------------------------------------------------/

        # /----------------- User Login (incorrect data) ------------------\
        # Arange
        request_data = {
            'email': '*****@*****.**',
            'password': '******'
        }

        expected_response_status = status.HTTP_401_UNAUTHORIZED

        # Act
        response = self.client.post('/api/v0/session/login/', request_data)

        # Assert
        self.assertEqual(expected_response_status, response.status_code)
        # \----------------------------------------------------------------/

        # /------------------  User Login (correct data) ------------------\
        # Arrange
        request_data = {'email': '*****@*****.**', 'password': '******'}

        expected_response_status = status.HTTP_200_OK
        expected_response_data = {
            'username': '******',
            'email': '*****@*****.**'
        }

        # Act
        response = self.client.post('/api/v0/session/login/', request_data)

        # Assert
        self.assertEqual(expected_response_status, response.status_code)
        self.assertEqual(expected_response_data, response.data)
        # \----------------------------------------------------------------/

        # /------------------------- Search -------------------------------\
        # Arrange
        search_quote = "Run, Frodo"
        expected_response_status = status.HTTP_200_OK
        expected_response_data = [{
            "quote":
            search_quote,
            "movie": {
                "id": "1",
                "title": 'The Lord of the Rings',
                "year": "2001",
                "director": "Peter Jackson",
                "poster": 'http://someurl/',
                "url": 'http://anotherurl/'
            },
            "quotes": [{
                "id": "652",
                "quote": "Run, Frodo!",
                "time": "00:56:54.940000"
            }, {
                "id": "1712",
                "quote": "Run, Frodo. Go!",
                "time": "03:06:04.190000"
            }]
        }]

        request_data = {"quote": search_quote}

        # Act
        response = self.client.post('/api/v0/movies/quote/', request_data)

        # Assert
        self.assertEqual(expected_response_status, response.status_code)
        self.assertEqual(expected_response_data, response.data)
        # \----------------------------------------------------------------/

        # /--------------------- User history update ----------------------\
        # Arrange
        request_data = {
            "movie_id": "1",
            "quote": search_quote,
            "subtitle_ids": ["652", "1712"]
        }

        expected_response_status = status.HTTP_200_OK

        # Act
        response = self.client.post('/api/v0/user/testusername/',
                                    request_data,
                                    format='json')

        # Assert
        self.assertEqual(expected_response_status, response.status_code)
        # \----------------------------------------------------------------/

        # /----------------------- History show ---------------------------\
        # Arrange
        expected_response_status = status.HTTP_200_OK
        expected_response_data = [{
            "quote":
            search_quote,
            "movie": {
                "id": "1",
                "title": 'The Lord of the Rings',
                "year": "2001",
                "director": "Peter Jackson",
                "poster": 'http://someurl/',
                "url": 'http://anotherurl/'
            },
            "quotes": [{
                "id": "1712",
                "quote": "Run, Frodo. Go!",
                "time": "03:06:04.190000"
            }, {
                "id": "652",
                "quote": "Run, Frodo!",
                "time": "00:56:54.940000"
            }]
        }]

        # Act
        response = self.client.get('/api/v0/user/testusername/')

        # Assert
        self.assertEqual(expected_response_status, response.status_code)
        self.assertEqual(expected_response_data, response.data)
class Command(BaseCommand):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # pylint: disable-msg=C0103
        self.HOST = 'http://movie-quotes.ru'
        self.STATIC_PATH = '/static/'

        self._movie_repo = MovieRepo()
        self._subtitle_repo = SubtitleRepo()

    def handle(self, *args, **options):
        # pylint: disable-msg=C0103
        # ---------------------- The Lord Of the Rings 2001 ------------------------
        movie_the_lord_of_the_rings_2001 = Movie(
            title='The Lord of The Rings',
            year=2001,
            director='Peter Jackson',
            poster_url=self.HOST + self.STATIC_PATH +
            'the_lord_of_the_rings_2001/poster.jpg',
            video_url=self.HOST + self.STATIC_PATH +
            'the_lord_of_the_rings_2001/movie.mp4')
        dir_name = 'the_lord_of_the_rings_2001'
        self._populate_movie(
            movie_the_lord_of_the_rings_2001, dir_name,
            [self.HOST + self.STATIC_PATH + dir_name + '/' + 'sub.rus.srt'])

        # --------------------------- Forrest Gump 1994 ----------------------------
        movie_forrest_gump_1994 = Movie(
            title='Forrest Gump',
            year=1994,
            director='Robert Zemeckis',
            poster_url=self.HOST + self.STATIC_PATH +
            'forrest_gump_1994/poster.jpg',
            video_url=self.HOST + self.STATIC_PATH +
            'forrest_gump_1994/movie.mp4')
        dir_name = 'forrest_gump_1994'
        self._populate_movie(
            movie_forrest_gump_1994, dir_name,
            [self.HOST + self.STATIC_PATH + dir_name + '/' + 'sub.rus.srt'])

        # --------------------------- The Godfather 1972 ----------------------------
        movie_the_godfather_1972 = Movie(
            title='The Godfather',
            year=1972,
            director='Francis Ford Coppola',
            poster_url=self.HOST + self.STATIC_PATH +
            'the_godfather_1972/poster.jpg',
            video_url=self.HOST + self.STATIC_PATH +
            'the_godfather_1972/movie.mp4')
        dir_name = 'the_godfather_1972'
        self._populate_movie(movie_the_godfather_1972, dir_name, [
            self.HOST + self.STATIC_PATH + dir_name + '/' + 'sub_pt1.rus.srt',
            self.HOST + self.STATIC_PATH + dir_name + '/' + 'sub_pt2.rus.srt'
        ])

    def _download_files(self, tmp_dirname, urls: list) -> List[str]:
        '''
        Downloads files from given urls into temporary directory tmp_dirname.
        Returns list of filenames, which were download succesfully.
        '''
        downloaded_filepaths = []

        os.mkdir(tmp_dirname)
        self.stdout.write(f'created temporary directory: {tmp_dirname}')

        for url in urls:
            self.stdout.write(f'downloading file: {url} ...')
            filepath = tmp_dirname + '/' + url.split('/')[-1]
            urllib.request.urlretrieve(url, filepath)
            downloaded_filepaths.append(filepath)

        return downloaded_filepaths

    def _read_subtitles(self, movie_dirname,
                        subtitle_files_urls: list) -> List[Subtitle]:
        downloaded_files = self._download_files(movie_dirname,
                                                subtitle_files_urls)

        subtitles = []
        for filepath in downloaded_files:
            self.stdout.write(f'reading file with subtitles: {filepath} ...')
            subtitles_part = SubtitleParser.parse(filepath)
            subtitles += subtitles_part

        shutil.rmtree(movie_dirname)
        self.stdout.write(f'deleted temporary directory: {movie_dirname}')

        return subtitles

    def _populate_movie(self, movie, movie_dir_name, subtitle_files_urls):
        movie = self._movie_repo.save(movie)

        subtitles = self._read_subtitles(movie_dir_name, subtitle_files_urls)

        for sub in subtitles:
            sub.movie = movie
            self._subtitle_repo.save(sub)

        self._log(movie, len(subtitles))

    def _log(self, movie, subtitles_count):
        self.stdout.write('Added Movie:')
        self.stdout.write(f'\t{movie.title}\n' + f'\t{movie.year}\n' +
                          f'\t{movie.director}\n' + f'\t{movie.poster_url}\n' +
                          f'\t{movie.video_url}\n')
        self.stdout.write(f'\tsubtitles count {subtitles_count}')
        self.stdout.write('\n')