def register_business(): """ Register business """ sent_data = request.get_json(force=True) valid = validate(sent_data, REGISTER_BUSINESS_RULES) if valid != True: response = jsonify( status='error', message="Please provide required info", errors=valid) response.status_code = 400 return response user_id = token_id(request.headers.get('Authorization')) data = { 'id': uuid.uuid4().hex, 'user_id': user_id, 'name': sent_data['name'], 'description': sent_data['description'], 'country': sent_data['country'], 'city': sent_data['city'], } if Business.has_same_business(user_id, sent_data['name']): response = jsonify( status='error', message="You have already registered this business") response.status_code = 400 return response Business.save(data) response = jsonify({ 'status': 'ok', 'message': "Your business has been successfully registered" }) response.status_code = 201 return response
def get_business_reviews(business_id): ''' Business reviews ''' business = Business.get(business_id) if business is not None: reviews = Review.query.order_by(desc(Review.created_at)).filter_by( business_id=Business.get(business_id).id).all() if len(reviews) is not 0: response = jsonify({ 'status': 'ok', 'message': str(len(reviews)) + " reviews found", 'business': Business.serialize_obj(business), 'reviews': Review.serializer(reviews) }) response.status_code = 200 return response response = jsonify({ 'status': 'ok', 'message': "No business review yet", 'business': Business.serialize_obj(business), 'reviews': [] }) response.status_code = 200 return response response = jsonify({ 'status': 'error', 'message': "This business doesn't exist" }) response.status_code = 404 return response
def test_updating_business_with_same_name(self): ''' Test business updating with existing busiiness name under one user ''' # New business details to test updating new_business_data = { 'name': 'TRM', 'description': 'Enjoy Coffee and Pizzas', 'country': 'Kenya', 'city': 'Nakuru' } # Data to be saved to test same name businesses under one person additional_business_data = { 'id': uuid.uuid4().hex, 'user_id': self.sample_user['id'], 'name': 'TRM', 'description': 'Enjoy Coffee and Pizzas', 'country': 'Kenya', 'city': 'Nakuru' } # Add user(owner) to the business data dict self.business_data['user_id'] = self.sample_user['id'] # Save business in the storage list for testing Business.save(self.business_data) Business.save(additional_business_data) response = self.app.put(self.url_prefix + 'businesses/' + self.business_data['id'], data=json.dumps(new_business_data), headers={'Authorization': self.test_token}, content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn( b'You have already registered this other business with same name', response.data)
def test_no_priv_business_deletion(self): ''' Test removing business without privileges to it ''' # Add user(owner) to the business data dict self.business_data['user_id'] = self.sample_user['id'] # Save business in the storage list for testing Business.save(self.business_data) response = self.app.delete( self.url_prefix + 'businesses/' + self.business_data['id'], data={}, headers={'Authorization': self.orphan_test_token}) self.assertEqual(response.status_code, 400)
def test_business_deletion(self): ''' Test removing business ''' # Add user(owner) to the business data dict self.business_data['user_id'] = self.sample_user['id'] # Save business in the storage list for testing Business.save(self.business_data) response = self.app.delete(self.url_prefix + 'businesses/' + self.business_data['id'], data={}, headers={'Authorization': self.test_token}) self.assertEqual(response.status_code, 202) self.assertIn(b'Your business has been successfully deleted', response.data)
def get_business(business_id): ''' Get business ''' business = Business.get(business_id) if business is not None: response = jsonify({ 'status': 'ok', 'message': 'Business found', 'business': Business.serialize_obj(business), }) response.status_code = 200 return response response = jsonify({'status': 'error', 'message': "Business not found"}) response.status_code = 400 return response
def test_exist_name_business(self): ''' Test business updating with existing busiiness name under one user ''' self.add_business() # Data to be saved to test same name businesses under one person new_business_data = { 'user_id': self.sample_user['id'], 'name': 'TRM', 'description': 'Enjoy Coffee and Pizzas', 'category': 'Mall', 'country': 'Kenya', 'city': 'Nakuru' } business = Business( user_id=self.sample_user['id'], name='TRM', description=self.business_data['description'], category=self.business_data['category'], country=self.business_data['country'], city=self.business_data['city'], ) db.session.add(business) db.session.commit() response = self.app.put(self.url_prefix + 'businesses/' + self.business_data['hashid'], data=json.dumps(new_business_data), headers={'Authorization': self.test_token}, content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn(b'You have already registered a business with same name', response.data)
def add_business_review(business_id): ''' Add Review ''' user_id = token_id(request.headers.get('Authorization')) business = Business.get(business_id) if business is not None: sent_data = request.get_json(force=True) valid = validate(sent_data, REVIEW_RULES) if valid is not True: response = jsonify(status='error', message='Please provide valid details', errors=valid) response.status_code = 400 return response review = Review.save({ 'user_id': user_id, 'description': sent_data['review'], 'business_id': business.id }) response = jsonify({ 'status': 'ok', 'message': 'Your review has been sent', 'review': review.serialize_one, }) response.status_code = 201 return response response = jsonify({ 'status': 'error', 'message': 'This business doesn\'t exist' }) response.status_code = 400 return response
def get_business_reviews(business_id): """ Business reviews """ if business_id in [business['id'] for business in Store.businesses]: if business_id in Store.reviews: reviews = Store.reviews[business_id] business = Business.get_business( business_id) # Get business details response = jsonify({ 'status': 'ok', 'message': str(len(reviews)) + " reviews found", 'business': business, 'reviews': reviews }) response.status_code = 200 return response response = jsonify({ 'status': 'ok', 'message': "No business review yet" }) response.status_code = 204 return response response = jsonify({ 'status': 'error', 'message': "This business doesn't exist" }) response.status_code = 400 return response
def add_business(self): ''' Add sample business in database ''' business = Business( user_id=self.sample_user['id'], name=self.business_data['name'], description=self.business_data['description'], category=self.business_data['category'], country=self.business_data['country'], city=self.business_data['city'], ) db.session.add(business) db.session.commit() self.business_data['hashid'] = business.hashid() self.business_data['id'] = business.id
def delete_business(business_id): """ Delete business """ user_id = token_id(request.headers.get('Authorization')) if Business.has_this_business(user_id, business_id): Business.delete_business(business_id) response = jsonify({ 'status': 'ok', 'message': "Your business has been successfully deleted" }) response.status_code = 202 return response response = jsonify( status='error', message="This business doesn't exist or you don't have privileges to it") response.status_code = 400 return response
def get_user_businesses(): """ Business lists """ user_id = token_id(request.headers.get('Authorization')) if Business.has_business(user_id): businesses = Business.user_businesses(user_id) response = jsonify({ 'status': 'ok', 'message': 'You have businesses ' + str(len(businesses)) + ' registered businesses', 'businesses': businesses }) response.status_code = 200 return response response = jsonify( status='error', message="You don't have registered business") response.status_code = 204 return response
def update_business(business_id): ''' Update business ''' sent_data = request.get_json(force=True) user_id = token_id(request.headers.get('Authorization')) business = Business.get_by_user(business_id, user_id) if business is not None: valid = validate(sent_data, REGISTER_BUSINESS_RULES) if valid is not True: response = jsonify(status='error', message="Please provide required info", errors=valid) response.status_code = 400 return response data = { 'name': sent_data['name'], 'description': sent_data['description'], 'category': sent_data['category'], 'country': sent_data['country'], 'city': sent_data['city'], } if Business.has_two_same_business(user_id, sent_data['name'], business_id): response = jsonify(status='error', message=("You have already registered" " a business with same name")) response.status_code = 400 return response Business.update(business_id, data) response = jsonify({ 'status': 'ok', 'message': "Your business has been successfully updated" }) response.status_code = 202 return response response = jsonify(status='error', message=("This business doesn't exist or you" " don't have privileges to it")) response.status_code = 400 return response
def test_businesses(self): ''' Test retrieving logged in user business ''' # New business details to test updating dummy_business_data = { 'id': uuid.uuid4().hex, 'user_id': self.sample_user['id'], 'name': 'KFC', 'description': 'Finger lickin\' good', 'country': 'Kenya', 'city': 'Nairobi' } # Add user(owner) to the business data dict self.business_data['user_id'] = self.sample_user['id'] # Save businesses to test Business.save(self.business_data) Business.save(dummy_business_data) response = self.app.get(self.url_prefix + 'businesses', headers={'Authorization': self.test_token}) self.assertEqual(response.status_code, 200)
def test_business_update_with_invalid_data(self): ''' Test business updating with invalid data ''' # New business details to test updating new_business_data = { 'name': 'Inzora Nakuru', 'country': 'Kenya', 'city': 'Nakuru' } # Add user(owner) to the business data dict self.business_data['user_id'] = self.sample_user['id'] # Save business in the storage list for testing Business.save(self.business_data) response = self.app.put(self.url_prefix + 'businesses/' + self.business_data['id'], data=json.dumps(new_business_data), headers={'Authorization': self.test_token}, content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn(b'Please provide required info', response.data)
def test_business_update(self): ''' Test business updating ''' # New business details to test updating new_business_data = { 'name': 'Inzora Nakuru', 'description': 'Enjoy Coffee and Pizzas', 'country': 'Kenya', 'city': 'Nakuru' } # Add user(owner) to the business data dict self.business_data['user_id'] = self.sample_user['id'] # Save business in the storage list for testing Business.save(self.business_data) response = self.app.put(self.url_prefix + 'businesses/' + self.business_data['id'], data=json.dumps(new_business_data), headers={'Authorization': self.test_token}) self.assertEqual(response.status_code, 202) self.assertIn(b'Your business has been successfully updated', response.data)
def register_business(): ''' Register business ''' sent_data = request.get_json(force=True) valid = validate(sent_data, REGISTER_BUSINESS_RULES) if valid is not True: response = jsonify(status='error', message="Please provide required info", errors=valid) response.status_code = 400 return response user_id = token_id(request.headers.get('Authorization')) if Business.query.order_by(desc(Business.created_at)).filter( Business.user_id == user_id, func.lower(Business.name) == func.lower( sent_data['name'])).first() is not None: response = jsonify(status='error', message=("You have already " "registered business with the same name")) response.status_code = 400 return response data = { 'user_id': user_id, 'name': sent_data['name'], 'description': sent_data['description'], 'category': sent_data['category'], 'country': sent_data['country'], 'city': sent_data['city'] } Business.save(data) response = jsonify({ 'status': 'ok', 'message': "Your business has been successfully registered" }) response.status_code = 201 return response
def test_same_business_registration(self): ''' Test business registration with the same name under same user ''' data = self.business_data data['user_id'] = self.sample_user['id'] Business().save( self.business_data) # Save business assigned to sample user response = self.app.post(self.url_prefix + 'businesses', data=json.dumps(self.business_data), headers={'Authorization': self.test_token}, content_type='application/json') self.assertEqual(response.status_code, 400) self.assertIn(b'You have already registered this business', response.data)
def get_business(business_id): """ Get business """ if business_id in [business['id'] for business in Store.businesses]: business = Business.get_business( business_id) # Get business details response = jsonify({ 'status': 'ok', 'message': 'Business found', 'business': business, }) response.status_code = 200 return response response = jsonify({ 'status': 'error', 'message': "Business not found" }) response.status_code = 400 return response
def delete_business(business_id): ''' Delete business ''' user_id = token_id(request.headers.get('Authorization')) business = Business.get_by_user(business_id, user_id) if business is not None: Review.delete_all(business.id) business.delete(business.id) response = jsonify({ 'status': 'ok', 'message': "Your business has been successfully deleted" }) response.status_code = 202 return response response = jsonify(status='error', message='''This business doesn't exist or you don't have privileges to it''') response.status_code = 400 return response
from faker import Faker from api.models.business import Business from api import create_app from api import db app = create_app('development') fake = Faker() with app.app_context(): businesses = [] for _ in range(100): business = Business( user_id=1, name=fake.company(), description=fake.text(max_nb_chars=300, ext_word_list=None), category=fake.job(), country=fake.country(), city=fake.city(), ) db.session.add(business) db.session.commit() businesses.append(business)
def get_all_businesses(): ''' Get all Businesses ''' name = request.args.get('name') category = request.args.get('category') city = request.args.get('city') country = request.args.get('country') searchAll = request.args.get('searchAll') page = request.args.get('page') per_page = request.args.get('limit') businesses = Business.query.order_by(desc(Business.created_at)).order_by( desc(Business.created_at)) # Filter by search query name_q = category_q = country_q = city_q = None if name or category or country or city: # Filter by if name is not None and name.strip() != '': name_q = func.lower(Business.name).like('%' + func.lower(name) + '%') # Filter by category if category is not None and category.strip() != '': category_q = func.lower( Business.category).like('%' + func.lower(category) + '%') # Filter by city if city is not None and city.strip() != '': city_q = func.lower(Business.city).like('%' + func.lower(city) + '%') # Filter by country if country is not None and country.strip() != '': country_q = func.lower( Business.country).like('%' + func.lower(country) + '%') businesses = businesses.filter( or_(name_q, country_q, city_q, category_q)) if searchAll is not None or searchAll == 'true': # Search by all if name is not None and name.strip() != '': businesses = businesses.filter( or_( func.lower(Business.name).like('%' + func.lower(name) + '%'), func.lower(Business.city).like('%' + func.lower(name) + '%'), func.lower(Business.category).like('%' + func.lower(name) + '%'), func.lower(Business.country).like('%' + func.lower(name) + '%'))) errors = [] # Errors list if (per_page is not None and per_page.isdigit() is False and per_page.strip() != ''): errors.append({'limit': 'Invalid limit page limit number'}) if page is not None and page.isdigit() is False and page.strip() != '': errors.append({'page': 'Invalid page number'}) if len(errors) is not 0: response = jsonify(status='error', message="Please provide valid details", errors=errors) response.status_code = 400 return response page = int(page) if page is not None and page.strip() != '' else 1 per_page = int( per_page) if per_page is not None and per_page.strip() != '' else 20 # Overall filter results businesses = businesses.paginate(per_page=per_page, page=page) if len(Business.serializer(businesses.items)) is not 0: response = jsonify({ 'status': 'ok', 'message': 'There are {} businesses found'.format(str(len(businesses.items))), 'next_page': businesses.next_num, 'previous_page': businesses.prev_num, 'current_page': businesses.page, 'pages': businesses.pages, 'total_businesses': businesses.total, 'businesses': Business.serializer(businesses.items) }) response.status_code = 200 return response response = jsonify(status='error', message="No business found!") response.status_code = 200 return response
def setUp(self): ''' Set up test data ''' self.main = create_app('testing') self.app = self.main.test_client() self.app_context = self.main.app_context() self.app_context.push() with self.app_context: db.init_app(self.main) db.create_all() self.sample_user = { 'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******' } self.exist_user = { 'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******' } self.unconfirmed_user = { 'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******', 'activation_token': 'AvauDT0T7wo_O6vnb5XJxKzuPteTIpJVv_0HRokS' } self.business_data = { 'name': 'Inzora rooftop coffee', 'description': 'We have best coffee for you,', 'category': 'Coffee-shop', 'country': 'Kenya', 'city': 'Nairobi' } # Business sample data self.rev_business_data = { 'name': 'KFC', 'description': 'Finger lickin\' good', 'category': 'Food', 'country': 'Kenya', 'city': 'Nairobi' } with self.main.test_request_context(): # Orphan id: User id that will be used to create an orphan token orphan_user = User(username="******", email="*****@*****.**", password=self.sample_user['password']) user = User(username=self.sample_user['username'], email=self.sample_user['email'], password=generate_password_hash( self.sample_user['password']), activation_token=None) unconfirmed_account = User( username=self.unconfirmed_user['username'], email=self.unconfirmed_user['email'], password=generate_password_hash( self.unconfirmed_user['password']), activation_token=self.unconfirmed_user['activation_token']) db.session.add(user) db.session.add(orphan_user) db.session.add(unconfirmed_account) db.session.commit() self.sample_user['id'] = user.id self.orphan_id = orphan_user.id self.unconfirmed_user_id = unconfirmed_account.id db.session.remove() token = Token(user_id=self.sample_user['id'], access_token=get_token(self.sample_user['id'])) orphan_token = Token(user_id=self.orphan_id, access_token=get_token(self.orphan_id)) unconfirmed_user_token = Token(user_id=self.unconfirmed_user_id, access_token=get_token( self.unconfirmed_user_id)) expired_token = Token(user_id=self.sample_user['id'], access_token=get_token( self.sample_user['id'], -3600)) # Create bad signature token # Bad signature: #nt secret key from the one used in our API used # to hash tokens other_signature_token = Token(user_id=self.sample_user['id'], access_token=get_token( self.sample_user['id'], 3600, 'other_signature')) business = Business( user_id=self.sample_user['id'], name=self.rev_business_data['name'], description=self.rev_business_data['description'], category=self.rev_business_data['category'], country=self.rev_business_data['country'], city=self.rev_business_data['city'], ) db.session.add(token) db.session.add(orphan_token) db.session.add(expired_token) db.session.add(unconfirmed_user_token) db.session.add(other_signature_token) db.session.add(business) db.session.commit() self.test_token = token.access_token self.expired_test_token = expired_token.access_token self.other_signature_token = other_signature_token.access_token self.orphan_token = orphan_token.access_token self.unconfirmed_user_token = unconfirmed_user_token.access_token
def get_user_businesses(): ''' User's Businesses list ''' user_id = token_id(request.headers.get('Authorization')) query = request.args.get('name') category = request.args.get('category') city = request.args.get('city') country = request.args.get('country') page = request.args.get('page') per_page = request.args.get('limit') businesses = Business.query.order_by(desc( Business.created_at)).filter_by(user_id=user_id) if businesses.count() is not 0: # Filter by search query if query is not None and query.strip() != '': businesses = businesses.filter( func.lower(Business.name).like('%' + func.lower(query) + '%')) # Filter by category if category is not None and category.strip() != '': businesses = businesses.filter( func.lower(Business.category) == func.lower(category)) # Filter by city if city is not None and city.strip() != '': businesses = businesses.filter( func.lower(Business.city) == func.lower(city)) # Filter by country if country is not None and country.strip() != '': businesses = businesses.filter( func.lower(Business.country) == func.lower(country)) errors = [] # Errors list if (per_page is not None and per_page.isdigit() is False and per_page.strip() != ''): errors.append({'limit': 'Invalid limit page limit number'}) if page is not None and page.isdigit() is False and page.strip() != '': errors.append({'page': 'Invalid page number'}) if len(errors) is not 0: response = jsonify(status='error', message="Please provide valid details", errors=errors) response.status_code = 400 return response page = int(page) if page is not None and page.strip() != '' else 1 per_page = int(per_page) if ((per_page is not None) and (per_page.strip() != '')) else 20 # Overall filter results businesses = businesses.paginate(per_page=per_page, page=page) if len(Business.serializer(businesses.items)) is not 0: response = jsonify({ 'status': 'ok', 'message': 'There are {} businesses found'.format( str(len(businesses.items))), 'next_page': businesses.next_num, 'previous_page': businesses.prev_num, 'current_page': businesses.page, 'pages': businesses.pages, 'total_businesses': businesses.total, 'businesses': Business.serializer(businesses.items) }) response.status_code = 200 return response response = jsonify(status='error', message="No business found!") response.status_code = 200 return response response = jsonify(status='error', message="You don't have any registered business") response.status_code = 200 return response
def setUp(self): """ Set up test data """ self.app = APP.test_client() self.app.testing = True self.sample_user = { 'id': uuid.uuid4().hex, 'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******' } self.exist_user = { 'id': uuid.uuid4().hex, 'username': '******', 'email': '*****@*****.**', 'password': '******', 'confirm_password': '******' } self.business_data = { 'id': uuid.uuid4().hex, 'name': 'Inzora rooftop coffee', 'description': 'We have best coffee for you,', 'country': 'Kenya', 'city': 'Nairobi' } save_user = User() save_user.save({ 'id': self.sample_user['id'], 'username': self.sample_user['username'], 'email': self.sample_user['email'], 'password': self.sample_user['password'], 'confirm_password': self.sample_user['confirm_password'] }) # Save business for reviews testing self.rev_business_data = { 'id': uuid.uuid4().hex, 'name': 'KFC', 'description': 'Finger lickin\' good', 'country': 'Kenya', 'city': 'Nairobi' } # Add user(owner) to the business data dict self.rev_business_data['user_id'] = self.sample_user['id'] # Save business in the storage list for testing Business.save(self.rev_business_data) with APP.test_request_context(): # Orphan id: User id that will be used to create an orphan token orphan_id = uuid.uuid4().hex save_user.save({ 'id': orphan_id, 'username': "******", 'email': "*****@*****.**", 'password': self.exist_user['password'], 'confirm_password': self.exist_user['confirm_password'] }) # Issue a token the the test user (sample_user) # Store test token in auth storage auth_token list token = get_token(self.sample_user['id']) # Orphan token: User token that do not have any registered business orphan_token = get_token(orphan_id) expired_token = get_token(self.sample_user['id'], -3600) # Create bad signature token # Bad signature: #nt secret key from the one used in our API used # to hash tokens other_signature_token = get_token(self.sample_user['id'], 3600, 'other_signature') User().add_token(token) User().add_token(expired_token) User().add_token(orphan_token) User().add_token(other_signature_token) self.test_token = token self.expired_test_token = expired_token self.other_signature_token = other_signature_token self.orphan_test_token = orphan_token