Пример #1
0
 def setUp(self):
     """ Runs before each test """
     # service.init_db()
     db.drop_all()    # clean up the last tests
     db.create_all()  # create new tables
     Product(pid=1,pname="Athens Table", pdesc='Stupid Table', pcat="Table", pprice=20, pcond="Boxed",pinv=2, prev="", prat=5).save()
     Product(pid=2,pname="Rome Chair", pdesc='Stupid Chair', pcat="Chair", pprice=40, pcond="Boxed", pinv=2, prev="",prat=8).save()
     self.app = service.app.test_client()
Пример #2
0
    def mutate(self, info, name, price, bakery_id):
        bakery = BakeryModel.query.get(bakery_id)

        product = ProductModel(name=name, price=price)

        product.bakery = bakery

        db.session.add(product)
        db.session.commit()

        return ProductMutation(product=product)
Пример #3
0
 def get(self):
     """ Return all the products"""
     name = request.args.get('name')
     category = request.args.get('category')
     if name:
         products = Product.find_by_name(name)
     elif category:
         products = Product.find_by_category(category)
     else:
         products = Product.all()
     results = [product.serialize() for product in products]
     return results, status.HTTP_200_OK
Пример #4
0
 def post(self):
     """
     Creates a Product
     This endpoint will create a Product based the data in the body that is posted
     """
     try:
         check_content_type('application/json')
         product = Product(1, "", "", "", 0, "", 0, "", 0)
         # product = Product()
         # app.logger.info((api.payload))
         product.deserialize(api.payload)
         product.save()
         message = product.serialize()
         location_url = api.url_for(ProductCollection,
                                    item_id=product.id,
                                    _external=True)
         # return make_response(jsonify(message), status.HTTP_201_CREATED,
         #                      {
         #                          'Location': location_url
         #                      })
         return product.serialize(), status.HTTP_201_CREATED, {
             'Location': location_url
         }
     except ValidationError:
         return request_validation_error('Invalid Data')
Пример #5
0
def dbcreate():
    Product.logger.info(Product.query.with_entities(Product.id).all())
    if ((Product.query.with_entities(Product.id).all()) != []):
        return
    Product(1, 'Desk', 'Wooden study desk', 'Furniture', 50, 'Boxed', 500,
            "Great product", 8).save()
    Product(2, 'Chair', 'Mesh office chair', 'Furniture', 30, 'Boxed', 1500,
            "Nothing great", 9).save()
    Product(3, 'Tshirt', 'Black printed tshirt', 'Clothing', 20, 'Boxed', 900,
            "So so", 8).save()
    Product(4, 'Trousers', 'Brown linen trouser', 'Clothing', 35, 'Boxed', 300,
            "Awesome!", 10).save()
    Product(5, 'Mattress', 'Memory foam mattress', 'Furniture', 100, 'Boxed',
            2000, "Still checking", 7).save()
    Product.logger.info(Product.query.with_entities(Product.id).all())
Пример #6
0
 def test_find_by_category(self):
     """ Find Products by Category """
     Product(1, "Couch", "White couch", "Furniture", 200, "Boxed", 50, " ",
             8).save()
     Product(2, "Table", "Oak table", "Home", 150, "Boxed", 100, " ",
             7).save()
     products = Product.find_by_category("Furniture")
     self.assertEqual(products[0].id, 1)
     self.assertEqual(products[0].category, "Furniture")
     self.assertEqual(products[0].name, "Couch")
     self.assertEqual(products[0].description, "White couch")
     self.assertEqual(products[0].price, 200)
     self.assertEqual(products[0].condition, "Boxed")
     self.assertEqual(products[0].inventory, 50)
     self.assertEqual(products[0].rating, 8)
