Exemple #1
0
    def setUp(self):
        super(TestMovieHandler, self).setUp()
        # create several movies
        for i in range(3):
            movie = Movie(name="movie%i" % i, description="description%i" % i)
            movie.put()
            self.movie = movie.key()

        post_data = {"email": "*****@*****.**", "password": "******"}
        request = webapp2.Request.blank("/api/auth/login/", POST=post_data)
        response = request.get_response(main.app)
        self.jwt_token = response.headers["JWT"]
def get_movies(_):
    from backend.models import Movie
    movies = Movie.get_all()
    return jsonify({
        'success': True,
        'data': [to_dict(movie) for movie in movies]
    })
def update_movie(_, movie_id):
    from backend.models import Movie
    req_data = request.get_json()
    # We should not inject id, since we are directly passing request data to
    # model's attributes
    if 'id' in req_data:
        del req_data['id']
    movie = Movie.update((Movie.id == movie_id), **req_data)
    return build_orm_json(movie, fail_err_msg='Cannot update movie !!!')
def fetch_movies_cast(_):
    from backend.models import Movie
    movies = Movie.get_all()
    if movies is None or len(movies) == 0:
        return jsonify({'success': False, 'msg': f'No movies found!!!!'})
    res_data = []
    for movie in movies:
        res_data.append({
            'movie': to_dict(movie),
            'actors': [to_dict(actor) for actor in movie.actors]
        })
    return jsonify({'success': True, 'data': res_data})
Exemple #5
0
def append():
    # title = request.form.get('title')
    # year  = request.form.get('year')
    title = request.json.get('title')
    year = request.json.get('year')

    db.session.add(Movie(title=title, year=year))
    db.session.commit()

    return jsonify({
        'status': 'append success',
    })
def create_movie(payload):
    try:
        data = json.loads(request.data)
        name = data.get('title', None)
        release_date = data.get('release_date', None)
        actor_ids = data.get('actors', [])

        if (name is None) or (len(name.strip()) == 0):
            abort(400, 'Movie name is not specified.')

        if ((isinstance(release_date, int) is False) or
                (isValidDateTimeInSeconds(release_date) is False)):
            abort(400, 'Invalid release date')

        actors = Actor.query.filter(Actor.id.in_(actor_ids)).all()

        movie = Movie(title=name, release_date=release_date)
        movie.performing_actors = actors

        movie.insert()

        return jsonify(movie.serialize_with_actors())

    except Exception as error:
        print(sys.exc_info())
        raise error
Exemple #7
0
def forge():
    db.create_all()

    movies = [
        {
            'title': 'My Neighbor Totoro',
            'year': '1988'
        },
        {
            'title': 'Dead Poets Society',
            'year': '1989'
        },
        {
            'title': 'A Perfect World',
            'year': '1993'
        },
        {
            'title': 'Leon',
            'year': '1994'
        },
        {
            'title': 'Mahjong',
            'year': '1996'
        },
        {
            'title': 'Swallowtail Butterfly',
            'year': '1996'
        },
        {
            'title': 'King of Comedy',
            'year': '1999'
        },
        {
            'title': 'Devils on the Doorstep',
            'year': '1999'
        },
        {
            'title': 'WALL-E',
            'year': '2008'
        },
        {
            'title': 'The Pork of Music',
            'year': '2012'
        },
    ]

    for item in movies:
        movie = Movie(title=item['title'], year=item['year'])
        db.session.add(movie)

    db.session.commit()
    click.echo('Done.')
Exemple #8
0
    def post(self):
        logging.debug("MovieListHandler. POST. auth: {}".format(
            self.request.headers.get("Authorization")))
        name = self.request.get("name")
        description = self.request.get("description")

        if not (name and description):
            json_response(
                self,
                {"message": "Name and description fields must be filled"},
                status=400)
            return

        logging.debug(
            "MovieListHandler. POST. name: {}. description: {}. auth: {}".
            format(name, description,
                   self.request.headers.get("Authorization")))

        movie = Movie(name=name, description=description)
        movie.put()

        json_response(self, data=movie.to_dict(), status=201)
def add_movie(payload):

    data = request.get_json()

    if not ('title' in data):
        abort(404)

    title = data.get('title', None)
    new_movie_genrs = data.get('movie_genrs', None)
    new_release_date = data.get('release_date', None)

    # i want body to have title, release_date, and movie_genrs

    try:
        new_movie = Movie(title=title,
                          release_date=new_release_date,
                          movie_genrs=new_movie_genrs)
        new_movie.insert()

        return jsonify({'success': True, 'added': [new_movie.get_movie()]})

    except Exception:
        abort(422)
