Beispiel #1
0
    def test_crud(self):
        with self.app_context():
            StoreModel('test').save_to_db()
            item = ItemModel('test', 19.99, 1)

            # verifica se o item não existe no banco de dados
            # o terceiro argumento é uma mensagem de erro personalizada, que pode ajudar muito no decorrer das execuções de testes
            self.assertIsNone(
                ItemModel.find_by_name('test'),
                f'Found an item with name {item.name!r} on database, but expected not to.'
            )

            item.save_to_db()
            # verifica se o item existe no banco de dados
            self.assertIsNotNone(
                ItemModel.find_by_name('test'),
                f'Not found an item with name {item.name!r} on database, but expected to.'
            )

            item.delete_from_db()
            # verifica se o item não existe no banco de dados
            self.assertIsNone(
                ItemModel.find_by_name('test'),
                f'Found an item with name {item.name!r} on database, but expected not to.'
            )
Beispiel #2
0
def create_item(data, user_id):
    """Create a new item, save to database and response it."""

    # check if item's title has already existed
    if ItemModel.query.filter_by(name=data['name'], category_id=data['category_id']).first():
        raise BadRequest(f"This category has already had item {data['name']}.")

    # save item to database and response
    item = ItemModel(**data, user_id=user_id)
    item.save_to_db()
    return jsonify(ItemSchema().dump(item)), 201
Beispiel #3
0
    def test_item_list(self):
        with self.app() as client:
            with self.app_context():
                ItemModel('test1', 15.99, 1).save_to_db()
                ItemModel('test2', 10.99, 1).save_to_db()
                ItemModel('test3', 17.99, 1).save_to_db()

                expected = { 'items': [ {'name': 'test1', 'price': 15.99},
                                        {'name': 'test2', 'price': 10.99}, 
                                        {'name': 'test3', 'price': 17.99} ] }

                resp = client.get('/items', headers = self.header)

                self.assertDictEqual(json.loads(resp.data), expected)
Beispiel #4
0
    def test_item_json(self):

        with self.app_context():
            store = StoreModel('test store')
            item = ItemModel('test item', 19.99, 1)

            store.save_to_db()
            item.save_to_db()

            item_json = item.json()

            expected = {'name': 'test item', 'price': 19.99}

            self.assertDictEqual(expected, item_json)
Beispiel #5
0
    def delete(self, name):

        item = ItemModel.find_by_name(name)
        if item:
            item.delete_from_db()

            return {'message': 'item has been deleted'}
Beispiel #6
0
 def get(self, name):
     try:
         item = ItemModel.find_item_by_name(name)
         if item:
             return item.json()
         return {"message": "Item not found"}, 404
     except:
         return {"Message": "An error occured while getting the item"}
Beispiel #7
0
def insert_test_data():
    for data in user_data:
        UserModel(**data).save()

    for data in category_data:
        CategoryModel(**data).save()

    for data in item_data:
        ItemModel(**data).save()
Beispiel #8
0
def new_item(category_id):
    item_data = request.json
    if item_data:
        item_data['category_id'] = category_id
        item_data['user_id'] = current_identity.id
    category = CategoryModel.query.get_or_404(category_id)
    schema = ItemSchema()
    schema.load(item_data)
    item = ItemModel(item_data['name'], item_data['description'],
                     item_data['price'], category_id, current_identity.id)
    item.save_to_db()
    return jsonify({
        'id': item.id,
        'name': item.name,
        'description': item.description,
        'price': item.price,
        'category_id': item.category_id,
        'user_id': item.user_id
    }), 201
Beispiel #9
0
    def put(self, name):
        data = Item.parser.parse_args()

        item = ItemModel.find_by_name(name)

        if item is None:
            item = ItemModel(name, **data)
        else:
            item.price = data['price']
            item.store_id = data['store_id']

        item.save_to_db()
        return item.json()
Beispiel #10
0
    def test_find_by_name(self):
        app = create_app()
        app.testing = True

        expected = self.item

        with app.app_context():
            self.item.save_to_db()
            resp = ItemModel.find_by_name('Caneta')

            self.assertEqual(resp.name, expected.name)
            self.assertEqual(resp.price, expected.price)
Beispiel #11
0
    def put(self, name):
        # Create or Update
        data = Item.parser.parse_args()
        item = ItemModel.find_by_name(name)

        if item is None:
            item = ItemModel(name, data['price'])
        else:
            item.price = data['price']

        item.save_to_db()

        return item.json()
Beispiel #12
0
    def post(self):
        data = Item.parser.parse_args()

        if ItemModel.find_item_by_name(data["name"]):
            return {"message": "Error: Item already exists"}, 409

        item = ItemModel(**data)
        item.save()

        return item.json(), 201
Beispiel #13
0
    def put(self, name):

        data = Item.parser.parse_args()

        try:
            item = ItemModel.find_item_by_name(name)
            if not item:
                item = ItemModel(**data)
            else:
                item.price = data["price"]
            item.save()

            return item.json()
        except:
            return {"message": "There was an error updating the item"}, 500
