def test_store_relationship(self): store = StoreModel('Test Store') item = ItemModel('Test', 19.99, 1) store.save_to_db() item.save_to_db() self.assertEqual(item.store.name, 'Test Store')
def test_item_relationship(self): store = StoreModel('Test Store') item = ItemModel('Test', 19.99, 1) store.save_to_db() item.save_to_db() self.assertEqual(store.items.count(), 1) self.assertEqual(store.items.first().name, item.name)
def on_put(self, req, resp, name): """Insert/Update an item called name into items list""" if ItemModel.validate_name(name): msg = "Invalid Request" raise falcon.HTTPBadRequest("Bad Request", msg) else: data = req.context.get("json") item = ItemModel.find_by_name(name) if item is None: try: item = ItemModel(name, data.get("price"), data.get("store_id")) except Exception as e: msg = "An error occured inserting the item" raise falcon.HTTPInternalServerError("Internal Server Error", msg) else: resp.body = json.dumps({"item": item.json()}, ensure_ascii=False) resp.status = falcon.HTTP_201 else: try: item.price = data.get("price") except Exception as e: msg = "An error occured inserting the item" raise falcon.HTTPInternalServerError("Internal Server Error", msg) else: resp.body = json.dumps({"item": item.json()}, ensure_ascii=False) resp.status = falcon.HTTP_200 item.save_to_db()
def test_store_json_with_item(self): store = StoreModel('Test Store') item = ItemModel('Test', 19.99, 1) store.save_to_db() item.save_to_db() expected = { 'name': 'Test Store', 'items': [{ 'name': 'Test', 'price': 19.99 }] } self.assertEqual(store.json(), expected)
def test_store_found_with_items(self): item = ItemModel('Test Item', 19.99,1 ) store = StoreModel('Test') store.save_to_db() item.save_to_db() response = self.client.get('store/Test') self.assertEqual(response.status_code, 200) expected = { 'name': 'Test', 'items': [ {'name': 'Test Item', 'price': 19.99} ] } self.assertDictEqual(json.loads(response.data), expected)
def on_delete(self, req, resp, name): """Delete item called name from items list""" item = ItemModel.find_by_name(name) if item: item.delete_from_db() resp.body = json.dumps({"message": f"Item {name} deleted"}, ensure_ascii=False) resp.status = falcon.HTTP_201
def test_get_item_with_auth(self): headers = {'Authorization': self.token} ItemModel('test', 19.99, 1).save_to_db() response = self.client.get('/item/test', headers=headers) self.assertEqual(response.status_code, 200) expected = {'name': 'test', 'price': 19.99} self.assertDictEqual(json.loads(response.data), expected)
def test_store_list_with_items(self): store = StoreModel('Test') store.save_to_db() ItemModel('Test Item', 19.99, 1).save_to_db() response = self.client.get('/stores') self.assertEqual(response.status_code, 200) self.assertDictEqual(json.loads(response.data), {'stores': [store.json()]})
def test_get_item_no_auth(self): ItemModel('test', 19.99, 1).save_to_db() response = self.client.get('/item/test') self.assertEqual(response.status_code, 401) expected = { 'message': 'Could not authorize. Did you include a valid Authorization header?' } self.assertDictEqual(json.loads(response.data), expected)
def get(self): user_id = get_jwt_identity() itens = [item.json for item in ItemModel.list_itens()] if user_id: return {'itens': itens}, return { 'item': [item['name'] for item in itens], 'message': 'Há mais dados se você logar.' }, 200
def delete(self, name): claims = get_jwt_claims() if not claims['is_admin']: return {'message': 'Você nao possui acesso.'}, 401 item = ItemModel.find_by_name(name) if item: item.delete() return {'message': 'Item deletado'}, 400
def on_get(self, req, resp, name): """Fetch item called name from items list""" item = ItemModel.find_by_name(name) if item: resp.body = json.dumps(item.json(), ensure_ascii=False) resp.status = falcon.HTTP_200 else: resp.body = json.dumps({"message": "Item not found"}, ensure_ascii=False) resp.status = falcon.HTTP_404 # Not Found
def on_post(self, req, resp, name): """Insert item called name into items list""" if ItemModel.validate_name(name): msg = "Invalid Request" raise falcon.HTTPBadRequest("Bad Request", msg) elif ItemModel.find_by_name(name): message = f"An item with name {name} already exists." resp.body = json.dumps({"message": message}, ensure_ascii=False) resp.status = falcon.HTTP_400 # Bad Request else: # data = json.load(req.bounded_stream) #Return type - dict # data = req.bounded_stream.read() #Return type - bytes # data = json.loads(req.bounded_stream.read()) #Return type - dict # data = req.bounded_stream.read().decode("utf-8") #Return type - str # data = json.loads(req.bounded_stream.read().decode("utf-8")) #Return type - dict data = req.context.get("json") item = ItemModel(name, data.get("price"), data.get("store_id")) try: item.save_to_db() except Exception as e: msg = "An error occured inserting the item" raise falcon.HTTPInternalServerError("Internal Server Error", msg) else: resp.body = json.dumps( {"message": "Item added successfully"}, ensure_ascii=False ) resp.status = falcon.HTTP_201
def put(self, name): data = Item.parser.parse_args() item = ItemModel.find_by_name(name) if item is None: item = ItemModel(name, data['price'], data['store_id']) else: item.price = data['price'] item.save_to_db() return item.json()
def test_put_item_update(self): ItemModel('test', 19.99, 1).save_to_db() response = self.client.put( '/item/test', data=json.dumps({ 'price': 20.00, 'store_id': 1 }), headers={'Content-Type': 'application/json'}) self.assertEqual(response.status_code, 200) self.assertDictEqual(json.loads(response.data), { 'name': 'test', 'price': 20.00 })
def test_crud(self): StoreModel('Test Store').save_to_db() item = ItemModel('Test', 19.99, 1) self.assertIsNone( ItemModel.find_by_name('Test'), "Found an item with name '{}', but expected not to.".format( item.name)) item.save_to_db() self.assertIsNotNone( ItemModel.find_by_name('Test'), "Did not find an item with name '{}', but expected to.".format( item.name)) item.delete_from_db() self.assertIsNone( ItemModel.find_by_name('Test'), "Found an item with name '{}', but expected not to.".format( item.name))
def post(self, name): if ItemModel.find_by_name(name): return { 'message': 'Um item {} já esta cadastrado.'.format(name) }, 400 data = Item.parser.parse_args() item = ItemModel(name, data['price'], data['store_id']) try: item.save_to_db() except: return {'message': 'Ocorreu um erro ao inserir o item.'}, 500 return item.json(), 201
def get(self, name): item = ItemModel.find_by_name(name) if item: return item.json() return {'message': 'item não foi encontrado.'}, 404
def test_delete_item(self): ItemModel('test', 19.99, 1).save_to_db() response = self.client.delete('/item/test') self.assertEqual(response.status_code, 200) self.assertDictEqual(json.loads(response.data), {'message': 'Item deleted'})