Exemple #10
0
    def _get_movie(self, movie_id):
        """
        Get movie from datastore by movie_id
        Return status (found/not found) and movie instance
        :param movie_id: str
        """
        # movie_id is always int (based on handler regexp), but dispatcher sends as str
        movie = Movie.get_by_id(int(movie_id))
        if not movie:
            logging.debug(
                "MovieDetailsHandler. Movie not found. movie_id: {}. auth: {}".
                format(movie_id, self.request.headers.get("Authorization")))

            json_response(self, {"message": "No such movie"}, status=404)
            return False, None
        return True, movie
Exemple #11
0
def movie_add(request):
    if request.method == "POST":
        form = MovieForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            movie = Movie()
            movie.title = cd['title']
            movie.content = cd['content']
            movie.created =  time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
            movie.save()
            return HttpResponseRedirect("/backend/movies")
    else:
        form = MovieForm()
        c = {'form':form}
        return render_to_response("backend/movie_add.html",c,context_instance=RequestContext(request))
def create_movie(_):
    from backend.models import Movie
    req_data = request.get_json()
    movie = Movie.insert(**req_data)
    return build_orm_json(movie, fail_err_msg='Not able to insert new actor')
def delete_movie(_, movie_id):
    from backend.models import Movie
    filter_by = (Movie.id == movie_id)
    movie = Movie.delete(filter_by)
    return build_orm_json(movie, fail_err_msg='Not able to delete movie!!!')
 def setUp(self):
     super().setUp()
     self.mock_actor = Actor(name="Test Actor", age=50, gender='M')
     self.mock_movie = Movie(title="Test Movie",
                             release_date=1597277251,
                             performing_actors=[self.mock_actor])
