def test_delete_recipe_in_category_catid_recipeid_not_number(self):
     """
     Test for deleting recipe in category
     """
     response = self.register_user("Patrick", "Walukagga",
                                   "*****@*****.**", "telnetcmd123")
     # registered user login
     rep_login = self.login_user("*****@*****.**", "telnetcmd123")
     # valid token
     headers = dict(Authorization='Bearer ' +
                    json.loads(rep_login.data.decode())['auth_token'])
     category = RecipeCategory(name="Breakfast",
                               description="How to make breakfast",
                               user_id=1)
     category.save()
     response = self.create_category("LunchBuffe",
                                     "How to make lunch buffe", headers)
     recipe = Recipe(name="Rolex for Lunch",
                     cat_id=2,
                     user_id=1,
                     ingredients="oil, Onions, Tomatoes",
                     description="How to make breakfast rolex")
     recipe.save()
     response = self.create_recipe_in_category(2, "Chicken Lunch Buffe",
                                               "oil, Onions,Tomatoes",
                                               "Mix and boil", headers)
     response = self.client.delete('/recipe_category/a/recipes/2',
                                   headers=headers)
     self.assertEqual(response.status_code, 400)
     self.assertIn('Category ID must be an integer', str(response.data))
     # recipe id not number
     response = self.client.delete('/recipe_category/2/recipes/a',
                                   headers=headers)
     self.assertEqual(response.status_code, 400)
     self.assertIn('Recipe ID must be an integer', str(response.data))
 def test_get_single_recipe_in_category(self):
     """
     Test for getting single recipe in category
     """
     response = self.register_user(
         "Patrick", "Walukagga", 
         "*****@*****.**", "telnetcmd123"
     )
     # registered user login
     rep_login = self.login_user("*****@*****.**", "telnetcmd123")
     # valid token
     headers=dict(
         Authorization='Bearer ' + json.loads(
             rep_login.data.decode()
         )['auth_token']
     )
     category = RecipeCategory(
         name="Breakfast",
         description="How to make breakfast",
         user_id=1
     )
     category.save()
     response = self.create_category("LunchBuffe", 
                                     "How to make lunch buffe", 
                                     headers)
     recipe = Recipe(
         name="Rolex for Lunch",
         cat_id=2,
         user_id=1,
         ingredients="oil, Onions, Tomatoes",
         description="How to make breakfast rolex"            
     )
     recipe.save()
     response = self.create_recipe_in_category(2, 
         "Chicken Lunch Buffe",
         "oil, Onions,Tomatoes",
         "Mix and boil",
         headers
     )
     response = self.client.get('/recipe_category/2/recipes/1', 
                                 headers=headers)
     self.assertEqual(response.status_code, 200)
     self.assertIn('Rolex for Lunch', str(response.data))
     self.assertNotIn('Mix and boil', str(response.data))
     # get recipe not yet in database
     response = self.client.get('/recipe_category/2/recipes/4', 
                                 headers=headers)
     self.assertEqual(response.status_code, 404)
     self.assertIn('Recipe not found', str(response.data))
     # get recipe in category not yet in database
     response = self.client.get('/recipe_category/3/recipes/1', 
                                 headers=headers)
     self.assertEqual(response.status_code, 404)
     self.assertIn('Category not found in database', 
                   str(response.data))