Пример #7
0
 def test_find_by_pricerange(self):
     """ Find a Product by PriceRange """
     Product(1, "Couch", "White couch", "Furniture", 200, "Boxed", 50, " ",
             8).save()
     Product(2, "Table", "Oak table", "Furniture", 150, "Boxed", 100, " ",
             7).save()
     products = Product.search_by_price(160, 210)
     self.assertEqual(products[0].id, 1)
     self.assertEqual(products[0].category, "Furniture")
     self.assertEqual(products[0].name, "Couch")
     self.assertEqual(products[0].description, "White couch")
     self.assertEqual(products[0].price, 200)
     self.assertEqual(products[0].condition, "Boxed")
     self.assertEqual(products[0].inventory, 50)
     self.assertEqual(products[0].rating, 8)
Пример #8
0
 def test_update_product_review(self):
     """ Update an existing Product Review """
     product = Product.find_by_name('Athens Table')[0]
     resp = self.app.put('/products/review',
                         query_string='id=1&newrev=Average',
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     new_json = json.loads(resp.data)
     self.assertEqual(new_json['review'], 'Average')
     product = Product.find_by_name('Athens Table')[0]
     resp = self.app.put('/products/review',
                         query_string='id=1&newrev=Awesome',
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     new_json = json.loads(resp.data)
     self.assertEqual(new_json['review'], 'Average|Awesome')
Пример #9
0
 def get(self):
     """List all the product by their updated date"""
     app.logger.info("List products by updated date")
     sorted_products = Product.sort_by_date()
     results = [product.serialize() for product in sorted_products]
     # return make_response(jsonify(results), status.HTTP_200_OK)
     return results, status.HTTP_200_OK
Пример #10
0
 def put(self):
     """Updates product review with review provided as newrev"""
     app.logger.info("Fetching the product")
     item = request.args.get("id")
     # item = int((product_arguments3.parse_args())['id'])
     check_content_type("application/json")
     if not item:
         return request_validation_error("Missing Parameter product ID")
     product = Product.find_by_id(item)
     newreview = request.args.get('newrev')
     # newreview =  str ((product_arguments2.parse_args())['rev'])
     print(newreview)
     if not product:
         # api.abort(status.HTTP_404_NotFound,'Product with id: %s was not found' % str(item))
         return not_found("Product with id {} not found".format(item))
     if newreview == '' or newreview is None:
         return request_validation_error(
             "Review should be an empty string atleast")
     elif not product.review:
         print(newreview)
         product.review = str(newreview)
     else:
         product.review = str(product.review) + "|" + str(newreview)
         print(product.review)
     product.update()
     return product.serialize(), status.HTTP_200_OK
Пример #11
0
 def test_delete_a_product(self):
     """ Delete a Product """
     product = Product(1, "Couch", "White couch", "Furniture", 200, "Boxed",
                       50, " ", 8)
     product.save()
     self.assertEqual(len(Product.all()), 1)
     # delete the product and make sure it isn't in the database
     product.delete()
     self.assertEqual(len(Product.all()), 0)
Пример #12
0
def deleteproduct(item_id):
    app.logger.info("Deleting the product for the id provided")
    product = Product.find_by_id(item_id)
    if not product:
        return make_response("Product does not exist",
                             status.HTTP_204_NO_CONTENT)
    product.delete()
    return make_response(" ", status.HTTP_204_NO_CONTENT)
Пример #13
0
 def test_get_product(self):
     """ Get a single Product """
     # get the id of a product
     product = Product.find_by_name('Athens Table')[0]
     resp = self.app.get('/products/{}'.format(product.id),
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     data = json.loads(resp.data)
     self.assertEqual(data['name'], product.name)
Пример #14
0
def list_products():
    """ Return all the products"""
    products = []
    name = request.args.get('name')
    app.logger.info(name)
    category = request.args.get('category')
    id = request.args.get("id")
    if name:
        products = Product.find_by_name(name)
    elif category:
        products = Product.find_by_category(category)
    elif id:
        products = Product.find_by_id(id)
    else:
        products = Product.all()

    results = [product.serialize() for product in products]
    return make_response(jsonify(results), status.HTTP_200_OK)
Пример #15
0
 def delete(self, item_id):
     """ Deletes a product by ID"""
     app.logger.info("Deleting the product for the id provided")
     product = Product.find_by_id(item_id)
     # if not product:
     #     return make_response("Product does not exist", status.HTTP_204_NO_CONTENT)
     if product:
         product.delete()
     # return make_response(" ", status.HTTP_204_NO_CONTENT)
     return " ", status.HTTP_204_NO_CONTENT
Пример #16
0
 def get(self, item_id):
     """ Finds a product by ID"""
     app.logger.info('Finding a Product with id [{}]'.format(item_id))
     if not isinstance(item_id, int):
         return request_validation_error("Invalid Product ID")
     product = Product.find_by_id(item_id)
     if product:
         # app.logger.info(product)
         return product.serialize(), status.HTTP_200_OK
     else:
         return not_found('Product ID was not found')
Пример #17
0
 def test_update_product_rating(self):
     """ Update an existing Product Rating """
     product = Product.find_by_name('Athens Table')[0]
     # new_product = dict(id=1,name='Athens Table', description='Stupid Table', category="Fancy Table",price=20, condition="Boxed", inventory=2, review="", rating=8)
     # data = json.dumps(new_product)
     resp = self.app.put('/products/rating',
                         query_string='id=1&stars=10',
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     new_json = json.loads(resp.data)
     self.assertEqual(new_json['rating'], 7)
Пример #18
0
 def test_update_product(self):
     """ Update an existing Product """
     product = Product.find_by_name('Athens Table')[0]
     new_product = dict(id=1,name='Athens Table', description='Stupid Table', category="Fancy Table",price=20, condition="Boxed", inventory=2, review="", rating=8)
     data = json.dumps(new_product)
     resp = self.app.put('/products/{}'.format(product.id),
                         data=data,
                         content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     new_json = json.loads(resp.data)
     self.assertEqual(new_json['category'], 'Fancy Table')
Пример #19
0
def pricerange():
    app.logger.info("Fetching products by provided price range")
    # app.logger.info(request.args.get('minimum'))
    minimum = request.args.get('minimum')
    maximum = request.args.get('maximum')
    tlist = list(Product.search_by_price(minimum, maximum))
    result = []
    for i in tlist:
        result.append(i.serialize())
    # app.logger.info(result)
    return make_response(jsonify(result), status.HTTP_200_OK)
Пример #20
0
 def test_delete_product(self):
     """ Delete a Product """
     product = Product.find_by_name('Athens Table')[0]
     # save the current number of products for later comparison
     product_count = self.get_product_count()
     resp = self.app.delete('/products/{}'.format(product.id),
                            content_type='application/json')
     self.assertEqual(resp.status_code, status.HTTP_204_NO_CONTENT)
     self.assertEqual(len(resp.data), 0)
     new_count = self.get_product_count()
     self.assertEqual(new_count, product_count - 1)
Пример #21
0
 def test_get_product_list_by_date(self):
     """ Get a list of Products by date order"""
     products = Product.sort_by_date()
     results = [ product.serialize() for product in products]
     resp = self.app.get('/products/latest')
     self.assertEqual(resp.status_code, status.HTTP_200_OK)
     data = json.loads(resp.data)
     # print(data)
     # print(products)
     # print(results)
     self.assertEqual(data, results)
Пример #22
0
def list_products_by_id(item_id):
    app.logger.info('Finding a Product with id [{}]'.format(item_id))
    product = Product.find_by_id(item_id)
    if product:
        message = product.serialize()
        return_code = status.HTTP_200_OK
    else:
        message = {'error': 'Product with id: %s was not found' % str(item_id)}
        raise NotFound(message)
        # return_code = status.HTTP_404_NOT_FOUND

    return jsonify(message), return_code
Пример #23
0
 def test_serialize_a_product(self):
     """ Test serialization of a Product """
     product = Product(1, "Couch", "White couch", "Furniture", 200, "Boxed",
                       50, " ", 8)
     data = product.serialize()
     self.assertNotEqual(data, None)
     self.assertIn('id', data)
     self.assertEqual(data['id'], 1)
     self.assertIn('name', data)
     self.assertEqual(data['name'], "Couch")
     self.assertIn('category', data)
     self.assertEqual(data['category'], "Furniture")
     self.assertIn('description', data)
     self.assertEqual(data['description'], "White couch")
     self.assertIn('price', data)
     self.assertEqual(data['price'], 200)
     self.assertIn('condition', data)
     self.assertEqual(data['condition'], "Boxed")
     self.assertIn('inventory', data)
     self.assertEqual(data['inventory'], 50)
     self.assertIn('rating', data)
     self.assertEqual(data['rating'], 8)
Пример #24
0
def add_product():
    name = request.json['product']
    product_category = request.json['category']

    if product_exists_name(name):
        return jsonify({'error': 'this product already exists in database'})
    elif not category_exists_id(product_category):
        return jsonify({'error': 'there is no such category'})
    else:
        product = Product(name, product_category)
        db.session.add(product)
        db.session.commit()
        return jsonify({'response': {'added': product.serialized}})
Пример #25
0
def gen_sample_data():
    for i in range(10):
        user = User(username=f'user{i}', password='******')

        for j in range(10):
            name = ''.join(
                random.choices(string.ascii_uppercase + string.digits, k=10))
            Product(name=name, designer=user)

        db.session.add(user)
        db.session.commit()
        echo(f'{user} added.', fg='blue')
    echo('sample data generated.', fg='green')
Пример #26
0
 def test_create_a_product(self):
     """ Create a product and assert that it exists """
     product = Product(1, "Couch", "White couch", "Furniture", 200, "Boxed",
                       50, " ", 8)
     self.assertTrue(product is not None)
     self.assertEqual(product.id, 1)
     self.assertEqual(product.name, "Couch")
     self.assertEqual(product.category, "Furniture")
     self.assertEqual(product.description, "White couch")
     self.assertEqual(product.price, 200)
     self.assertEqual(product.condition, "Boxed")
     self.assertEqual(product.inventory, 50)
     self.assertEqual(product.rating, 8)
Пример #27
0
 def test_update_a_product_rating(self):
     """ Update a Product Rating"""
     product = Product(1, "Couch", "White couch", "Furniture", 200, "Boxed",
                       50, " ", 8)
     product.save()
     self.assertEqual(product.id, 1)
     # Change it and save it
     product.rating = 10
     product.update()
     self.assertEqual(product.id, 1)
     # Fetch it back and make sure the id hasn't changed
     # but the data did change
     products = Product.all()
     self.assertEqual(len(products), 1)
     self.assertEqual(products[0].rating, 10)
Пример #28
0
 def test_sort_by_date(self):
     """ Sort Products by Date """
     Product(1, "Couch", "White couch", "Furniture", 200, "Boxed", 50, " ",
             8).save()
     table = Product(2, "Table", "Oak table", "Home", 150, "Boxed", 100,
                     " ", 7)
     table.save()
     table.price = 200
     table.update()
     product = list(Product.sort_by_date())[0]
     self.assertIsNot(product, None)
     self.assertEqual(product.id, table.id)
     self.assertEqual(product.name, "Table")
     self.assertEqual(product.category, "Home")
     self.assertEqual(product.description, "Oak table")
     self.assertEqual(product.price, 200)
     self.assertEqual(product.condition, "Boxed")
     self.assertEqual(product.inventory, 100)
     self.assertEqual(product.rating, 7)
Пример #29
0
def create(name: str, price: int) -> Product:
    """Create product

    Args:
        name: name of product
        price: price of product

    Returns:
        Product object
    """
    p = Product(name, price)
    db.session.add(p)
    db.session.commit()
    return p
Пример #30
0
 def test_deserialize_bad_data_missing_arg(self):
     """ Test deserialization of missing arg """
     data = {
         "id": 1,
         "name": "Couch",
         "category": "Furniture",
         "price": 200,
         "condition": "Boxed",
         "inventory": 50,
         "rating": 8,
         "review": " "
     }
     product = Product(1, "", "", "", 0, "", 0, "", 0)
     self.assertRaises(ValidationError, product.deserialize, data)