Example #1
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):
        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)
Example #3
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)
    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)
Example #5
0
    def test_save(self):
        # Arrange
        movie_name = "Black swan"
        year = 2011
        director = "Darren Aronofsky"
        poster_url = "https://blackswan/poster"
        video_url = "https://blackswan/video"
        movie = Movie(title = movie_name, year = year, director = director,
                      poster_url = poster_url, video_url = video_url)

        quote = "I am gonna die"

        subtitle = Subtitle(quote = quote, start_time = datetime.now(),
                            end_time = datetime.now(), movie = movie)
        expected_movie = {'title': movie_name, 'year': year, 'director': director,
                          'poster_url': poster_url, 'video_url': video_url}
        subtitle_repo = SubtitleRepo()

        # Act
        subtitle_repo.save(subtitle)
        subtitle_orm = SubtitleORM.objects.all().filter(quote = quote).first()

        # Assert
        self.assertIsNotNone(subtitle_orm)
        movie_orm = subtitle_orm.movie
        self.assertIsNotNone(movie_orm)
        actual_movie = {'title': movie_orm.title,
                        'year': movie_orm.year, 'director': movie_orm.director,
                        'poster_url': movie_orm.poster_url, 'video_url': movie_orm.video_url}
        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()
Example #7
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)
Example #8
0
    def test_find_by_substring_in_quote_all_matched(self):
        # Arrange
        quote = "!"
        expected_quotes = ["Monday is a bad day!!!", "Hello, Vasya!", "Hello, Petya!"]
        subtitle_repo = SubtitleRepo()

        # Act
        subtitles = subtitle_repo.find_by_quote(quote)
        actual_quotes = [subtitle.quote for subtitle in subtitles]

        # Assert
        self.assertEqual(expected_quotes, actual_quotes)
Example #9
0
    def test_find_by_substring_in_quote_no_matched(self):
        # Arrange
        quote = "Good"
        expected_quotes = []
        subtitle_repo = SubtitleRepo()

        # Act
        subtitles = subtitle_repo.find_by_quote(quote)
        actual_quotes = [subtitle.quote for subtitle in subtitles]

        # Assert
        self.assertEqual(expected_quotes, actual_quotes)
Example #10
0
    def test_save__try_to_update_with_none_values(self):
        # Arrange
        movie_name = "Black swan"
        year = 2011
        director = "Darren Aronofsky"
        poster_url = "https://blackswan/poster"
        video_url = "https://blackswan/video"

        movie_orm = MovieORM.objects.create(
            title=movie_name,
            year=year,
            director=director,
            poster_url=poster_url,
            video_url=video_url
        )

        quote = "I am gonna die"
        start_time = time(hour=0, minute=0, second=37, microsecond=673000)
        end_time = time(hour=0, minute=0, second=40, microsecond=673000)

        subtitle_orm = SubtitleORM.objects.create(
            quote=quote,
            start_time=start_time,
            end_time=end_time,
            movie=movie_orm
        )

        expected_subtitle_data = {
            'quote': quote,
            'start_time': start_time,
            'end_time': end_time,
            'movie_id': movie_orm.id
        }


        # Act
        subtitle_repo = SubtitleRepo()

        existing_subtitle = subtitle_repo.get(subtitle_orm.id)
        existing_subtitle.quote = None
        existing_subtitle.movie = None
        actual_subtitle = subtitle_repo.save(existing_subtitle)

        actual_subtitle_data = {
            'quote': actual_subtitle.quote,
            'start_time': actual_subtitle.start_time,
            'end_time': actual_subtitle.end_time,
            'movie_id': actual_subtitle.movie.id
        }

        # Assert
        self.assertDictEqual(expected_subtitle_data, actual_subtitle_data)
Example #11
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)
    def test__deserialize_subtitle_and_update_from_repo(self):
        # Arrange
        incomplete_subtitle_json = f'{{"id": "{self.subtitle_1.id}", \
"quote": "{self.subtitle_1.quote}"}}'

        # Act
        subtitle_repo = SubtitleRepo()
        subtitle_serializer = SubtitleSerializer()

        incomplete_subtitle = subtitle_serializer.deserealize(
            incomplete_subtitle_json)
        actual_subtitle = subtitle_repo.save(incomplete_subtitle)

        # Assert
        compare(self.subtitle_1, actual_subtitle)
Example #13
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}')
Example #14
0
    def test_get_subtitle(self):
        # Arrange
        quote = "I am a new one"
        subtitle_orm = SubtitleORM.objects.create(quote = quote,
                                                  start_time = datetime.now(),
                                                  end_time = datetime.now(),
                                                  movie = self.movie_orm)
        id = subtitle_orm.id
        expected_subtitle = {'id': id, 'quote': quote}
        subtitle_repo = SubtitleRepo()

        # Act
        subtitle = subtitle_repo.get(id)
        actual_subtitle = {'id': subtitle.id, 'quote': subtitle.quote}

        # Assert
        self.assertDictEqual(expected_subtitle, actual_subtitle)
    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
    def test__execute__no_matches(self):
        # Arrange
        quote = "This qoute exists nowhere"

        expected_matches = []

        # Act
        match_repo = MatchRepo()
        subtitle_repo = SubtitleRepo()
        usecase = SearchByQuoteUsecase(match_repo, subtitle_repo, quote)
        actual_matches = usecase.execute()

        # Assert
        self.assertEqual(expected_matches, actual_matches)
    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)
Example #18
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)
Example #19
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)
    def test__execute__one_subtitle(self):
        # Arrange
        quote = "Joe Biden"

        expected_matches = [
            Match(quote=quote,
                  movie=self.movie_2,
                  subtitles=[self.sub_6_movie_2])
        ]

        # Act
        match_repo = MatchRepo()
        subtitle_repo = SubtitleRepo()
        usecase = SearchByQuoteUsecase(match_repo, subtitle_repo, quote)
        actual_matches = usecase.execute()

        # Assert
        compare(expected_matches, actual_matches)
    def post(self, request):
        # **Возвращаемый результат**
        try:
            quote = request.data['quote']
        except KeyError:
            
            try:
                quote = request.query_params['quote']
            except KeyError:
                """
                Отсутствие цитаты для поиска (некорректный запрос):
                
                - код 400
                
                - текст ошибки
                
                """
                return Response(
                    status=status.HTTP_400_BAD_REQUEST,
                    data='Не обнаружено цитаты для поиска'
                )

        search_usecase = SearchByQuoteUsecase(
            MatchRepo(),
            SubtitleRepo(),
            quote
        )

        result = search_usecase.execute()

        """
        Успешный поиск фильмов по цитате:
            
        - код 200
            
        - словарь с данными о найденных фильмах
            
        """
        return Response(
            status=status.HTTP_200_OK,
            data=[match.to_dict() for match in result]
        )
    def test__execute__quote_Hello(self):
        # Arrange
        quote = "Hello"

        expected_matches = [
            Match(quote=quote,
                  movie=self.movie_1,
                  subtitles=[self.sub_1_movie_1, self.sub_3_movie_1]),
            Match(quote=quote,
                  movie=self.movie_2,
                  subtitles=[self.sub_5_movie_2])
        ]

        # Act
        match_repo = MatchRepo()
        subtitle_repo = SubtitleRepo()
        usecase = SearchByQuoteUsecase(match_repo, subtitle_repo, quote)
        actual_matches = usecase.execute()

        # Assert
        compare(expected_matches, actual_matches)
    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)
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')
    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)
Example #27
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)