class MoviesApiTestCase(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.mock_actor = Actor(name="Test Actor", age=50, gender='M')
        self.mock_movie = Movie(title="Test Movie",
                                release_date=1597277251,
                                performing_actors=[self.mock_actor])

    def tearDown(self):
        super().tearDown()

    def test_get_all_movies_empty_database(self):
        response = self.client.get(
            '/api/movies',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 0)

    def test_get_all_movies_with_records(self):
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.get(
            '/api/movies',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 1)
        self.assertEqual(len(data['results']), 1)

    def test_get_all_movies_rbac_check(self):
        self.mock_movie.insert()

        response = self.client.get('/api/movies')
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 401)
        self.assertEqual(data['success'], False)

        response = self.client.get(
            '/api/movies',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 1)

        response = self.client.get(
            '/api/movies',
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 1)

        response = self.client.get(
            '/api/movies',
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 1)

    """ Verify GET /api/movies/<movie_id> endpoint """

    def test_get_movie_by_id_empty_database(self):
        response = self.client.get(
            '/api/movies/0',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 404)
        self.assertEqual(data['success'], False)

    def test_get_movie_by_id(self):
        """ Insert records first """
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.get(
            f'/api/movies/{self.mock_movie.id}',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data["id"], self.mock_movie.id)
        self.assertEqual(data["title"], self.mock_movie.title)

    """ Verify POST /api/movies endpoint """

    def test_create_movies_invalid_payload(self):
        payload = {"release_date": round(datetime.now().timestamp())}

        response = self.client.post(
            '/api/movies',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertFalse(data['success'])

    def test_create_movies_valid_payload(self):
        payload = self.mock_movie.serialize()

        response = self.client.post(
            '/api/movies',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])
        self.assertEqual(data["title"], self.mock_movie.title)

    def test_create_movies_rbac_check(self):
        payload = self.mock_movie.serialize()

        response = self.client.post(
            '/api/movies',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.post(
            '/api/movies',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.post(
            '/api/movies',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

    """ Verify PATCH /api/movies/<movie_id> endpoint """

    def test_edit_movie_invalid_movie_id(self):
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.patch(
            '/api/movies/99999',
            json={},
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 404)
        self.assertFalse(data['success'])

    def test_edit_movie_valid_payload(self):
        self.mock_movie.insert()

        payload = {"title": "Updated Movie Title"}

        response = self.client.patch(
            f'/api/movies/{self.mock_movie.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])
        self.assertEqual(data["title"], payload["title"])

    def test_edit_movie_rbac_check(self):
        self.mock_movie.insert()
        payload = {
            "title": "Update Movie Title",
            "age": round(datetime.now().timestamp())
        }

        response = self.client.patch(
            f'/api/movies/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.patch(
            f'/api/movies/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

        response = self.client.patch(
            f'/api/movies/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

    """ Verify DELETE /api/movies/<movie_id> endpoint """

    def test_delete_movie_invalid_movie_id(self):
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.delete(
            '/api/movies/99999',
            json={},
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])

    def test_delete_movie_valid_id(self):
        self.mock_movie.insert()

        response = self.client.delete(
            f'/api/movies/{self.mock_movie.id}',
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["success"])

    def test_delete_movie_rbac_check(self):
        self.mock_movie.insert()

        response = self.client.delete(
            f'/api/movies/{self.mock_movie.id}',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.delete(
            f'/api/movies/{self.mock_movie.id}',
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.delete(
            f'/api/movies/{self.mock_movie.id}',
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["success"])
class ActorsApiTestCase(BaseTestCase):
    def setUp(self):
        super().setUp()
        self.mock_actor = Actor(name="Test Actor", age=50, gender='M')
        self.mock_movie = Movie(title="Test Movie",
                                release_date=1597277251,
                                performing_actors=[self.mock_actor])

    def tearDown(self):
        super().tearDown()

    def test_get_index_page(self):
        response = self.client.get('/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.mimetype, "text/html")

    """ Verify GET /api/actors endpoint """

    def test_get_all_actors_wihtout_token(self):
        response = self.client.get('/api/actors')
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 401)
        self.assertEqual(data['success'], False)

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

        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 0)
        self.assertEqual(len(data['results']), 0)

    def test_get_all_actors_returns_actors(self):
        self.mock_actor.insert()
        self.mock_movie.insert()
        response = self.client.get(
            '/api/actors',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)

        self.assertEqual(response.status_code, 200)
        self.assertEqual(data['count'], 1)
        self.assertEqual(len(data['results']), 1)

    def test_get_all_actors_rbac_check(self):
        response = self.client.get('/api/actors')
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 401)
        self.assertEqual(data['success'], False)

        response = self.client.get(
            '/api/actors',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            '/api/actors',
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)

        response = self.client.get(
            '/api/actors',
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)

    """ Verify GET /api/actors/<actor_id> endpoint """

    def test_get_actor_by_id_empty_database(self):
        response = self.client.get(
            '/api/actors/0',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 404)
        self.assertEqual(data['success'], False)

    def test_get_actor_by_id(self):
        """ Insert records first """
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.get(
            f'/api/actors/{self.mock_actor.id}',
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(data["id"], self.mock_actor.id)
        self.assertEqual(data["name"], self.mock_actor.name)

    """ Verify POST /api/actors endpoint """

    def test_create_actor_invalid_payload(self):
        payload = {"name": "", "age": 0, "gender": "U"}

        response = self.client.post(
            '/api/actors',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 400)
        self.assertFalse(data['success'])

    def test_create_actor_valid_payload(self):
        payload = self.mock_actor.serialize()

        response = self.client.post(
            '/api/actors',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])
        self.assertEqual(data["name"], self.mock_actor.name)

    def test_create_actor_rbac_check(self):
        payload = self.mock_actor.serialize()

        response = self.client.post(
            '/api/actors',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.post(
            '/api/actors',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

        response = self.client.post(
            '/api/actors',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

    """ Verify PATCH /api/actors/<actor_id> endpoint """

    def test_edit_actor_invalid_actor_id(self):
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.patch(
            '/api/actors/99999',
            json={},
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 404)
        self.assertFalse(data['success'])

    def test_edit_actor_valid_payload(self):
        self.mock_actor.insert()

        payload = {"name": "Updated Actor Name"}

        response = self.client.patch(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])
        self.assertEqual(data["name"], payload["name"])

    def test_edit_actor_rbac_check(self):
        self.mock_actor.insert()
        payload = {"name": "Update Actor Name", "age": 99}

        response = self.client.patch(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.patch(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

        response = self.client.patch(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["id"])

    """ Verify DELETE /api/actors/<actor_id> endpoint """

    def test_delete_actor_invalid_actor_id(self):
        self.mock_actor.insert()
        self.mock_movie.insert()

        response = self.client.delete(
            '/api/actors/99999',
            json={},
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data['success'])

    def test_delete_actor_valid_id(self):
        self.mock_actor.insert()

        response = self.client.delete(
            f'/api/actors/{self.mock_actor.id}',
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["success"])

    def test_delete_actor_rbac_check(self):
        self.mock_actor.insert()
        payload = {"name": "Update Actor Name", "age": 99}

        response = self.client.delete(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.assistant_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 403)
        self.assertFalse(data["success"])

        response = self.client.delete(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.director_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["success"])

        response = self.client.delete(
            f'/api/actors/{self.mock_actor.id}',
            json=payload,
            headers={'Authorization': f'Bearer {tokens.producer_jwt_token}'})
        data = json.loads(response.data)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(data["success"])