Пример #1
0
def test_actor_to_dict():
    actor = Actor(name='Actor', age=10, gender='F')
    assert actor.to_dict() == {
        'id': None,
        'name': 'Actor',
        'age': 10,
        'gender': 'F'
    }
Пример #2
0
def add_actor():
    try:
        data = json.loads(request.data)
        actor = Actor(**data)
        actor.insert()
        return jsonify({'success': True, 'actor': actor.format()}), 201
    except Exception as error:
        raise error
Пример #3
0
 def test_delete_actors_cd(self):
     '''Test delete_actors as Casting Director '''
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     res = self.client().delete(f'/actors/{actor.id}',
                                headers={'Authorization': bearer('cd')})
     self.assertEqual(res.status_code, 200)
     self.assertIsInstance(res.json['deleted'], dict)
     self.assertEqual(res.json['deleted']['id'], actor.id)
Пример #4
0
def create_actor(payload):
    try:
        actor = Actor(name=request.json['name'],
                      age=request.json['age'],
                      gender=request.json['gender'])
        actor.insert()
        return jsonify({'success': True, 'actors': [actor.long()]}), 200

    except Exception as e:
        print(e)
        abort(422)
def add_actor():
    if request.method == 'POST':
        try:
            username = request.form['username']
            user = TwitterUser(username)
            if user.existence == True:
                name = user.name
                name = unidecode(name)
                f = Actor(id=int(user.id), username=username, name=name)
                db.session.add(f)
                db.session.commit()
                if not scheduler.get_job(job_id=user.id):
                    scheduler.add_job(tweets_job,
                                      'interval',
                                      minutes=10080,
                                      replace_existing=False,
                                      id=user.id,
                                      args=[user.id])
                print("Ator", username, "adicionado")
            else:
                print("Usuario", username, "não existe!")
        except:
            pass

    return redirect("/")
Пример #6
0
 def setUp(self):
     """Define test variables and initialize app"""
     self.app = app
     self.client = self.app.test_client
     database_path = os.getenv('TEST_DATABASE_URI')
     setup_db(self.app, database_path)
     self.actor_id = ''
     with self.app.app_context():
         self.db = SQLAlchemy()
         self.db.init_app(self.app)
         self.db.create_all()
         # Add an actor
         self.actor = Actor(name="Mugerwa Fred",
                            dob='1996-05-07',
                            gender="male")
         self.actor.insert()
         self.actor_id = self.actor.id
Пример #7
0
def add_actors(actors):
    for a in actors:
        if 'birthday' not in a or not a['birthday'] or len(a['birthday']) < 8:
            continue
        actor = Actor(a["id"], a["name"], a["birthday"], a["biography"][:3000],
                      a["profile_path"])
        db.session.merge(actor)
        db.session.commit()
        print("Added " + a["name"])
Пример #8
0
def create_actors(actors):
    for csfd_id, actor in actors.items():
        a = Actor(
            name=actor['name'],
            simple_name=actor['simple_name'],
            csfd_id=actor['csfd_id'],
        )
        db.session.add(a)
        actor['db_entry'] = a
    db.session.commit()
Пример #9
0
 def test_api_get_actor_account_date_zero_reports(self):
     user = TwitterUser('Renova_BR')
     user = Actor(user.id, user.username, user.name)
     with app.app_context():
         TestAPIRoutes.setUp()
         db.session.add(user)
         db.session.commit()
         response = api_get_actor_account_date('Renova_BR', '01-01-2018')
         TestAPIRoutes.tearDown()
     assert '500' == json.loads(response.get_data().decode())['code']
Пример #10
0
    def test_api_get_actors(self):
        user = TwitterUser('CNN')
        user = Actor(user.id, user.username, user.name)

        with app.app_context():
            TestAPIRoutes.setUp()
            db.session.add(user)
            db.session.commit()
            response = api_get_actors()
            TestAPIRoutes.tearDown()

        assert '{"actors":["CNN"],"code":"200","length":1,"message":"Success"}\n' == response.get_data(
        ).decode()
Пример #11
0
 def test_delete_actors_ca(self):
     '''Test delete_actors as Casting Assistant '''
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     res = self.client().delete(f'/actors/{actor.id}',
                                headers={'Authorization': bearer('ca')})
     self.assertEqual(res.status_code, 401)
     actor.delete()