Beispiel #14
0
def init_db():
    user1 = UserModel('Test User1', 'testuser1', 'testpassword123',
                      '*****@*****.**')
    user2 = UserModel('Test User2', 'testuser2', 'testpassword123',
                      '*****@*****.**')
    category1 = CategoryModel('Category 1', 'Test category number 1')
    category2 = CategoryModel('Category 2', 'Test category number 2')
    item1 = ItemModel('Item 1', 'Test item number 1', 10, 1, 1)
    item2 = ItemModel('Item 2', 'Test item number 2', 20, 1, 1)
    user1.save_to_db()
    user2.save_to_db()
    category1.save_to_db()
    category2.save_to_db()
    item1.save_to_db()
    item2.save_to_db()

    yield db

    db.session.close()
    db.drop_all()
Beispiel #15
0
    def post(self, name):
        self.logger.info(f'parsed args: {Item.parser.parse_args()}')

        if ItemModel.find_by_name(name):
            return {'message': "An item with name '{}' already exists.".format(
                name)}, 400
        data = Item.parser.parse_args()
        item = ItemModel(name, data['price'], data['store_id'])

        try:
            item.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500
        return item.json(), 201
Beispiel #16
0
class ItemTest(TestCase):
    def setUp(self):
        self.item = ItemModel('Caneta', 1.5)

    def test_create_item(self):
        self.assertEqual(self.item.name, 'Caneta')
        self.assertEqual(self.item.price, 1.5)

    def test_save_item(self):
        with patch('app.models.item.db.session.add') as mocked_db_add:
            with patch(
                    'app.models.item.db.session.commit') as mocked_db_commit:
                self.item.save_to_db()

                mocked_db_add.assert_called()
                mocked_db_commit.assert_called()

    def test_delete_item(self):
        with patch('app.models.item.db.session.delete') as mocked_db_delete:
            with patch(
                    'app.models.item.db.session.commit') as mocked_db_commit:
                self.item.delete_from_db()

                mocked_db_delete.assert_called()
                mocked_db_commit.assert_called()

    def test_find_by_name(self):
        app = create_app()
        app.testing = True

        expected = self.item

        with app.app_context():
            self.item.save_to_db()
            resp = ItemModel.find_by_name('Caneta')

            self.assertEqual(resp.name, expected.name)
            self.assertEqual(resp.price, expected.price)

    def test_json(self):
        item_json = self.item.json()
        expected = {'name': 'Caneta', 'price': 1.5}

        self.assertDictEqual(item_json, expected)
Beispiel #17
0
    def post(self, name):
        if ItemModel.find_by_name(name):
            return {
                'message':
                "An item with name '{}' already exists.".format(name)
            }, 400

        data = Item.parser.parse_args()

        item = ItemModel(name, **data)

        try:
            item.save_to_db()
        except:
            return {"message": "An error occurred inserting the item."}, 500

        return item.json(), 201
Beispiel #18
0
    def test_store_list_with_items(self):
        with self.app() as client:
            with self.app_context():
                client.post('/store/test')

                resp = client.get('/stores')

                store_test_info = json.loads(resp.data)['stores'][0]
                items_store_test_info = store_test_info['items']

                self.assertIsNotNone(store_test_info)
                self.assertListEqual(items_store_test_info, [])

                ItemModel('item1', 19.99, 1).save_to_db()

                resp1 = client.get('/stores')
                store_test_info = json.loads(resp1.data)['stores'][0]
                items_store_test_info = store_test_info['items']

                self.assertListEqual(items_store_test_info, [{
                    'name': 'item1',
                    'price': 19.99
                }])
Beispiel #19
0
 def setUp(self):
     self.item = ItemModel('Caneta', 1.5)
Beispiel #20
0
 def delete(self, name):
     item = ItemModel.find_item_by_name(name)
     if item:
         item.delete()
         return {"message": "Item deleted successfully"}
     return {"message": "The item was not found"}, 404
Beispiel #21
0
def init_items():
    """Create 4 sample items, 2 for each sample user and category."""
    ItemModel('ball', 'A ball', 1, 1).save_to_db()
    ItemModel('grass', 'Some grass', 1, 1).save_to_db()
    ItemModel('racket', 'A racket', 2, 2).save_to_db()
    ItemModel('net', "A ", 2, 2).save_to_db()
Beispiel #22
0
def create_item(category, data, user):
    new_item = ItemModel(**data, category_id=category.id, user_id=user.id)
    new_item.save()
    return jsonify(GetItemSchema().dump(new_item)), 201
Beispiel #23
0
 def get(self, name):
     item = ItemModel.find_by_name(name)
     self.logger.info(f'returning item: {item.json()}')
     if item:
         return item.json()
     return {'message': 'Item not found'}, 404
Beispiel #24
0
 def get(self, name):
     item = ItemModel.find_by_name(name)
     if item:
         return item.json()
     return {'message': 'Item not found'}, 404