def test_category_json_with_recipe(self):

        user = UserModel(username="******",
                         password="******",
                         email="*****@*****.**")
        user.save_to_db()

        category = CategoryModel(name='Beverages', user=user)
        recipe = RecipeModel(name='test_recipe',
                             description='Add stuff',
                             user=user,
                             category=category)

        category.save_to_db()
        recipe.save_to_db()

        expected = {
            'id': 3,
            'name': 'Beverages',
            'recipes': [{
                'name': 'test_recipe',
                'description': 'Add stuff'
            }]
        }

        # print(category.json())
        self.assertDictEqual(category.json(), expected)
    def test_category_json(self):

        UserModel(username="******",
                  password="******",
                  email="*****@*****.**").save_to_db()

        category = CategoryModel(name='Beverages', created_by=self.user)
        expected = {'id': None, 'name': 'Beverages', 'recipes': []}

        self.assertDictEqual(category.json(), expected)
Exemplo n.º 3
0
    def post(self):
        """
        This method creates a recipe category
        """
        try:
            parser = reqparse.RequestParser()
            parser.add_argument('name', type=category_name_validator)
            parser.add_argument('description', type=str, default='')
            args = parser.parse_args()
            name = args.get("name")
            description = args["description"]
            user_id = get_jwt_identity()
            # set parsed items to an object of model class
            category = CategoryModel(name=name,
                                     description=description,
                                     created_by=user_id)  #

            if not name:
                response = jsonify(
                    {'message': 'Please provide a name for the category'})
                response.status_code = 400
                return response
            user_id = get_jwt_identity()
            # check for similar name on category created by current user
            categories = CategoryModel.query.filter_by(
                name=name, created_by=user_id).first()  # bucks
            if categories:
                response = jsonify(
                    {'message': 'You already have a category with that name'})
                response.status_code = 400
                return response
            try:
                category.save_to_db()
                message = {'message': 'Category created Successfully'}
                response = marshal(category, categories_serializer)
                response.update(message)
                response.status_code = 201
                return response

            except Exception as e:
                logging.exception("message")
                response = jsonify(
                    {'message': 'There was an error saving the category'})
                response.status_code = 400

                return response
        except BadRequest:
            response = jsonify({
                'message':
                'You json data is deformed, correct that and '
                'continue!'
            })
            response.status_code = 400

            return response
Exemplo n.º 4
0
 def get(self, category_id, recipe_id=None):
     """
     This method gets a specific recipe from a category
     """
     if recipe_id is None:
         response = jsonify({'message': 'Method not allowed, check url'})
         response.status_code = 400
         return response
     category = CategoryModel.find_by_id(category_id)
     recipe = RecipeModel.query.filter_by(id=recipe_id,
                                          category_id=category_id).first()
     user_id = get_jwt_identity()
     if category:
         if recipe:
             if recipe.created_by == user_id:
                 return marshal(recipe, recipes_serializer)
             else:
                 response = jsonify(
                     {'message': 'You are not authorized to view this'})
                 response.status_code = 401
                 return response
         else:
             response = jsonify({'message': 'The recipe does not exist'})
             response.status_code = 404
             return response
     else:
         response = jsonify({'message': 'the category does not exist'})
         response.status_code = 404
         return response
Exemplo n.º 5
0
    def delete(self, category_id):
        """
        This method deletes a user's category by id
        """
        if category_id is None:
            response = jsonify({'message': 'Method not allowed(DELETE)'})
            response.status_code = 400
            return response
        # query whether the category exists
        category = CategoryModel.find_by_id(category_id)
        user_id = get_jwt_identity()

        # if it exists delete and commit changes to db
        if category:
            if category.created_by == user_id:  # if category belongs to
                # logged in user
                category.delete_from_db()

                response = jsonify({
                    'message':
                    'The category and its items have been '
                    'successfully deleted'
                })
                response.status_code = 200
                return response
            else:
                abort(401, message='You are not authorized to delete this')
        else:  # else return a 204 response
            response = {
                'message':
                'The category you are trying to delete '
                'does not exist'
            }, 404

            return response