Пример #12
0
def register():
    """
    Route pour enregistrer un nouvel utilisateur
    """
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        actor = Actor(actor_name=form.actor_name.data,
                      email=form.email.data,
                      phone=form.phone.data,
                      manufacturer=form.manufacturer.data)
        actor.set_password(form.password.data)
        db.session.add(actor)
        db.session.flush(
        )  # pour obtenir l'identifiant de l'acteur qui vient d'être ajouté

        adress = Adress(street=form.street.data,
                        city=form.city.data,
                        state=form.state.data,
                        zip_code=form.zip_code.data,
                        country=form.country.data,
                        id=actor.id)
        db.session.add(adress)
        db.session.commit()
        flash('Félicitations, vous êtes maintenant inscrit ✅')

        global manufacturer
        if actor.manufacturer != 1:
            manufacturer = False
        else:
            manufacturer = True

        login_user(actor, remember=True)

        return redirect(url_for('index'))
    return render_template('register.html', title='Register', form=form)
Пример #13
0
def register():
    """
    Route to register a new user
    """
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        actor = Actor(actor_name=form.actor_name.data,
                      email=form.email.data,
                      phone=form.phone.data,
                      manufacturer=form.manufacturer.data)
        actor.set_password(form.password.data)
        db.session.add(actor)
        db.session.flush()  # to get the id of the actor just added

        adress = Adress(street=form.street.data,
                        city=form.city.data,
                        state=form.state.data,
                        zip_code=form.zip_code.data,
                        country=form.country.data,
                        id=actor.id)
        db.session.add(adress)
        db.session.commit()
        flash('Congratulations, you are now registered!')

        global manufacturer
        if actor.manufacturer != 1:
            manufacturer = False
        else:
            manufacturer = True

        login_user(actor, remember=True)

        return redirect(url_for('index'))
    return render_template('register.html', title='Register', form=form)
Пример #14
0
    def test_api_get_actor_account_date(self):
        csv_content = 'nome;seguidores;tweets;seguindo;curtidas;retweets;favorites;hashtags;mentions\n923257662569148417;1715;146;193;104;0;0;;;\n'
        a = ActorReport('01-01-2018', '12:00', csv_content.encode())
        user = TwitterUser('Renova_BR')
        user = Actor(user.id, user.username, user.name)
        with app.app_context():
            TestAPIRoutes.setUp()
            db.session.add(a)
            db.session.add(user)
            db.session.commit()
            response = api_get_actor_account_date('Renova_BR', '01-01-2018')
            TestAPIRoutes.tearDown()

        assert '{"12:00":{"date":"01-01-2018","followers_count":"193","following_count":"104","likes_count":"0","name":"1715","tweets_count":"0","username":"******"},"code":"200","message":["Success"]}\n' == response.get_data(
        ).decode()
Пример #15
0
def actor():
    actors = Actor.query.order_by(Actor.name.asc()).all()
    form = ActorForm()
    if form.validate_on_submit():
        a = Actor(name=form.name.data)
        db.session.add(a)
        db.session.commit()
        flash('Actor added to db')
        return redirect(url_for('admin.actor'))
    return render_template('admin_movie_friend.html',
                           title='admin.movie_friend',
                           collection=actors,
                           collection_name='actors',
                           header='Actor',
                           form=form)
Пример #16
0
 def test_api_get_actor_account_date_tweets(self):
     csv_content = 'Data;Texto;Autor(RT);Retweets;Curtidas;Hashtags;Mentions\n2018-06-08 14:25:30;@MarcioQuessada Pressionar e discutir. Essa mudanca dificilmente vai vir deles!;;0;0; ;MarcioQuessada;'
     user = TwitterUser('Renova_BR')
     user = Actor(user.id, user.username, user.name)
     t = TweetReport('12-06-2018', '19:00', user.id, csv_content.encode())
     with app.app_context():
         TestAPIRoutes.setUp()
         db.session.add(t)
         db.session.add(user)
         db.session.commit()
         response = api_get_actor_account_date_tweets(
             'Renova_BR', '12-06-2018')
         TestAPIRoutes.tearDown()
     assert '{"code":"200","message":"Success","tweets":[{"date":"2018-06-08 14:25:30","hashtags":" ","likes":"0","mention":"MarcioQuessada","retweets":"0","rt_author":"","text":"@MarcioQuessada Pressionar e discutir. Essa mudanca dificilmente vai vir deles!"}]}\n' == response.get_data(
     ).decode()