示例#3
0
def add(request):
	if request.method == 'GET':
		contents = {
			'title': 'This is Recipe',
			'url': 'urlurlurl',
		}
		return Response(contents)
	if request.method == 'POST':
		title = 'Recipe1'
		url = 'url1url1'
		recipe = Recipe(title=title, url=url)
		recipe.save()
		return Response(contents)
    def test_update_recipe_in_category_with_one_field(self):
        """
        Test for editing recipe in category with one field
        """
        response = self.register_user("Patrick", "Walukagga",
                                      "*****@*****.**", "telnetcmd123")
        # registered user login
        rep_login = self.login_user("*****@*****.**", "telnetcmd123")
        # valid token
        headers = dict(Authorization='Bearer ' +
                       json.loads(rep_login.data.decode())['auth_token'])
        category = RecipeCategory(name="Breakfast",
                                  description="How to make breakfast",
                                  user_id=1)
        category.save()
        response = self.create_category("LunchBuffe",
                                        "How to make lunch buffe", headers)
        recipe = Recipe(name="Rolex for Lunch",
                        cat_id=2,
                        user_id=1,
                        ingredients="oil, Onions, Tomatoes",
                        description="How to make breakfast rolex")
        recipe.save()
        response = self.create_recipe_in_category(2, "Chicken Lunch Buffe",
                                                  "oil, Onions,Tomatoes",
                                                  "Fresh chicken",
                                                  "Mix and boil", headers)
        recipe_data = json.dumps({"name": "Chicken Lunch Buffes"})
        response = self.client.put('/recipe_category/2/recipes/1',
                                   headers=headers,
                                   data=recipe_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Recipe has been updated', str(response.data))
        response = self.client.get('/recipe_category/2/recipes/1',
                                   headers=headers)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Chicken Lunch Buffes', str(response.data))

        recipe_data = json.dumps({"ingredients": "oil, Onions"})
        response = self.client.put('/recipe_category/2/recipes/1',
                                   headers=headers,
                                   data=recipe_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Recipe has been updated', str(response.data))

        recipe_data = json.dumps({"description": "Mix and boils"})
        response = self.client.put('/recipe_category/2/recipes/1',
                                   headers=headers,
                                   data=recipe_data)
        self.assertEqual(response.status_code, 200)
        self.assertIn('Recipe has been updated', str(response.data))
 def test_recipe_crud_when_not_logged_in(self):
     """
     Test for recipe crud when not logged in
     """
     response = self.register_user(
         "Patrick", "Walukagga", 
         "*****@*****.**", "telnetcmd123"
     )
     
     headers=dict(Authorization='Bearer ')
     category = RecipeCategory(
         name="Breakfast",
         description="How to make breakfast",
         user_id=1
     )
     category.save()
     response = self.create_category("LunchBuffe", 
                                     "How to make lunch buffe", 
                                     headers)
     self.assertEqual(response.status_code, 401)
     self.assertIn('Token is missing', str(response.data))
     recipe = Recipe(
         name="Rolex for breakfast",
         cat_id=1,
         user_id=1,
         ingredients="oil, Onions, Tomatoes",
         description="How to make breakfast rolex"            
     )
     recipe.save()
     response = self.create_recipe_in_category(2, 
         "Chicken Lunch Buffe",
         "oil, Onions,Tomatoes",
         "Mix and boil",
         headers
     )
     response = self.client.delete('/recipe_category/2/recipes/2', 
                                 headers=headers)
     self.assertEqual(response.status_code, 401)
     self.assertIn('Token is missing', str(response.data))
     # delete recipe not yet in database
     response = self.client.delete('/recipe_category/2/recipes/4', 
                                 headers=headers)
     self.assertEqual(response.status_code, 401)
     self.assertIn('Token is missing', str(response.data))
     # delete recipe in category not yet in database
     response = self.client.delete('/recipe_category/3/recipes/1', 
                                 headers=headers)
     self.assertEqual(response.status_code, 401)
     self.assertIn('Token is missing', str(response.data))
 def test_search_user_recipes(self):
     """
     Test for searching all user recipes
     """
     response = self.register_user("Patrick", "Walukagga",
                                   "*****@*****.**", "telnetcmd123")
     # registered user login
     rep_login = self.login_user("*****@*****.**", "telnetcmd123")
     # valid token
     headers = dict(Authorization='Bearer ' +
                    json.loads(rep_login.data.decode())['auth_token'])
     category = RecipeCategory(name="Breakfast",
                               description="How to make breakfast",
                               user_id=1)
     category.save()
     response = self.create_category("LunchBuffe",
                                     "How to make lunch buffe", headers)
     recipe = Recipe(name="Rolex for Lunch",
                     cat_id=2,
                     user_id=1,
                     ingredients="oil, Onions, Tomatoes",
                     description="How to make lunch rolex")
     recipe.save()
     recipe = Recipe(name="Rolex for Breakfast",
                     cat_id=1,
                     user_id=1,
                     ingredients="oil, Onions, Tomatoes",
                     description="How to make breakfast rolex")
     recipe.save()
     response = self.create_recipe_in_category(2, "Chicken Lunch Buffe",
                                               "oil, Onions,Tomatoes",
                                               "Fresh chicken",
                                               "Mix and boil", headers)
     response = self.client.get('/search_recipes?q=Rolex', headers=headers)
     self.assertEqual(response.status_code, 200)
     self.assertIn('Rolex for Breakfast', str(response.data))
     self.assertIn('Rolex for Lunch', str(response.data))
     self.assertNotIn('Mix and boil', str(response.data))
     # get recipes in category with limit
     response = self.client.get('/search_recipes?limit=1&page=2',
                                headers=headers)
     self.assertEqual(response.status_code, 200)
     self.assertIn('Rolex for Breakfast', str(response.data))
     self.assertNotIn('Mix and boil', str(response.data))
     # get recipes in category with limit=a&page=b
     response = self.client.get('/search_recipes?limit=a&page=b',
                                headers=headers)
     self.assertEqual(response.status_code, 400)
     self.assertIn('limit and page query parameters should be integers',
                   str(response.data))
     self.assertNotIn('Mix and boil', str(response.data))
示例#7
0
    def put(current_user, self, id):
        """
                      Edit and update a recipe with the specified id
                      ---
                      tags:
                        - recipes
                      parameters:
                        - in: path
                          name: id
                          required: true
                          description: The ID of the recipe to edit
                          type: string
                        - in: body
                          name: recipe
                          required: true
                          description: The title and body of the recipe
                          type: string
                          schema:
                            id: recipe
                            properties:
                                title:
                                    type: string
                                    default: Meat soup
                                body:
                                    type: string
                                    default: Pour, mix, cook
                      security:
                         - TokenHeader: []
                      responses:
                        200:
                          description: A single recipe successfully edited
                          schema:
                            id: recipe
                            properties:
                                title:
                                    type: string
                                    default: Meat soup
                                body:
                                    type: string
                                    default: Pour, mix, cook
                      """

        recipe = Recipe.query.filter_by(id=id, user_id=current_user.id).first()
        if not recipe:
            return {"Error": "A recipe with that Id does not exist"}, 404
        recipe_dict = request.get_json(force=True)
        if 'title' in recipe_dict:
            recipe_title = recipe_dict['title'].strip()
            error, validate_title = recipe.validate_recipe(ctx=recipe_title)
            if validate_title:
                if Recipe.is_unique(id=id,
                                    title=recipe_title,
                                    user_id=current_user.id):
                    recipe.title = recipe_title
                else:
                    abort(status.HTTP_409_CONFLICT,
                          'A recipe with the same title already exists')
            else:
                abort(400, {"error": error})
        if 'body' in recipe_dict:
            recipe_body = recipe_dict['body'].strip()
            body_errors, validate_body = recipe.validate_recipe(
                ctx=recipe_body)
            if validate_body:
                recipe.body = recipe_body
            else:
                abort(400, body_errors)

        dumped_recipe, dumped_errors = recipe_schema.dump(recipe)
        if dumped_errors:
            abort(status.HTTP_400_BAD_REQUEST, dumped_errors)

        recipe.update()
        return {"message": "Recipe successfully edited"}, 200
示例#8
0
    def post(current_user, self, category_id):
        """
        Create a recipe
        ---
        tags:
          - recipes
        parameters:
          - in: path
            name: category_id
            required: true
            description: Category Id
            type: integer
          - in: body
            name: recipe
            required: true
            description: The title of the recipe
            type: string
            schema:
              id: recipe
              properties:
                title:
                  type: string
                  default: Meat soup
                body:
                  type: string
                  default: This is the process of making meat soup
        security:
           - TokenHeader: []
        responses:
          200:
            description: Create a recipe
            schema:
              id: recipe
              properties:
                title:
                  type: string
                  default: Meat soup
                body:
                  type: string
                  default: This is the process of making meat soup
        """

        request_dict = request.get_json()

        if not request_dict:
            abort(status.HTTP_400_BAD_REQUEST, "All fields are required")
        errors = recipe_schema.validate(request_dict)
        if errors:
            abort(status.HTTP_400_BAD_REQUEST, errors)
        recipe_title = request_dict['title'].title()
        recipe_body = request_dict['body'].strip()
        if not Recipe.is_unique(
                id=0, title=recipe_title, user_id=current_user.id):
            abort(status.HTTP_409_CONFLICT,
                  'A recipe with the same title already exists')
        error, validated_title = Recipe.validate_recipe(ctx=recipe_title)
        if not validated_title:
            abort(400, error)
        error_body, validated_body = Recipe.validate_recipe(ctx=recipe_body)
        if not validated_body:
            abort(400, error_body)
        category = Category.query.filter_by(id=category_id,
                                            user_id=current_user.id).first()
        if category:
            recipe = Recipe(title=recipe_title,
                            body=recipe_body,
                            category_id=category.id,
                            user=current_user)
            recipe.add(recipe)
            response = "Recipe uccessfully added!"
            return make_response(jsonify(response), status.HTTP_201_CREATED)
        else:
            abort(400,
                  "A category with Id {0} does not exist".format(category_id))
 def post(self, current_user, cat_id):
     auth_header = request.headers['Authorization']
     if auth_header:
         auth_token = auth_header.split(" ")[1]
     else:
         auth_token = ""
     if auth_token:
         resp = current_user.decode_auth_token(auth_token)
         if not isinstance(resp, str):
             if not cat_id.isdigit():
                 responseObject = {
                     'error': 'Category ID must be an integer',
                     'status': "fail"
                 }
                 return make_response(jsonify(responseObject)), 400
             category = RecipeCategory.query.filter_by(id=cat_id,
                                               user_id=\
                                               current_user.id).\
                                               first()
             if not category:
                 responseObject = {
                     'message': 'Category not found in database'
                 }
                 return make_response(jsonify(responseObject)), 404
             if not request.get_json(force=True):
                 abort(400)
             data = request.get_json(force=True)
             if data:
                 recipe_key_missing_in_body(data)
                 if key_is_not_string(data):
                     response_object = {
                         'error':
                         'Bad request, body field must be of type string'
                     }
                     return jsonify(response_object), 400
                 if data['name'] == "" or data["description"] == "" \
                    or data['ingredients'] == "" or data['directions'] == "":
                     responseObject = {
                         'status': 'fail',
                         'message': 'field names not provided'
                     }
                     return make_response(jsonify(responseObject)), 200
                 if Recipe.query.filter_by(name=' '.join(data['name'].split()).capitalize(),
                                   cat_id=cat_id,
                                   user_id=current_user.id).\
                                   first():
                     responseObject = {
                         'status': 'fail',
                         'message': 'Recipe already exists'
                     }
                     return make_response(jsonify(responseObject)), 202
                 recipe = Recipe(name=' '.join(
                     data['name'].split()).capitalize(),
                                 cat_id=cat_id,
                                 user_id=current_user.id,
                                 ingredients=data['ingredients'],
                                 description=data['description'],
                                 directions=data['directions'])
                 recipe.save()
                 responseObject = {
                     'status': 'success',
                     'message': 'New recipe added to category'
                 }
                 return make_response(jsonify(responseObject)), 201
             else:
                 responseObject = {
                     'status': 'fail',
                     'message': 'New recipe not created!'
                 }
                 return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {'status': 'fail', 'message': resp}
             return make_response(jsonify(responseObject)), 401
     else:
         responseObject = {
             'status': 'fail',
             'message': 'Provide a valid auth token.'
         }
         return make_response(jsonify(responseObject)), 403
示例#10
0
 def create_recipes_list(self, json_list):
     obj_list = []
     for obj in json_list:
         recipe = Recipe.create_obj(obj)
         obj_list.append(recipe)
     return obj_list
 def get(self, current_user, cat_id):
     auth_header = request.headers['Authorization']
     if auth_header:
         auth_token = auth_header.split(" ")[1]
     else:
         auth_token = ""
     if auth_token:
         resp = current_user.decode_auth_token(auth_token)
         if not isinstance(resp, str):
             if not cat_id.isdigit():
                 responseObject = {
                     'error': 'Category ID must be an integer',
                     'status': "fail"
                 }
                 return make_response(jsonify(responseObject)), 400
             category = RecipeCategory.query.filter_by(id=cat_id, 
                                               user_id=\
                                               current_user.id).\
                                               first()
             if not category:
                 responseObject = {
                     'message': 'Category not found in database'
                 }
                 return make_response(jsonify(responseObject)), 404
             '''Returns recipes of current logged in user'''
             recipes = Recipe.query.filter_by(cat_id=cat_id, user_id=\
                                              current_user.id).all()
             # pagination
             limit = request.args.get('limit', 0)
             if limit:
                 limit = int(limit)
                 # offset = int(request.args.get('offset', 0))
                 recipes = Recipe.get_all_limit_offset(cat_id,
                                                     current_user.id, 
                                                     limit)
             recipe_list = []
             for recipe in recipes:
                 recipe_data = {}
                 recipe_data['id'] = recipe.id
                 recipe_data['cat_id'] = recipe.cat_id
                 recipe_data['user_id'] = recipe.user_id
                 recipe_data['name'] = recipe.name
                 recipe_data['ingredients'] = recipe.ingredients
                 recipe_data['description'] = recipe.description
                 recipe_list.append(recipe_data)
             responseObject = {
                 'status': 'sucess',
                 'recipes in category': recipe_list
             }
             return make_response(jsonify(responseObject)), 200
         else:
             responseObject = {
                 'status': 'fail',
                 'message': resp
             }
             return make_response(jsonify(responseObject)), 401
     else:
         responseObject = {
             'status': 'fail',
             'message': 'Provide a valid auth token.'
         }
         return make_response(jsonify(responseObject)), 403