Exemplo n.º 6
0
def create_category(user_id, display_name):
    category = CategoryModel(category_id=str(uuid.uuid4()),
                             display_name=display_name,
                             created_at=datetime.utcnow(),
                             user_id=user_id)
    db.session.add(category)
    db.session.commit()
    return category
Exemplo n.º 7
0
    def test_create_category(self):
        user = UserModel(username='******', password='******')

        category = CategoryModel(name='categoryname', user=user)

        self.assertEqual(
            category.name, 'categoryname',
            "The name of the category after creation in wrong!!.")
Exemplo n.º 8
0
    def test_category_relationship(self):

        user = UserModel(username="******",
                         password="******",
                         email="*****@*****.**")
        user.save_to_db()

        category = CategoryModel(name='test_category', user=user)
        recipe = RecipeModel(name='test_recipe',
                             description='Add stuff',
                             user=user,
                             category=category)

        category.save_to_db()
        recipe.save_to_db()

        self.assertEqual(recipe.category.name, 'test_category')
Exemplo n.º 9
0
def seed_categories():
    categories_names = [
        'Soccer', 'Basketball', 'Baseball', 'Frisbee', 'Snowboarding',
        'Rock Climbing', 'Foosball', 'Skating', 'Hockey'
    ]
    categories = map(lambda name: CategoryModel(name=name, slug=slugify(name)),
                     categories_names)
    db.session.bulk_save_objects(categories)
    db.session.commit()
    def test_category_relationship(self):

        user = UserModel(username="******",
                         password="******",
                         email="*****@*****.**")
        user.save_to_db()

        category = CategoryModel(name='Beverages', user=user)
        category.save_to_db()
        recipe = RecipeModel(name='test_recipe',
                             description="Add stuff",
                             user=user,
                             category=category)
        recipe.save_to_db()

        self.assertEqual(category.recipes.count(), 1)

        self.assertEqual(category.recipes.first().name, 'test_recipe')
Exemplo n.º 11
0
    def test_create_category(self):

        query = { "name": category1.get("name") }
        create_category1 = upsert(CategoryModel, query=query, update=category1)

        assert create_category1.name == category1.get("name")
        assert create_category1.color == category1.get("color")

        found = CategoryModel.objects(**query).first()
        assert found.name == category1.get("name")
        assert found.color == category1.get("color")
    def test_crud(self):

        UserModel(username="******",
                  password="******",
                  email="*****@*****.**").save_to_db()

        category = CategoryModel(name='Beverages', created_by=self.user)

        self.assertIsNone(CategoryModel.find_by_name('Beverages'))

        category.save_to_db()

        self.assertIsNotNone(CategoryModel.find_by_name('Beverages'))

        category.delete_from_db()

        self.assertIsNone(CategoryModel.find_by_name('Beverages'))
    def test_create_category_recipes_empty(self):

        UserModel(username="******",
                  password="******",
                  email="*****@*****.**").save_to_db()

        category = CategoryModel(name='Beverages', created_by=self.user)

        self.assertListEqual(
            category.recipes.all(), [],
            "The categories recipes length was not 0 even though "
            "no recipes were added.")
Exemplo n.º 14
0
def get_categories():
    """
    Get all categories
    :return: Response contains list of categories
    """

    categories = CategoryModel.get_all_categories()

    categories_schema = CategorySchema(many=True)
    result = categories_schema.dump(categories)

    return send_success(result.data)
Exemplo n.º 15
0
def update_item(item_id, user_info):
    """
    Update an item, find by its id
    Protected
    :param item_id: item id
    :param user_info: decoded access token
    :return:
    """

    data = request.get_json()

    # Validate json
    schema = ItemSchema(dump_only=('slug', 'id'))
    errors = schema.validate(data)
    if len(errors) > 0:
        raise ValidationError('Post data error', errors)

    # Validate item id
    item = ItemModel.get_user_item(item_id, user_info.get('id'))
    if item is None:
        raise ValidationError('Item not found!')

    # Validate item name
    slug = slugify(data['name'])
    if slug != item.slug:
        valid = ItemModel.validate_slug(slug)

        if not valid:
            raise ValidationError('An item with the same name has already been added. Please try another name.')

    # Validate category id
    category = CategoryModel.find(category_id=data['category_id'])
    if category is None:
        raise ValidationError('Invalid category Id')

    item.name = data['name']
    item.description = data['description']
    item.category_id = data['category_id']
    item.slug = slugify(item.name)

    db.session.add(item)
    db.session.commit()

    item_schema = ItemSchema()
    result = item_schema.dump(item)

    return send_success(result.data)