Пример #17
0
 def test_patch_actors_ca(self):
     '''Test patch_actors as Casting Assistant '''
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     res = self.client().patch(f'/actors/{actor.id}',
                               json={
                                   'name': 'Test Actorrrr',
                                   'age': 45,
                                   'gender': 'F'
                               },
                               headers={'Authorization': bearer('ca')})
     self.assertEqual(res.status_code, 401)
     actor.delete()
Пример #18
0
def test_actor_model():
    first_actor = Actor(name='ACTOR1', age=10, gender='F')
    first_actor.save()
    second_actor = Actor(name='ACTOR2', age=20, gender='M')
    second_actor.save()

    saved_actors = Actor.query.all()
    assert len(saved_actors) == 2

    first_saved_actor = Actor.query.get(1)
    assert first_saved_actor.name == 'ACTOR1'
    assert first_saved_actor.age == 10
    assert first_saved_actor.gender == 'F'

    second_saved_actor = Actor.query.get(2)
    assert second_saved_actor.name == 'ACTOR2'
    assert second_saved_actor.age == 20
    assert second_saved_actor.gender == 'M'

    first_saved_actor.remove()
    assert Actor.query.get(1) is None
Пример #19
0
 def test_post_movie_actors_ca(self):
     '''Test post_actors as Casting Assistant '''
     movie = Movie(title='Test Movie', release_date='2020-01-15')
     movie.insert()
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     res = self.client().post(f'/movies/{movie.id}/actors',
                              json={'actor': {
                                  'id': actor.id
                              }},
                              headers={'Authorization': bearer('ca')})
     self.assertEqual(res.status_code, 401)
     actor.delete()
     movie.delete()
Пример #20
0
 def test_post_movie_actors_ep(self):
     '''Test post_actors as Executive Producer '''
     movie = Movie(title='Test Movie', release_date='2020-01-15')
     movie.insert()
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     res = self.client().post(f'/movies/{movie.id}/actors',
                              json={'actor': {
                                  'id': actor.id
                              }},
                              headers={'Authorization': bearer('ep')})
     self.assertEqual(res.status_code, 200)
     self.assertIsInstance(res.json["movie"], dict)
     actor.delete()
     movie.delete()
Пример #21
0
    def setUp(self):
        """Define test variables and initialize app."""
        self.app = create_app()
        self.client = self.app.test_client
        self.database_name = "capstoneDB_test"

        self.database_path = os.getenv("TEST_DATABASE_URL")
        setup_db(self.app, self.database_path, self.database_name)

        self.movie = Movie(title="instersteller", release_date="2014-4-4")
        self.actor = Actor(name="tom cruise", age=55, gender="M")

        self.casting_producer_jwt = os.getenv("CASTING_PRODUCER_JWT")
        self.casting_director_jwt = os.getenv("CASTING_DIRECTOR_JWT")
        self.casting_assistant_jwt = os.getenv("CASTING_ASSISTANT_JWT")

        # binds the app to the current context
        with self.app.app_context():
            db = SQLAlchemy()
            db.init_app(self.app)
            # create all tables
            db.create_all()
Пример #22
0
 def test_delete_movie_actors_cd(self):
     '''Test delete_actors as Casting Director '''
     movie = Movie(title='Test Movie', release_date='2020-01-15')
     movie.insert()
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     movie.actors.append(actor)
     movie.update()
     res = self.client().delete(f'/movies/{movie.id}/actors',
                                json={'actor': {
                                    'id': actor.id
                                }},
                                headers={'Authorization': bearer('cd')})
     self.assertEqual(res.status_code, 200)
     self.assertIsInstance(res.json["movie"], dict)
     movie.delete()
     actor.delete()
Пример #23
0
 def test_patch_actors_cd(self):
     '''Test patch_actors as Casting Director '''
     actor = Actor(name='Test Actor', age=40, gender='M')
     actor.insert()
     res = self.client().patch(f'/actors/{actor.id}',
                               json={
                                   'name': 'Test Actorrrr',
                                   'age': 45,
                                   'gender': 'F'
                               },
                               headers={'Authorization': bearer('cd')})
     self.assertEqual(res.status_code, 200)
     self.assertIsInstance(res.json["actor"], dict)
     actor = Actor.query.get(actor.id)
     self.assertEqual(actor.name, 'Test Actorrrr')
     self.assertEqual(actor.age, 45)
     self.assertEqual(actor.gender, 'F')
     actor.delete()
