class ItemTest(BaseTest): def setUp(self): super(ItemTest, self).setUp() self.item = ItemModel( url= 'https://www.johnlewis.com/john-lewis-partners-amber-clear-swirl-bauble-orange/p3527237', price=19.99, name='test', store_id=1) def test_load_item_data_raises_exception(self): mocked_response = MagicMock() mocked_response.status_code = 500 mocked_response.content = 'Some extra data not important' with patch('pricealerts.models.requests.get', return_value=mocked_response) as mocked_requests: with self.assertRaises(ItemNotLoadedError): self.item.load_item_data() mocked_requests.assert_called_with( url= 'https://www.johnlewis.com/john-lewis-partners-amber-clear-swirl-bauble-orange/p3527237' ) def test_load_item_data_correctly(self): with self.app_context(): self.assertTupleEqual(( 'John Lewis & Partners Amber Clear Swirl Bauble, Orange at John Lewis & Partners', 6.00, None), self.item.load_item_data())
def setUp(self): super(ItemTest, self).setUp() self.item = ItemModel( url= 'https://www.johnlewis.com/john-lewis-partners-amber-clear-swirl-bauble-orange/p3527237', price=19.99, name='test', store_id=1)
def setUp(self): super(AlertTest, self).setUp() self.store = StoreModel(name='store1', url_prefix='http://johnlewis.com', tag_name='span', query_string={'id': 'priceblock_ourprice'}) self.user = UserModel('Alex', '*****@*****.**', '12345', is_admin=True) self.item = ItemModel( url='https://www.johnlewis.com/john-lewis-partners-amber-clear-swirl-bauble-orange/p3527237', price=19.99, name='Item1', store_id=1) self.last_checked = datetime.datetime.utcnow() - datetime.timedelta(minutes=15) self.alert = AlertModel(price_limit=20, item_id=1, user_id=1, active=True, shared=False, contact_phone=None, contact_email='*****@*****.**', last_checked=self.last_checked, check_every=10)
class ItemTest(UnitBaseTest): def setUp(self): self.item = ItemModel(url='http://johnlewis.com', price=19.99, name='test', store_id=1) def test_create_item(self): self.assertEqual('test', self.item.name) self.assertEqual(19.99, self.item.price) self.assertEqual(1, self.item.store_id) self.assertIsNone(self.item.store) self.assertEqual('http://johnlewis.com', self.item.url) def test_item_json(self): expected = { 'name': 'test', 'price': 19.99, 'store_id': 1, 'url': 'http://johnlewis.com' } self.assertDictEqual(expected, self.item.json()) def test_item_representation(self): self.assertEqual("Item(id='None', name='test')", str(self.item))
def delete(self, name): """This endpoint is used to delete an item from the store. Requires a fresh jwt token to execute the request --- tags: - Items parameters: - in: path name: name required: true description: The name of the item, try item1! type: string responses: 200: description: Item deleted 401: description: Authorization required 403: description: Admin privilege required """ # Checking claims for actually execute or not the request as expected claims = get_jwt_claims() if not claims['is_admin']: return {'message': 'Admin privilege required'}, 403 item = ItemModel.find_by_name(name) if item: item.delete_from_db() return {'message': 'Item deleted'}
def test_get_item_from_store_not_found(self): with self.app_context(): self.store.save_to_db() ItemModel(name='Item1', url='http://johnlewis.com/item/1', store_id=self.store.id).save_to_db() # Get an item with id = 2, raises ItemNotFoundError self.assertRaises( ItemNotFoundError, self.store.get_item, 2)
def put(self, name): """Endpoint to create/update an item for the store This is an example --- tags: - Items parameters: - in: body name: body schema: properties: store_id: type: integer required: true price: type: number format: double required: true url: type: string format: url required: false - in: path name: name required: true description: The name of the item! type: string responses: 201: description: The item has been created schema: $ref: '#/definitions/Item' 200: description: Item updated schema: $ref: '#/definitions/Item' """ data = ItemResource.parser.parse_args() item = ItemModel.find_by_name(name) if item is None: item = ItemModel(name, **data) flag_create = True else: item.price = data['price'] flag_create = False try: item.save_to_db() except: return {"message": "An error occurred inserting the item."}, 500 return item.json(), 201 if flag_create else item.json()
def test_delete_item_not_found_from_store(self): with self.app_context(): self.store.save_to_db() item = ItemModel(name='Item1', url='http://johnlewis.com/item/1', store_id=self.store.id).save_to_db() # This item has id = 1 self.assertEqual(1, item.id) # Deleting an item with id = 2, raises ItemNotFoundError self.assertRaises( ItemNotFoundError, self.store.delete_item, 2)
def test_delete_item_from_store(self): with self.app_context(): self.store.save_to_db() # This item has id = 1, after is saved item = ItemModel(name='Item1', url='http://johnlewis.com/item/1', store_id=self.store.id).save_to_db() self.assertEqual(1, item.id) self.assertEqual(1, self.store.items.count()) self.store.delete_item(1) self.assertEqual(0, self.store.items.count())
def get(self): """ Returns the list of items in the store --- tags: - Items definitions: Item: type: object properties: id: type: integer description: Identifier of the Item name: type: string description: Name of the item store_id: type: integer description: Identifier of the store to which this item belongs responses: 200: description: The list of items in the store schema: type: object properties: items: type: array items: $ref: '#/definitions/Item' examples: { 'items' : [{'id': 1, 'name': 'New Item', 'store_id': 2},]} """ # Access the identity of the current user identity (username) with get_jwt_identity current_user = get_jwt_identity() # same as: {'items': list(map(lambda x: x.json(), ItemModel.query.all()))} items = [item.json() for item in ItemModel.find_all()] if current_user: return {'items': items} return { 'items': list(map(lambda x: x['name'], items)), 'message': 'More data available if logged in' }
def test_store_json_with_items(self): """ Tests if json method returns a dic() instance with items list added on it :return: None """ with self.app_context(): self.store.save_to_db() ItemModel(name='Item1', url='http://johnlewis.com/item/1', store_id=self.store.id).save_to_db() expected = { 'id': self.store.id, 'name': 'store1', 'items': [{ "name": "Item1", "price": 0.0, "store_id": self.store.id, 'url': 'http://johnlewis.com/item/1' }] } self.assertDictEqual(expected, self.store.json())
def test_get_item_from_store(self): with self.app_context(): self.store.save_to_db() ItemModel(name='Item1', url='http://johnlewis.com/item/1', store_id=self.store.id).save_to_db() self.assertEqual('Item1', self.store.get_item(1).name)
class AlertTest(BaseTest): def setUp(self): super(AlertTest, self).setUp() self.store = StoreModel(name='store1', url_prefix='http://johnlewis.com', tag_name='span', query_string={'id': 'priceblock_ourprice'}) self.user = UserModel('Alex', '*****@*****.**', '12345', is_admin=True) self.item = ItemModel( url='https://www.johnlewis.com/john-lewis-partners-amber-clear-swirl-bauble-orange/p3527237', price=19.99, name='Item1', store_id=1) self.last_checked = datetime.datetime.utcnow() - datetime.timedelta(minutes=15) self.alert = AlertModel(price_limit=20, item_id=1, user_id=1, active=True, shared=False, contact_phone=None, contact_email='*****@*****.**', last_checked=self.last_checked, check_every=10) def test_alert_representation(self): with self.app_context(): self.user.save_to_db() self.store.save_to_db() self.item.save_to_db() self.alert.save_to_db() self.assertEqual("(AlertModel<id=1, user='******', item='Item1'>)", str(self.alert)) def test_json(self): expected = { 'id': 1, 'price_limit': 20.0, 'last_checked': self.last_checked, 'check_every': 10.0, 'item_id': 1, 'item': 'Item1', 'user_id': 1, 'user': '******', 'active': True, 'shared': False, 'contact_phone': None, 'contact_email': '*****@*****.**' } with self.app_context(): self.user.save_to_db() self.store.save_to_db() self.item.save_to_db() self.alert.save_to_db() self.assertDictEqual(expected, self.alert.json()) def test_find_needing_update_with_one_alert(self): with self.app_context(): self.user.save_to_db() self.store.save_to_db() self.item.save_to_db() self.alert.save_to_db() print(self.last_checked) self.assertEqual(1, len(AlertModel.find_needing_update())) def test_find_needing_update_without_alerts(self): with self.app_context(): self.user.save_to_db() self.store.save_to_db() self.item.save_to_db() self.alert.last_checked = self.alert.last_checked + datetime.timedelta(minutes=8) self.alert.save_to_db() self.assertEqual(0, len(AlertModel.find_needing_update())) def test_load_price_change(self): with self.app_context(): with patch('pricealerts.models.ItemModel.load_item_data', return_value = ('Item1',6.00, None)) as mocked_load_item_data: self.user.save_to_db() self.store.save_to_db() self.item.save_to_db() self.alert.save_to_db() self.assertEqual('Item1', self.alert.item.name) self.assertEqual(19.99, self.alert.item.price) self.assertEqual(None, self.alert.item.image) self.alert.load_price_change() mocked_load_item_data.assert_called_once() self.assertEqual('Item1', self.alert.item.name) self.assertEqual(6.0, self.alert.item.price) self.assertEqual(None, self.alert.item.image) self.assertAlmostEqual(self.alert.last_checked,datetime.datetime.utcnow(), delta=datetime.timedelta(seconds=10))
def setUp(self): self.item = ItemModel(url='http://johnlewis.com', price=19.99, name='test', store_id=1)
def post(self, name): """Creates a new Item This is an example --- tags: - Items parameters: - in: body name: body schema: properties: store_id: type: integer required: true price: type: number format: double required: true url: type: string format: url required: false - in: path name: name required: true description: The name of the item! type: string responses: 201: description: Item created schema: $ref: '#/definitions/Item' 401: description: Authorization required """ if ItemModel.find_by_name(name): return { 'message': "An item with name '{}' already exists.".format(name) }, 400 data = ItemResource.parser.parse_args() item = ItemModel(name, **data) try: item.save_to_db() except Exception as ex: return {"message": str(ex)}, 500 current_user = get_jwt_identity() try: notifications.NotificationDispatcher.send_sms( from_name=current_user, to_phone='+12106105564', to_name='Alex', text='New Item with name {} and price {} was added.'.format( item.name, item.price)) except TwilioRestException as ex: return {'message': ex.msg}, 500 return item.json(), 201
def get(self, name): item = ItemModel.find_by_name(name) if item: return item.json() return {'message': 'Item not found'}, 404