Exemplo n.º 16
0
def get_category(category_slug):
    """
    Get details for a category. Find by its slug
    :param category_slug: category slug
    :return: Response details for that categories, including its items
    """

    category = CategoryModel.find(slug=category_slug)

    if category is None:
        raise ValidationError('Category not found!')

    category_schema = CategorySchema(load_only=(
        'items.category',
        'items.description',
        'items.user_id',
    ))
    result = category_schema.dump(category)

    return send_success(result.data)
Exemplo n.º 17
0
    def setUp(self):
        self.app = self.create_app().test_client()
        self.database = db
        db.create_all()

        # Add dummy data for test purposes
        user = UserModel(username="******")
        user.email = '*****@*****.**'
        user.password = '******'
        user.save_to_db()

        user2 = UserModel(username="******")
        user2.email = '*****@*****.**'
        user2.password = '******'
        user2.save_to_db()

        user3 = UserModel(username="******")
        user3.email = '*****@*****.**'
        user3.password = '******'
        user3.save_to_db()

        category1 = CategoryModel(name="somerecipecategory", created_by=1)
        category1.save_to_db()
        category2 = CategoryModel(name="somerecipecategory2", created_by=1)
        category2.save_to_db()

        recipe1 = RecipeModel(name="somerecipe1",
                              description="Add one spoonfuls of...",
                              created_by=1,
                              category_id=1)
        recipe1.save_to_db()
        recipe2 = RecipeModel(name="somerecipe2",
                              description="Add two spoonfuls of...",
                              created_by=1,
                              category_id=2)
        recipe2.save_to_db()
Exemplo n.º 18
0
def create_item(user_info):
    """
    Add an item
    Protected
    :param user_info: decoded access token
    :return:
    """

    data = request.get_json()

    # Validate json
    schema = ItemSchema(dump_only=('slug', 'id'))
    errors = schema.validate(data)
    if len(errors) > 0:
        raise ValidationError('Post data error', errors)

    # Validate item name
    valid = ItemModel.validate_slug(slugify(data['name']))

    if not valid:
        raise ValidationError('An item with the same name has already been added. Please try another name.')

    # Validate category id
    category = CategoryModel.find(category_id=data['category_id'])

    if category is None:
        raise ValidationError('Invalid category Id')

    item = ItemModel(name=data['name'], description=data['description'], category_id=data['category_id'],
                     user_id=user_info['id'], slug=slugify(data['name']))

    db.session.add(item)
    db.session.commit()

    item_schema = ItemSchema()
    result = item_schema.dump(item)

    return send_success(result.data)
Exemplo n.º 19
0
    def test_crud(self):

        user = UserModel(username="******",
                         password="******",
                         email="*****@*****.**")
        user.save_to_db()
        category = CategoryModel(name='Beverages', user=user)
        recipe = RecipeModel(name='African tea',
                             description='add stuf',
                             user=user,
                             category=category)

        self.assertIsNone(
            RecipeModel.find_by_name(''),
            "Found a recipe with name {}, but expected not to.".format(
                recipe.name))

        recipe.save_to_db()

        self.assertIsNotNone(RecipeModel.find_by_name('African tea'))

        recipe.delete_from_db()

        self.assertIsNone(RecipeModel.find_by_name('African tea'))