Пример #24
0
    def setUp(self):
        self.app = create_app(TestConfig)
        self.client = self.app.test_client

        self.app_context = self.app.app_context()
        self.app_context.push()

        self.CASTING_ASSISTANT_HEADER = {
            'Authorization': 'bearer ' + os.environ['CAST_ASSIST_JWT']
        }
        self.CASTING_DIRECTOR_HEADER = {
            'Authorization': 'bearer ' + os.environ['CAST_DIR_JWT']
        }
        self.EXEC_PRODUCER_HEADER = {
            'Authorization': 'bearer ' + os.environ['EXEC_PROD_JWT']
        }

        db.create_all()
        a = Actor(name='Tom Cruise', age=40, gender='male')
        db.session.add(a)
        db.session.commit()
        m = Movie(title='The Green Mile', release_date='2019-01-01')
        db.session.add(m)
        db.session.commit()
Пример #25
0
def create_db():
    with app.app_context():
        db.init_app(app)

        db.create_all()

        created_anime = []
        created_characters = []
        created_actors = []
        created_manga = []

        existing_character = {}
        existing_actor = {}
        existing_manga = {}

        for anime_file_num in os.listdir(data_folder + jikan_anime):
            with open(data_folder + jikan_anime +
                      anime_file_num) as anime_datafile:
                print("anime: " + anime_file_num)
                anime_json_data = json.load(anime_datafile)

                anime_title = anime_json_data['title']
                anime_aired = anime_json_data['aired']
                anime_score = anime_json_data['score'][0]
                anime_episodes = anime_json_data['episodes']
                anime_synopsis = anime_json_data['synopsis']

                anime_type = anime_json_data['type']
                if anime_type == None:
                    anime_type = 'Unknown'

                anime_pic = anime_json_data['image']
                anime_status = anime_json_data['status']
                anime_youtube = None
                try:
                    if anime_json_data['youtubeVideoId'] != '':
                        anime_youtube = anime_json_data['youtubeVideoId']

                except KeyError:
                    pass

                genre_list = []
                for genre in anime_json_data['genre']:
                    genre_list.append(genre[1])

                anime_genre = ', '.join(genre_list)

                anime_rating = anime_json_data['rating']

                final_anime = Anime(title=anime_title,
                                    aired=anime_aired,
                                    score=anime_score,
                                    num_episodes=anime_episodes,
                                    synopsis=anime_synopsis,
                                    media_type=anime_type,
                                    picture=anime_pic,
                                    status=anime_status,
                                    youtube_id=anime_youtube,
                                    rating=anime_rating,
                                    genre=anime_genre)
                created_anime.append(final_anime)

                # Character
                if 'character' in anime_json_data:
                    for character_list_object in anime_json_data['character']:
                        if character_list_object['role'] == 'Main':
                            anime_character_id = (
                                character_list_object['url'].split('/'))[4]
                            if anime_character_id in existing_character:
                                final_anime.characters.add(created_characters[
                                    existing_character[anime_character_id]])
                                continue

                            if os.path.exists(data_folder + jikan_character +
                                              anime_character_id):
                                with open(data_folder + jikan_character +
                                          anime_character_id
                                          ) as character_datafile:
                                    character_json_data = json.load(
                                        character_datafile)

                                    try:
                                        character_name = character_json_data[
                                            'name']
                                    except KeyError:
                                        continue

                                    character_japanese_name = character_json_data[
                                        'name-japanese']
                                    character_about = character_json_data[
                                        'about']
                                    character_pic = character_json_data[
                                        'image']
                                    if not character_pic:
                                        character_pic = None

                                    print("Creating character with MAL ID:" +
                                          anime_character_id)
                                    final_character = Character(
                                        name=character_name,
                                        japanese_name=character_japanese_name,
                                        about=character_about,
                                        picture=character_pic)
                                    created_characters.append(final_character)
                                    existing_character[
                                        anime_character_id] = len(
                                            created_characters) - 1

                                    final_anime.characters.add(final_character)

                                    # Voice actor
                                    if 'voice-actor' in character_list_object:
                                        for actor_list_object in character_list_object[
                                                'voice-actor']:
                                            actor_id = (
                                                actor_list_object['url'].split(
                                                    '/'))[4]

                                            if actor_id in existing_actor:
                                                final_character.actors.add(
                                                    created_actors[
                                                        existing_actor[
                                                            actor_id]])
                                                final_anime.actors.add(
                                                    created_actors[
                                                        existing_actor[
                                                            actor_id]])
                                                continue

                                            actor_name = actor_list_object[
                                                'name']

                                            if os.path.exists(data_folder +
                                                              jikan_person +
                                                              actor_id):
                                                print("actor id: " + actor_id)
                                                with open(data_folder +
                                                          jikan_person +
                                                          actor_id
                                                          ) as actor_datafile:
                                                    actor_json_data = json.load(
                                                        actor_datafile)

                                                    actor_language = actor_json_data[
                                                        'language']
                                                    actor_given_name = None

                                                    try:
                                                        actor_given_name = actor_json_data[
                                                            'given-name']
                                                    except KeyError:
                                                        pass

                                                    actor_birthday = actor_json_data[
                                                        'birthday']
                                                    actor_pic = None if actor_json_data[
                                                        'image'] == "" else actor_json_data[
                                                            'image']
                                                    actor_website = None if actor_json_data[
                                                        'website'] == "" else actor_json_data[
                                                            'website']

                                                    final_actor = Actor(
                                                        name=actor_name,
                                                        language=actor_language,
                                                        given_name=
                                                        actor_given_name,
                                                        birthday=actor_birthday,
                                                        picture=actor_pic,
                                                        website=actor_website)
                                                    created_actors.append(
                                                        final_actor)
                                                    existing_actor[
                                                        actor_id] = len(
                                                            created_actors) - 1

                                                    final_character.actors.add(
                                                        final_actor)
                                                    final_anime.actors.add(
                                                        final_actor)

                # Manga
                if 'related' in anime_json_data:
                    related = anime_json_data['related']
                    if 'Adaptation' in anime_json_data['related']:
                        adaptation_obj = related['Adaptation']

                        manga_id_list = []
                        if isinstance(adaptation_obj[0], list):
                            for list_obj in related['Adaptation']:
                                tokens = list_obj[1].split('/')
                                manga_id_list.append(tokens[2])

                        else:
                            manga = related['Adaptation']
                            manga = manga[1].split('/')
                            manga_id_list.append(manga[2])

                        for manga_id in manga_id_list:
                            if manga_id in existing_manga:
                                final_anime.mangas.add(
                                    created_manga[existing_manga[manga_id]])

                            elif os.path.exists(data_folder + jikan_manga +
                                                manga_id):
                                print("manga id: " + manga_id)
                                with open(data_folder + jikan_manga +
                                          manga_id) as manga_datafile:
                                    manga_json_data = json.load(manga_datafile)

                                    manga_title = None
                                    if manga_json_data['type'] == 'Novel':
                                        manga_title = manga_json_data[
                                            'title'] + ' - (Novel)'
                                    else:
                                        manga_title = manga_json_data['title']

                                    manga_title_english = None
                                    try:
                                        manga_title_english = manga_json_data[
                                            'title-english']
                                    except KeyError:
                                        pass

                                    manga_title_japanese = None
                                    try:
                                        manga_title_japanese = manga_json_data[
                                            'japanese']
                                    except KeyError:
                                        pass

                                    list_authors = []
                                    for json_author in manga_json_data[
                                            'author']:
                                        list_authors.append(
                                            json_author['name'])
                                    manga_author = ', '.join(list_authors)

                                    manga_published = manga_json_data[
                                        'published']

                                    manga_score = None
                                    try:
                                        manga_score = manga_json_data['score'][
                                            0]
                                    except KeyError:
                                        pass

                                    manga_chapters = manga_json_data[
                                        'chapters']
                                    manga_synopsis = manga_json_data[
                                        'synopsis']
                                    manga_type = manga_json_data['type']
                                    manga_picture = manga_json_data['image']
                                    manga_status = manga_json_data['status']

                                    manga_genre_list = []
                                    for genre in manga_json_data['genre']:
                                        manga_genre_list.append(genre[1])

                                    manga_genre = ', '.join(manga_genre_list)

                                    final_manga = Manga(
                                        title=manga_title,
                                        title_english=manga_title_english,
                                        title_japanese=manga_title_japanese,
                                        author=manga_author,
                                        published=manga_published,
                                        score=manga_score,
                                        num_chapters=manga_chapters,
                                        synopsis=manga_synopsis,
                                        media_type=manga_type,
                                        picture=manga_picture,
                                        status=manga_status,
                                        genre=manga_genre)
                                    created_manga.append(final_manga)
                                    existing_manga[manga_id] = len(
                                        created_manga) - 1

                                    final_anime.mangas.add(final_manga)

                                    for manga_character in manga_json_data[
                                            'character']:
                                        manga_character_id = (
                                            manga_character['url'].split('/')
                                        )[4]

                                        if manga_character_id in existing_character:
                                            final_manga.characters.add(
                                                created_characters[
                                                    existing_character[
                                                        manga_character_id]])
                                        else:
                                            if os.path.exists(
                                                    data_folder +
                                                    jikan_character +
                                                    manga_character_id):
                                                with open(
                                                        data_folder +
                                                        jikan_character +
                                                        manga_character_id
                                                ) as manga_character_datafile:
                                                    manga_character_json_data = json.load(
                                                        manga_character_datafile
                                                    )

                                                    try:
                                                        manga_character_name = manga_character_json_data[
                                                            'name']
                                                    except KeyError:
                                                        continue

                                                    manga_character_japanese_name = manga_character_json_data[
                                                        'name-japanese']
                                                    manga_character_about = manga_character_json_data[
                                                        'about']
                                                    manga_character_pic = manga_character_json_data[
                                                        'image']

                                                    print(
                                                        "Creating manga character: "
                                                        + manga_character_id)
                                                    final_manga_character = Character(
                                                        name=
                                                        manga_character_name,
                                                        japanese_name=
                                                        manga_character_japanese_name,
                                                        about=
                                                        manga_character_about,
                                                        picture=
                                                        manga_character_pic)
                                                    created_characters.append(
                                                        final_manga_character)
                                                    existing_character[
                                                        manga_character_id] = len(
                                                            created_characters
                                                        ) - 1

                                                    final_manga.characters.add(
                                                        final_manga_character)

        for anime in created_anime:
            db.session.add(anime)

        for character in created_characters:
            db.session.add(character)

        for actor in created_actors:
            db.session.add(actor)

        for manga in created_manga:
            db.session.add(manga)

        db.session.commit()
        print("I HAVE COMITTED")
