def test_get_customer(client, db): set_up(db) password = "******" customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(password)) db.session.add(customer) db.session.commit() response = client.post('/api/auth/customer/token', json=dict(email=customer.email, password=password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] headers = build_header(access_token) response = client.get('/api/customer', headers=headers, follow_redirects=True) assert response.status_code == 200 assert response.json['id'] == customer.id assert response.json['name'] == customer.name assert response.json['email'] == customer.email assert customer.verify_password(password)
def test_chai_apples(self): cust = customers.get_customer_by_customer_name('Arun') customer = Customer(cust.name, cust.eid, cust.aid, cust.joinDate) test_chai_apples_cart = Cart(customer) test_chai_apples_cart.add_multiple_products_to_cart(['CH1', 'AP1']) total = test_chai_apples_cart.display()[1] self.assertEqual(total, 9.11)
def test_change_customer_password(client, db): set_up(db) password = "******" customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(password)) db.session.add(customer) db.session.commit() response = client.post('/api/auth/customer/token', json=dict(email=customer.email, password=password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] new_password = "******" headers = build_header(access_token) response = client.put('/api/customer/password', json=dict(password=password, new_password=new_password), headers=headers, follow_redirects=True) assert response.status_code == 200 customer_db = db.session.query(Customer).filter_by( id=customer.id).one_or_none() assert customer_db.verify_password(new_password)
def book_car(): """ Book car Only POST method is allowed with route /customer/book Args: latitude (float) : current location (latitude) of customer longitude (float) : current location (longitude) of customer is_pink (bool) : does customer want pink car, true if want else False [Optional] booked_on (DateTime) : booking time [AutoCalculate] """ response = None try: params = dict() params.update({'latitude': float(request.form.get('latitude'))}) params.update({'longitude': float(request.form.get('longitude'))}) params.update({'is_pink': get_bool(request.form.get('is_pink'))}) params.update({'booked_on': datetime.now()}) if round(params.get('latitude')) in LAT_LNG_RANGE and round( params.get('longitude')) in LAT_LNG_RANGE: # check for cars as per customer's preference available_cars = Car.query.filter_by(is_pink=params.get('is_pink'), available_status=True).all() if available_cars: # calculate distance between car's location and customer's location distance = {} for car in available_cars: car_distance = Car.distance_travelled( params.get('latitude'), params.get('longitude'), car) distance.update({car.id: car_distance}) # get id of car which is nearest to customer booking_car_id = sorted(distance.items(), key=lambda x: x[1])[0][0] # alot that car to customer customer = Customer(booking_car_id) db.session.add(customer) Car.query.filter_by(id=booking_car_id).update( dict(available_status=False)) db.session.commit() response = jsonify( {'result': Serializer.serialize_list(available_cars)}) else: response = jsonify({'result': "NO_CARS_AVAILABLE"}) else: response = jsonify( {'result': "Please provide valid latitude and longitude."}) except ValueError as e: response = jsonify( {'result': "Please provide valid latitude/longitude."}) except Exception as e: response = jsonify( {'result': "Oops! Something went wrong. Please try again."}) return response
def test_update_customer_by_id(client, db): set_up(db) user_password = "******" customer_password = "******" user = User(name='Leia Organa', email='*****@*****.**', password=generate_password_hash(user_password), roles=[ UserRole(category=RoleCategory.SUPER_USER), UserRole(category=RoleCategory.ADMIN) ]) customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(customer_password)) db.session.add(user) db.session.add(customer) db.session.commit() response = client.post('/api/auth/user/token', json=dict(email=user.email, password=user_password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] name = "Darth Vader" email = "*****@*****.**" headers = build_header(access_token) response = client.put(f'/api/customer/{customer.id}', json=dict(name=name, email=email), headers=headers, follow_redirects=True) assert response.status_code == 200 assert response.json['id'] assert response.json['name'] == name assert response.json['email'] == email assert response.json['created_date'] assert response.json['updated_date'] customer_db = db.session.query(Customer).filter_by( id=response.json['id']).one_or_none() assert customer_db assert customer_db.id == response.json['id'] assert customer_db.name == response.json['name'] assert customer_db.email == response.json['email'] assert customer_db.created_date.strftime( DATE_FORMAT) == response.json['created_date'] assert customer_db.updated_date.strftime( DATE_FORMAT) == response.json['updated_date'] assert customer_db.verify_password(customer_password)
def test_get_wishlist(client, db): set_up(db) password = "******" customer = Customer(id=2, name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(password)) db.session.add(customer) product_1 = WishList(customer_id=customer.id, product_id="1") product_2 = WishList(customer_id=customer.id, product_id="2") product_3 = WishList(customer_id=customer.id, product_id="3") db.session.add(product_1) db.session.add(product_2) db.session.add(product_3) db.session.commit() response = client.post('/api/auth/customer/token', json=dict(email=customer.email, password=password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] headers = build_header(access_token) response = client.get(f'/api/wishlist/', headers=headers, follow_redirects=True) assert response.status_code == 200 assert len(response.json) == 3 products = db.session.query(WishList).filter_by( customer_id=customer.id).all() for index, product in enumerate(response.json, start=0): product_db = products[index] assert product_db.product_id == product['product_id'] response = client.get(f'/api/wishlist/1/1', headers=headers, follow_redirects=True) assert response.status_code == 200 assert len(response.json) == 1 products = db.session.query(WishList).filter_by( customer_id=customer.id).all() product_db = products[0] product = response.json[0] assert product_db.product_id == product['product_id']
def test_add_product_into_wishlist(client, db): set_up(db) product_id = "e9a72482-7e95-44ff-ea5a-75147aef2184" product = { "price": 7999.9, "image": "http://challenge-api.luizalabs.com/images/e9a72482-7e95-44ff-ea5a-75147aef2184.jpg", "brand": "fender", "id": "e9a72482-7e95-44ff-ea5a-75147aef2184", "title": "Guitarra Telecaster Fender Standard", "reviewScore": 4.352941 } responses.add( responses.GET, f'http://challenge-api.luizalabs.com/api/product/{product_id}/', json=product, status=200) product_id = "e9a72482-7e95-44ff-ea5a-75147aef2184" password = "******" customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(password)) db.session.add(customer) db.session.commit() response = client.post('/api/auth/customer/token', json=dict(email=customer.email, password=password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] headers = build_header(access_token) response = client.post(f'/api/wishlist/product/{product_id}', headers=headers, follow_redirects=True) assert response.status_code == 200 assert response.json['id'] assert response.json['product_id'] == product_id wishlist_db = db.session.query(WishList).filter_by( id=response.json['id']).one_or_none() assert wishlist_db assert wishlist_db.product_id == product_id
def test_get_customer_by_email(client, db): set_up(db) user_password = "******" customer_password = "******" user = User(name='Leia Organa', email='*****@*****.**', password=generate_password_hash(user_password), roles=[ UserRole(category=RoleCategory.SUPER_USER), UserRole(category=RoleCategory.ADMIN) ]) customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(customer_password)) db.session.add(user) db.session.add(customer) db.session.commit() response = client.post('/api/auth/user/token', json=dict(email=user.email, password=user_password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] headers = build_header(access_token) response = client.get(f'/api/customer/email/{customer.email}', headers=headers, follow_redirects=True) assert response.status_code == 200 assert response.json['id'] == customer.id assert response.json['name'] == customer.name assert response.json['email'] == customer.email assert customer.verify_password(customer_password)
def test_update_customer(client, db): set_up(db) password = "******" customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(password)) db.session.add(customer) db.session.commit() response = client.post('/api/auth/customer/token', json=dict(email=customer.email, password=password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] name = "Darth Vader" email = "*****@*****.**" headers = build_header(access_token) response = client.put('/api/customer', json=dict(name=name, email=email), headers=headers, follow_redirects=True) assert response.status_code == 200 assert response.json['id'] assert response.json['name'] == name assert response.json['email'] == email assert response.json['created_date'] assert response.json['updated_date'] customer_db = db.session.query(Customer).filter_by( id=response.json['id']).one_or_none() assert customer_db assert customer_db.id == response.json['id'] assert customer_db.name == response.json['name'] assert customer_db.email == response.json['email'] assert customer_db.created_date.strftime( DATE_FORMAT) == response.json['created_date'] assert customer_db.updated_date.strftime( DATE_FORMAT) == response.json['updated_date'] assert customer_db.verify_password(password)
from app import db, Order_created, Product, Customer db.create_all() Tom = Customer(first_name='Tom', last_name='Hennessy') Ben = Customer(first_name='Ben', last_name='Hasketh') db.session.add(Tom) db.session.add(Ben) db.session.commit() mouse = Product(item='Razer mouse') keyboard = Product(item='Excelvan keyboard') monitor = Product(item='HP monitor') db.session.add(mouse) db.session.add(monitor) db.session.add(keyboard) db.session.commit() order_1 = Order_created(customer_id=Tom.id, product_id=mouse.id) order_2 = Order_created(customer_id=Tom.id, product_id=keyboard.id) order_3 = Order_created(customer_id=Ben.id, product_id=mouse.id) db.session.add(order_1) db.session.add(order_2) db.session.add(order_3) db.session.commit()
def test_get_all_customers(client, db): set_up(db) user_password = "******" customer_1_password = "******" customer_2_password = "******" user = User(name='Leia Organa', email='*****@*****.**', password=generate_password_hash(user_password), roles=[ UserRole(category=RoleCategory.SUPER_USER), UserRole(category=RoleCategory.ADMIN) ]) customer_1 = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(customer_1_password)) customer_2 = Customer(name="Han Solo", email="*****@*****.**", password=generate_password_hash(customer_2_password)) db.session.add(user) db.session.add(customer_1) db.session.add(customer_2) db.session.commit() response = client.post('/api/auth/user/token', json=dict(email=user.email, password=user_password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] headers = build_header(access_token) response = client.get(f'/api/customer/', headers=headers, follow_redirects=True) assert response.status_code == 200 assert len(response.json) == 3 customers = db.session.query(Customer).all() for index, customer in enumerate(response.json, start=0): customer_db = customers[index] assert customer_db.id == customer['id'] assert customer_db.name == customer['name'] assert customer_db.email == customer['email'] response = client.get(f'/api/customer/1/1', headers=headers, follow_redirects=True) assert response.status_code == 200 assert len(response.json) == 1 customers = db.session.query(Customer).all() customer_db = customers[0] customer = response.json[0] assert customer_db.id == customer['id'] assert customer_db.name == customer['name'] assert customer_db.email == customer['email']
print("MY_HOME:", os.environ['DATABASE_URL']) DATABASE_URI = os.environ[ 'DATABASE_URL'] + "?sslmode=require" or f"postgresql://{DATABASE_USER}:{DATABASE_PASSWORD}@localhost:5432/loancompany" engine = create_engine(DATABASE_URI) Base = declarative_base() Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() customer1 = Customer(name="Tom", contact="2332770334", loan_amount=2500, loan_repaid=300, prepayment=0, arrears=100, city="Accra", region="Greater Accra", location="Ghana", coordinates="5.6037° N, 0.1870° W") customer2 = Customer(name="Roxanne", contact="233548705628", loan_amount=2500, loan_repaid=300, prepayment=500, arrears=0, city="Tema", region="Greater Accra", location="Ghana", coordinates="5.6037° N, 0.1870° W") customer3 = Customer(name="Joe",
def finish_journey(customer_id): """ Finish car trip for particular customer. Only POST method is allowed with route /customer/<customer_id>/complete Args: customer_id (int) : unique id of the customer latitude (float) : latitude of current location longitude (float) : longitude of current location """ response = None try: params = dict() params.update({'latitude': float(request.form.get('latitude', None))}) params.update( {'longitude': float(request.form.get('longitude', None))}) params.update({'customer_id': int(customer_id)}) if round(params.get('latitude')) in LAT_LNG_RANGE and round( params.get('longitude')) in LAT_LNG_RANGE: # customer with given customer_id booking_customer = Customer.query.filter_by( id=params.get('customer_id')).first() # car booked by given customer booking_car = Car.query.filter_by( id=booking_customer.car_id).first() completed_on = datetime.now() # calculate amount to be paid by customer after completion of trip booking_amount = Customer.set_amount(booking_customer.booked_on, completed_on, booking_car.is_pink) Customer.query.filter_by(id=params.get('customer_id')).update( dict(completed_on=completed_on, amount=booking_amount)) # update new location of car Car.query.filter_by(id=booking_customer.car_id).update( dict(available_status=True, latitude=params.get('latitude'), longitude=params.get('longitude'))) db.session.commit() response = jsonify(dict(result="Journey completed successfully.")) else: response = jsonify( {'result': "Please provide valid latitude and longitude."}) except ValueError as e: response = jsonify( dict(result="Please provide valid latitude/longitude.")) except AttributeError as e: response = jsonify( dict( result= "Oops! Customer with given id does not exists. Please check customer_id." )) except Exception as e: response = jsonify( dict(result="Oops! Something went wrong. Please try again.")) return response
def test_get_products(client, db): set_up(db) products = { "meta": { "page_number": 1, "page_size": 100 }, "products": [{ "price": 1699, "image": "http://challenge-api.luizalabs.com/images/1bf0f365-fbdd-4e21-9786-da459d78dd1f.jpg", "brand": "bébé confort", "id": "1bf0f365-fbdd-4e21-9786-da459d78dd1f", "title": "Cadeira para Auto Iseos Bébé Confort Earth Brown", "reviewScore": 3.4 }, { "price": 1149, "image": "http://challenge-api.luizalabs.com/images/958ec015-cfcf-258d-c6df-1721de0ab6ea.jpg", "brand": "bébé confort", "id": "958ec015-cfcf-258d-c6df-1721de0ab6ea", "title": "Moisés Dorel Windoo 1529", "reviewScore": 4.352941 }] } responses.add(responses.GET, f'http://challenge-api.luizalabs.com/api/product/?page=1', json=products, status=200) page = 1 password = "******" customer = Customer(name="Anakin Skywalker", email="*****@*****.**", password=generate_password_hash(password)) db.session.add(customer) db.session.commit() response = client.post('/api/auth/customer/token', json=dict(email=customer.email, password=password), follow_redirects=True) assert response.status_code == 200 assert response.json['access_token'] is not None access_token = response.json['access_token'] headers = build_header(access_token) response = client.get(f'/api/product/{page}', headers=headers, follow_redirects=True) assert response.status_code == 200 assert len(response.json['products']) == 2 assert response.json['meta']['page_number'] == products['meta'][ 'page_number'] assert response.json['meta']['page_size'] == products['meta']['page_size'] for index, product in enumerate(response.json['products'], start=0): product_api = products['products'][index] assert product['id'] == product_api['id'] assert product['title'] == product_api['title'] assert product['brand'] == product_api['brand'] assert product['image'] == product_api['image'] assert product['price'] == product_api['price'] assert product['reviewScore'] == product['reviewScore']
from app import db, Customer, Agent, Message db.drop_all() db.create_all() customer_names = ['Joe', 'John', 'Frank'] customers = [] for name in customer_names: customer = Customer(name=name) db.session.add(customer) customers.append(customer) db.session.commit() agent_names = ['Ben', 'Mike'] agents = [] for name in agent_names: agent = Agent(name=name) db.session.add(agent) agents.append(agent) db.session.commit() threads = [['Hello, I need help', 'How can I help you?', 'I need a loan'], ['I\'m just spamming']] for thread_idx, thread in enumerate(threads): print(thread) # Pick customers and agents in a round robin fashion customer = customers[thread_idx % len(customers)] agent = agents[thread_idx % len(agents)] print(customer)