Exemplo n.º 20
0
    def post(self, category_id):
        """
        This method handles requests for adding recipe to storage by id
        """

        category = CategoryModel.find_by_id(category_id)
        user_id = get_jwt_identity()
        if category:
            if category.created_by != user_id:
                response = jsonify({
                    'message':
                    'You are not authorized to use the '
                    'category'
                })
                response.status_code = 401
                return response
            parser = reqparse.RequestParser()
            parser.add_argument('name', type=recipe_name_validator)
            parser.add_argument('description', type=str, default='')
            args = parser.parse_args()

            name = args["name"]
            description = args["description"]

            if not name:
                response = jsonify(
                    {'message': 'Please provide a name for the recipe'})
                response.status_code = 400
                return response

            recipe = RecipeModel(name=name,
                                 description=description,
                                 category_id=category_id,
                                 created_by=user_id)

            if not name:
                response = jsonify(
                    {'message': 'Please provide a name for the recipe'})
                response.status_code = 400
                return response

            try:
                RecipeModel.query.filter_by(name=name).one()
                response = jsonify(
                    {'message': 'That name is already taken, try again'})
                response.status_code = 400
                return response

            except:
                try:
                    recipe.save_to_db()
                    message = {'message': 'Recipe added Successfully!'}
                    response = marshal(recipe, recipes_serializer)
                    response.update(message)
                    return response, 201

                except:
                    response = jsonify(
                        {'message': 'There was an error saving the '
                         'recipe'})
                    response.status_code = 400
                    return response
        else:
            response = jsonify({
                'message':
                'You json data is deformed, correct that '
                'and continue!'
            })
            response.status_code = 404
            return response
Exemplo n.º 21
0
    def put(self, category_id, recipe_id):
        """
        This method edits a recipe in a category of a user
        """
        try:
            if recipe_id is None:
                response = jsonify(
                    {'message': 'Method not allowed, check url'})
                response.status_code = 400
                return response
            try:
                category = CategoryModel.find_by_id(category_id)
                recipe = RecipeModel.query.filter_by(id=recipe_id).one()
            except:
                response = jsonify(
                    {'message': 'The category or recipe does not exist'})
                response.status_code = 404
                return response
            user_id = get_jwt_identity()
            if recipe.created_by == user_id:
                if category and recipe:
                    parser = reqparse.RequestParser()
                    parser.add_argument('name', type=recipe_name_validator)
                    parser.add_argument('description', type=str, default='')

                    args = parser.parse_args()

                    name = args["name"]
                    description = args["description"]

                    data = {'name': name, 'description': description}
                    if not name or name is None:
                        data = {'description': description}

                    recipe_info = RecipeModel.query.filter_by(
                        id=recipe_id).update(data)

                    try:
                        db.session.commit()
                        response = jsonify({'message': 'Recipe updated'})
                        response.status_code = 200
                        return response

                    except Exception:
                        response = jsonify({
                            'message':
                            'There was an error updating the '
                            'recipe'
                        })
                        response.status_code = 500
                        return response
                else:
                    response = jsonify(
                        {'message': 'The category or recipe does not exist'})
                    response.status_code = 404
                    return response
            else:
                response = jsonify(
                    {'message': 'You are not authorized to edit this'})
                response.status_code = 401
                return response
        except BadRequest:
            response = jsonify({
                'message':
                'Your json seems to be deformed, correct it '
                'and try again!'
            })
            response.status_code = 400
            return response
Exemplo n.º 22
0
    def put(self, category_id):
        """
        This method edits the user's category
        """
        try:
            category = CategoryModel.find_by_id(category_id)
            user_id = get_jwt_identity()
            # if the category exists get new changes
            if category:
                if category.created_by == user_id:
                    parser = reqparse.RequestParser()
                    parser.add_argument('name', type=category_name_validator)
                    parser.add_argument('description', type=str, default='')
                    args = parser.parse_args()

                    name = args["name"]
                    description = args["description"]
                    data = {'name': name, 'description': description}
                    if not name or name is None:
                        data = {'description': description}

                    # update changes and commit to db
                    item_info = CategoryModel.query.filter_by(
                        id=category_id).update(data)

                    try:
                        db.session.commit()
                        response = jsonify(
                            {'message': 'Category has been updated!'})
                        response.status_code = 201
                        return response

                    except Exception:
                        response = jsonify({
                            'message':
                            'There was an error updating the '
                            'category'
                        })
                        response.status_code = 500
                        return response
                else:
                    abort(401, message='You are not authorized to edit this')
            else:
                response = jsonify({
                    'message':
                    'The category you are '
                    'trying to edit does not '
                    'exist'
                })
                response.status_code = 404
                return response

        except BadRequest:

            response = jsonify({
                'message':
                'Your json seems to be deformed, correct it '
                'and try again!'
            })
            response.status_code = 400
            return response