Пример #26
0
class ActorsTestCase(unittest.TestCase):
    """This class represents the Actors test case """
    def setUp(self):
        """Define test variables and initialize app"""
        self.app = app
        self.client = self.app.test_client
        database_path = os.getenv('TEST_DATABASE_URI')
        setup_db(self.app, database_path)
        self.actor_id = ''
        with self.app.app_context():
            self.db = SQLAlchemy()
            self.db.init_app(self.app)
            self.db.create_all()
            # Add an actor
            self.actor = Actor(name="Mugerwa Fred",
                               dob='1996-05-07',
                               gender="male")
            self.actor.insert()
            self.actor_id = self.actor.id

    def tearDown(self):
        with self.app.app_context():
            for movie in Movie.query.all():
                movie.delete()
            self.db.session.query(Actor).delete()
            self.db.session.commit()

    def test_get_actors_with_assistant_token(self):
        response = self.client().get(
            '/api/v1/actors',
            headers={'Authorization': f'Bearer {assistant_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actors'][0].keys(), mock_data.actor.keys())
        self.assertEqual(data['total-actors'], 1)

    def test_get_actors_with_director_token(self):
        response = self.client().get(
            '/api/v1/actors',
            headers={'Authorization': f'Bearer {director_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actors'][0].keys(), mock_data.actor.keys())
        self.assertEqual(data['total-actors'], 1)

    def test_get_actors_with_producer_token(self):
        response = self.client().get(
            '/api/v1/actors',
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actors'][0].keys(), mock_data.actor.keys())
        self.assertEqual(data['total-actors'], 1)

    def test_get_actors_with_invalid_page_number(self):
        page = 100  # This page doesn't exist
        response = self.client().get(
            f'/api/v1/actors?page={page}',
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 404)
        self.assertEqual(data, mock_data.not_found_error_response)

    def test_get_actor_with_assistant_token(self):
        actor = Actor.query.get(self.actor_id)

        response = self.client().get(
            f'/api/v1/actors/{self.actor_id}',
            headers={'Authorization': f'Bearer {assistant_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], actor.name)
        self.assertEqual(data['actor']['age'], actor.get_age())
        self.assertEqual(data['actor']['gender'], actor.gender)

    def test_get_actor_with_director_token(self):
        actor = Actor.query.get(self.actor_id)

        response = self.client().get(
            f'/api/v1/actors/{self.actor_id}',
            headers={'Authorization': f'Bearer {director_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], actor.name)
        self.assertEqual(data['actor']['age'], actor.get_age())
        self.assertEqual(data['actor']['gender'], actor.gender)

    def test_get_actor_with_producer_token(self):
        actor = Actor.query.get(self.actor_id)

        response = self.client().get(
            f'/api/v1/actors/{self.actor_id}',
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], actor.name)
        self.assertEqual(data['actor']['age'], actor.get_age())
        self.assertEqual(data['actor']['gender'], actor.gender)

    def test_get_actor_with_invalid_actor_id(self):
        actor_id = 0  # This actor ID doesn't exist
        response = self.client().get(
            f'/api/v1/actors/{actor_id}',
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 404)
        self.assertEqual(data, mock_data.not_found_error_response)

    def test_add_actor_with_assistant_token(self):
        actor = {
            'name': 'Jane Vanfon',
            'dob': '1999-01-01',
            'gender': 'female'
        }

        response = self.client().post(
            '/api/v1/actors',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {assistant_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 403)
        self.assertEqual(data, mock_data.forbidden_error_response)

    def test_add_actor_with_director_token(self):
        actor = {
            'name': 'Jane Vanfon',
            'dob': '1999-01-01',
            'gender': 'female'
        }

        response = self.client().post(
            '/api/v1/actors',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {director_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 201)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], actor['name'])
        self.assertIsInstance(data['actor']['age'], int)
        self.assertEqual(data['actor']['gender'], actor['gender'])

    def test_add_actor_with_producer_token(self):
        actor = {
            'name': 'Jane Vanfon',
            'dob': '1999-01-01',
            'gender': 'female'
        }

        response = self.client().post(
            '/api/v1/actors',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 201)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], actor['name'])
        self.assertIsInstance(data['actor']['age'], int)
        self.assertEqual(data['actor']['gender'], actor['gender'])

    def test_edit_actor_with_assistant_token(self):
        actor = {'name': 'James Peters'}

        response = self.client().patch(
            f'/api/v1/actors/{self.actor_id}',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {assistant_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 403)
        self.assertEqual(data, mock_data.forbidden_error_response)

    def test_edit_actor_with_director_token(self):
        actor = {'name': 'James Peters'}
        expected_actor = Actor.query.get(self.actor_id)

        response = self.client().patch(
            f'/api/v1/actors/{self.actor_id}',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {director_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], expected_actor.name)
        self.assertEqual(data['actor']['age'], expected_actor.get_age())
        self.assertEqual(data['actor']['gender'], expected_actor.gender)

    def test_edit_actor_with_producer_token(self):
        actor = {'name': 'James Peters'}
        expected_actor = Actor.query.get(self.actor_id)

        response = self.client().patch(
            f'/api/v1/actors/{self.actor_id}',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['actor']['name'], expected_actor.name)
        self.assertEqual(data['actor']['age'], expected_actor.get_age())
        self.assertEqual(data['actor']['gender'], expected_actor.gender)

    def test_edit_actor_with_invalid_actor_id_in_request(self):
        actor = {'name': 'James Peters'}
        actor_id = 0  # This actor ID doesn't exist

        response = self.client().patch(
            f'/api/v1/actors/{actor_id}',
            content_type='application/json',
            data=json.dumps(actor),
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 422)
        self.assertEqual(data, mock_data.unprocessable_error_response)

    def test_delete_actor_with_assistant_token(self):

        response = self.client().delete(
            f'/api/v1/actors/{self.actor_id}',
            headers={'Authorization': f'Bearer {assistant_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 403)
        self.assertEqual(data, mock_data.forbidden_error_response)

    def test_delete_actor_with_director_token(self):

        response = self.client().delete(
            f'/api/v1/actors/{self.actor_id}',
            headers={'Authorization': f'Bearer {director_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['deleted'], self.actor_id)

    def test_delete_actor_with_producer_token(self):

        response = self.client().delete(
            f'/api/v1/actors/{self.actor_id}',
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])
        self.assertEqual(data['deleted'], self.actor_id)

    def test_delete_actor_with_invalid_actor_id(self):
        actor_id = 0  # This actor ID doesn't exist

        response = self.client().delete(
            f'/api/v1/actors/{actor_id}',
            headers={'Authorization': f'Bearer {producer_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 422)
        self.assertEqual(data, mock_data.unprocessable_error_response)
Пример #27
0
def test_actor_non_negative_age():
    with pytest.raises(ValidationError, match='Age is negative'):
        Actor(age=-1)
from modules.twitter_user import TwitterUser
import json
from app.models import Actor
from app import db
from unidecode import unidecode

# Adding actors from helpers/politicians.json
print("Adding Actors")
actors = json.load(open("helpers/politicians.json"))
for row in actors:
    username = row["twitter_handle"]
    user = TwitterUser(username)
    if user.existence == True:
        name = user.name
        name = unidecode(name)
        if not Actor.query.filter_by(id=user.id).first():
            f = Actor(id = int(user.id), username=username, name= name)
            db.session.add(f)
            db.session.commit()
            print(name, "added")






Пример #29
0
def insert_row(row):
    """
    This was another meathod I was trying out so that I could separate the data into better tables instead of just
    one, but time was an issue to get this project done.
    """
    session = Config.Session()
    try:
        movie = Movie(color=row[0],
                      director_name=row[1],
                      num_critic_for_reviews=int(row[2]),
                      duration=int(row[3]),
                      actor_2_name=row[6],
                      gross=int(row[8]),
                      genres=row[9],
                      actor_1_name=row[10],
                      movie_name=row[11],
                      num_voted_users=int(row[12]),
                      cast_total_facebook_likes=int(row[13]),
                      actor_3_name=row[14],
                      facenumber_in_poster=int(row[15]),
                      plot_keywords=row[16],
                      movie_imdb_link=row[17],
                      num_user_for_review=row[18],
                      language=row[19],
                      country=row[20],
                      content_rating=row[21],
                      budget=int(row[22]),
                      title_year=int(row[23]),
                      imdb_score=float(row[25]),
                      aspect_ration=float(row[26]),
                      movie_facebook_likes=int(row[27]))
        print(movie)
        session.add(movie)
        session.commit()
    except:
        print("Movie was not added to database")
    try:
        actor_1 = Actor(actor_name=row[10],
                        movie_name=row[11],
                        facebook_likes=int(row[7]))
        session.add(actor_1)
        session.commit()
    except:
        print("Actor 1 was not added to database.")
    try:
        actor_2 = Actor(actor_name=row[6],
                        movie_name=row[11],
                        facebook_likes=int(row[24]))
        session.add(actor_2)
        session.commit()
    except:
        print("Actor 2 was not added to database.")
    try:
        actor_3 = Actor(actor_name=row[14],
                        movie_name=row[11],
                        facebook_likes=int(row[5]))
        session.add(actor_3)
        session.commit()
    except:
        print("Actor 3 was not added to database.")
    try:
        director = Director(director_name=row[1],
                            movie_name=row[11],
                            facebook_likes=int(row[4]))
        session.add(director)
        session.commit()
    except:
        print("Director was not added  to database.")
Пример #30
0
    movie = Movie.query.filter(Movie.title == title, Movie.year == year,
                               Movie.director == director).first()
    if not movie:
        movie = Movie()
        movie.api_id = movie_data[column_pos.get('api_id')]
        sys.stdout.write('\rNEW Movie %s' % movie.api_id)
        movie.title = movie_data[column_pos.get('title')]
        movie.year = movie_data[column_pos.get('year')]
        movie.director = movie_data[column_pos.get('director')]
        # Set actors
        actors = [
            movie_data[column_pos.get('actor_1')],
            movie_data[column_pos.get('actor_2')],
            movie_data[column_pos.get('actor_3')]
        ]
        for actor_name in [a for a in actors if a]:
            actor = Actor.query.filter(Actor.name == actor_name).first()
            if not actor:
                actor = Actor(actor_name)
            movie.actors.append(actor)
        # Set IMDB url
        movie.imdb_url = get_imdb_url(movie.title, movie.year, movie.director)
        db.session.add(movie)
    else:
        sys.stdout.write('\rOLD Movie %s' % movie.api_id)

    location = Location(movie.id, movie_data[column_pos.get('locations')])
    movie.locations.append(location)
    db.session.commit()
sys.stdout.write('\r\n')