def test_delete__success(self): data_user = User.get() data_address1 = Address.create( uuid=uuid.uuid4(), user=data_user, nation='Italia', city='Prato', postal_code='59100', local_address='Via Roncioni 10', phone='0574100100', ) data_address2 = Address.create( uuid=uuid.uuid4(), user=data_user, nation='Italia', city='Firenze', postal_code='59000', local_address='Via Baracca 10', phone='0558778666', ) resp = self.app.delete('/addresses/{}'.format(data_address1.uuid)) all_addresses = Address.select() address_from_db = all_addresses.get() assert resp.status_code == NO_CONTENT assert len(all_addresses) == 1 assert address_from_db.uuid == data_address2.uuid
def test_post__success(self): data_user = User.get() address_id_created = uuid.uuid4() Address.create( uuid=address_id_created, user=data_user, nation='Italia', city='Prato', postal_code='59100', local_address='Via Roncioni 10', phone='0574100100', ) data_address = { 'user_id': data_user.uuid, 'nation': 'Italia', 'city': 'Prato', 'postal_code': '59100', 'local_address': 'Via Roncioni 10', 'phone': '0574100100', } resp = self.app.post('/addresses/', data=data_address) query = Address.select().where(Address.uuid != address_id_created) assert resp.status_code == CREATED assert query.get().json() == json.loads(resp.data.decode())
def test_delete__address_id_not_exists(self): data_user = User.get() Address.create( uuid=uuid.uuid4(), user=data_user, nation='Italia', city='Prato', postal_code='59100', local_address='Via Roncioni 10', phone='0574100100', ) resp = self.app.delete('/addresses/{}'.format(uuid.uuid4())) assert resp.status_code == NOT_FOUND assert len(Address.select()) == 1
def address_creator(num_addr): LIST_COUNTRIES = [ 'Belgium', 'France', 'Germany', 'Greece', 'Italy', 'Portugal', 'Spain' ] for i in range(num_addr): country = random.choice(LIST_COUNTRIES) Address.create( uuid=fake.uuid4(), user=User.select().order_by(fn.Random()).get(), country=country, city=fake.city(), post_code=fake.postcode(), address=fake.street_name(), phone=fake.phone_number(), )
def post(self): parser = reqparse.RequestParser() parser.add_argument('nation', type=utils.non_empty_str, required=True) parser.add_argument('city', type=utils.non_empty_str, required=True) parser.add_argument('postal_code', type=utils.non_empty_str, required=True) parser.add_argument('local_address', type=utils.non_empty_str, required=True) parser.add_argument('phone', type=utils.non_empty_str, required=True) args = parser.parse_args(strict=True) for parm in [ 'nation', 'city', 'postal_code', 'local_address', 'phone' ]: if len(args[parm]) < 3: return '', BAD_REQUEST address = Address.create( uuid=uuid.uuid4(), user=g.current_user, nation=args['nation'], city=args['city'], postal_code=args['postal_code'], local_address=args['local_address'], phone=args['phone'], ) return address.json(), CREATED
def address(): if request.method == 'POST': app.logger.debug('Args: {}'.format(request.args)) restaurant_id = int(request.args.get('restaurant_id', '')) address = to_string(request.args.get('address', '')) state = to_string(request.args.get('state', '')) city = to_string(request.args.get('city', '')) zip_code = int(request.args.get('zip', '')) r = Restaurant.query.filter( Restaurant.id == restaurant_id).first_or_404() address = Address.create(address, state, city, zip_code, restaurant=r) return json_response({'response': 'Created', 'id': address.id}) elif request.method == 'GET': response_list = list() restaurant_id = int(request.args.get('restaurant_id', 0)) results = Address.get_address_by(restaurant_id) app.logger.debug('Address: {}'.format(results)) if results: for result in results: response_list.append({ 'address': result.address, 'state': result.state, 'city': result.city, 'restaurant_id': result.restaurant_id, 'id': result.id }) return json_response(response_list)
def create(data, author, institution): """Create an event.""" event = Event() event.text = data.get('text') event.programation = data.get('programation') event.video_url = data.get('video_url', []) event.title = data.get('title') event.photo_url = data.get('photo_url') event.useful_links = data.get('useful_links', []) event.official_site = data.get('official_site') event.author_key = author.key event.author_photo = author.photo_url event.author_name = author.name event.institution_key = institution.key event.institution_name = institution.name event.institution_acronym = institution.acronym event.institution_image = institution.photo_url event.last_modified_by = author.key event.last_modified_by_name = author.name event.local = data.get('local') event.start_time = datetime.datetime.strptime( data.get('start_time'), "%Y-%m-%dT%H:%M:%S") event.end_time = datetime.datetime.strptime( data.get('end_time'), "%Y-%m-%dT%H:%M:%S") event.address = Address.create(data.get('address')) event.isValid() return event
def test_put__success(self): data_user = User.get() data_address = Address.create( uuid=uuid.uuid4(), user=data_user, nation='Italia', city='Prato', postal_code='59100', local_address='Via Roncioni 10', phone='0574100100', ) new_data_address = { 'user_id': data_user.uuid, 'nation': 'Italia', 'city': 'Firenze', 'postal_code': '505050', 'local_address': 'Via Baracca 15', 'phone': '0550550550', } resp = self.app.put('/addresses/{}'.format(data_address.uuid), data=new_data_address) address_from_db = Address.get() expected_data = { 'user_id': address_from_db.user.uuid, 'nation': address_from_db.nation, 'city': address_from_db.city, 'postal_code': address_from_db.postal_code, 'local_address': address_from_db.local_address, 'phone': address_from_db.phone, } assert expected_data == new_data_address assert resp.status_code == CREATED assert address_from_db.json() == json.loads(resp.data.decode())
def test_get__address_found(self): data_user = User.get() address_id_created = uuid.uuid4() Address.create( uuid=address_id_created, user=data_user, nation='Italia', city='Prato', postal_code='59100', local_address='Via Roncioni 10', phone='0574100100', ) resp = self.app.get('/addresses/{}'.format(address_id_created)) query = Address.get() assert resp.status_code == OK assert query.json() == json.loads(resp.data.decode())
def add_address(user, country='Italy', city='Pistoia', post_code='51100', address='Via Verdi 12', phone='3294882773', id=None): return Address.create( uuid=id or uuid.uuid4(), user=user, country=country, city=city, post_code=post_code, address=address, phone=phone, )
def create_address(self, user=None, nation="Italy", city="Prato", postal_code="59100", local_address="Via Roncioni 10", phone="0574100100"): if not user: user = self.create_user() return Address.create( uuid=uuid.uuid4(), user=user, nation=nation, city=city, postal_code=postal_code, local_address=local_address, phone=phone, )
def createInstitution(user, data): """Cretate a new institution stub.""" inst_stub = Institution() for property in data: if property != 'admin': setattr(inst_stub, property, data[property]) if (data.get("photo_url") is None): inst_stub.photo_url = "app/images/institution.png" inst_stub.address = Address.create(data.get('address')) inst_stub.state = 'pending' inst_stub.put() return inst_stub
def create_address(): first_name = request.json['first_name'] last_name = request.json['last_name'] phone = request.json['phone'] email = request.json['email'] street = request.json['street'] city = request.json['city'] state = request.json['state'] zip = request.json['zip'] favorite = request.json['favorite'] new_address = Address.create(first_name, last_name, phone, email, street, city, state, zip, favorite) if new_address is not None: return address_schema.jsonify(new_address), 201 else: return jsonify(message="Unable to create address"), 400
def post(self): json = request.get_json() try: Address.verify_json(json) except ValidationError as err: return {"message": err.message}, BAD_REQUEST address = Address.create( uuid=uuid.uuid4(), user=g.current_user, nation=json['nation'], city=json['city'], postal_code=json['postal_code'], local_address=json['local_address'], phone=json['phone'], ) return address.json(), CREATED
def post(self): res = request.get_json(force=True) errors = Address.validate_input(res) if errors: return errors, BAD_REQUEST data = res['data']['attributes'] addr = Address.create( uuid=uuid.uuid4(), user=auth.current_user, country=data['country'], city=data['city'], post_code=data['post_code'], address=data['address'], phone=data['phone']) return generate_response(addr.json(), CREATED)
def test_put__modify_one_field(self): data_user = User.get() data_address = Address.create( uuid=uuid.uuid4(), user=data_user, nation='Italia', city='Prato', postal_code='59100', local_address='Via Roncioni 10', phone='0574100100', ) new_data_address = { 'nation': 'Albania', } resp = self.app.put('/addresses/{}'.format(data_address.uuid), data=new_data_address) assert resp.status_code == BAD_REQUEST
def main(): database.connect() seed(2) fake = Factory.create('it_IT') fake.seed(99) items_list = [] users_list = [] for _ in range(10): item = Item.create( uuid=fake.uuid4(), name=fake.word(), price=fake.random_int(), description=fake.sentence(), category=fake.word(), availability=randint(1, 10), ) items_list.append(item) for _ in range(20): user = User.create( uuid=fake.uuid4(), first_name=fake.first_name(), last_name=fake.last_name(), email=fake.email(), password=fake.password(), ) users_list.append(user) for user in users_list: for x in range(randint(1, 3)): Address.create( uuid=fake.uuid4(), user=user, nation=fake.country(), city=fake.city(), postal_code=fake.postcode(), local_address=fake.address(), phone=fake.phone_number(), ) for user in users_list: # User has three chance on four to make an order make_order = randint(0, 4) # If use make an order, I insert an order and I iterate the items list if make_order != 0: order_total_price = 0 order_item_quantity = 0 order_item_subtotal = 0 order = Order.create( uuid=fake.uuid4(), total_price=order_total_price, user=user, ) for item in items_list: # If item_quantity == 0, the item isn't counted in the order order_item_quantity = randint(0, 3) if order_item_quantity != 0: order_item_subtotal = item.price * order_item_quantity order_total_price += order_item_subtotal OrderItem.create( order=order, item=item, quantity=item.price, subtotal=order_item_subtotal, ) order.total_price = order_total_price order.save()
def get(self): """Reset entities.""" Utils._assert( self.request.host in [ "backend.plataformacis.org", "backend.eciis-splab.appspot.com" ], "The production environment can not be redefined", NotAuthorizedException) clear_data_store() self.response.headers[ 'Content-Type'] = 'application/json; charset=utf-8' response = {"msg": "Datastore Cleaned"} self.response.write(json.dumps(response)) # Initialize the datastore jsonList = [] # new User Mayza mayza = User() mayza.name = 'Mayza Nunes' mayza.cpf = '089.675.908-90' mayza.email = ['*****@*****.**'] mayza.photo_url = getGravatar(mayza.email) mayza.state = 'active' mayza.put() # new User Maiana maiana = User() maiana.name = 'Maiana Brito' maiana.cpf = '089.675.908-65' maiana.email = ['*****@*****.**'] maiana.photo_url = getGravatar(maiana.email) maiana.state = 'active' maiana.put() # new User Raoni raoni = User() raoni.name = 'Raoni Smaneoto' raoni.cpf = '089.675.908-65' raoni.email = ['*****@*****.**'] raoni.photo_url = getGravatar(raoni.email) raoni.state = 'active' raoni.put() # new User Luiz luiz = User() luiz.name = 'Luiz Silva' luiz.cpf = '089.675.908-65' luiz.email = ['*****@*****.**'] luiz.photo_url = getGravatar(luiz.email) luiz.state = 'active' luiz.put() # new User Ruan ruan = User() ruan.name = 'Ruan Silveira' ruan.cpf = '089.675.908-65' ruan.email = ['*****@*****.**'] ruan.photo_url = getGravatar(ruan.email) ruan.state = 'active' ruan.put() # new User Tiago tiago = User() tiago.name = 'Tiago Pereira' tiago.cpf = '089.675.908-65' tiago.email = ['*****@*****.**'] tiago.photo_url = getGravatar(tiago.email) tiago.state = 'active' tiago.put() # new User Admin admin = User() admin.name = 'Administrador da Plataforma Virtual CIS' admin.cpf = '000.000.000-01' admin.email = ['*****@*****.**', '*****@*****.**'] admin.photo_url = "app/images/avatar.png" admin.state = 'active' admin.put() # new User Other Admin other_admin = User() other_admin.name = 'Teste Admin' other_admin.cpf = '089.675.908-65' other_admin.email = ['*****@*****.**', '*****@*****.**'] other_admin.photo_url = "app/images/avatar.png" other_admin.state = 'active' other_admin.put() jsonList.append({"msg": "database initialized with a few users"}) # new Institution Ministério da Saúde address_data = { 'street': 'Esplanada dos Ministérios Bloco G ', 'neighbourhood': 'Zona Cívico-Administrativa', 'city': 'Brasília', 'cep': '70058-900 ', 'federal_state': 'Distrito Federal', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Ministério da Saúde', 'acronym': 'MS', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'GOVERNMENT_AGENCIES', 'description': 'Ministério da Saúde', 'photo_url': 'https://i1.wp.com/notta.news/wp-content/uploads/2017/08/tbg_20170713080909_62787.jpg?w=1024', 'email': '*****@*****.**', 'phone_number': '61 3315-2425', 'state': 'active', 'institutional_email': '*****@*****.**', 'leader': ' Ministro Ricardo Barros', } data_deciis = { 'name': 'Departamento do Complexo Industrial e Inovação em Saúde', 'acronym': 'DECIIS', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'GOVERNMENT_AGENCIES', 'description': 'Departamento do Complexo Industrial e Inovação em Saúde', 'photo_url': 'http://www.plataformacis.org/images/logo.png', 'email': '*****@*****.**', 'state': 'active', 'institutional_email': '*****@*****.**', 'leader': ' Ministro Ricardo Barros' } ms = createInstitution(data, admin) deciis = createInstitution(data_deciis, admin) deciis.trusted = True for user in [ mayza, maiana, luiz, raoni, ruan, tiago, admin, other_admin ]: user.follow(deciis.key) user.follow(ms.key) deciis.follow(user.key) ms.follow(user.key) deciis.put() ms.put() admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, ms.key.urlsafe()) create_profile(admin, ms) admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, deciis.key.urlsafe()) admin.add_permissions(permissions.DEFAULT_SUPER_USER_PERMISSIONS, deciis.key.urlsafe()) create_profile(admin, deciis) admin.put() address_data = { 'number': '882', 'street': 'Avenida Aprígio Veloso', 'neighbourhood': 'Universitário', 'city': 'Campina Grande', 'federal_state': 'Paraíba', 'cep': '58428-830', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Laboratório de Avaliação e Desenvolvimento de Biomateriais do Nordeste', 'acronym': 'CERTBIO', 'cnpj': '18.104.068/0001-86', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'RESEARCH_INSTITUTE', 'description': 'Ensaio Químico - Determinação de Material Volátil por Gravimetria e Ensaio Biológico - Ensaio de Citotoxicidade', 'photo_url': 'https://pbs.twimg.com/profile_images/1782760873/Logo_do_site_400x400.jpg', 'email': '*****@*****.**', 'institutional_email': '*****@*****.**', 'phone_number': '83 3322-4455', 'state': 'active', 'leader': 'User' } certbio = createInstitution(data, other_admin) for user in [mayza, other_admin]: certbio.add_member(user) user.add_institution(certbio.key) user.follow(certbio.key) create_profile(user, certbio) for user in [mayza, maiana, luiz, raoni, ruan, tiago, other_admin]: certbio.follow(user.key) user.follow(certbio.key) address_data = { 'number': '1445', 'street': 'Rua Dom Pedro II', 'neighbourhood': 'Prata', 'city': 'Campina Grande', 'cep': '58400-565', 'federal_state': 'Paraíba', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Software Practice Laboratory', 'acronym': 'SPLAB', 'cnpj': '18.104.068/0001-56', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'COLLEGE', 'description': """The mission of the Software Practices Laboratory (SPLab) is to promote the development of the state-of-the-art in the theory and practice of Software Engineering.""", 'email': '*****@*****.**', 'institutional_email': '*****@*****.**', 'phone_number': '83 3322-7865', 'state': 'active', 'leader': 'User' } splab = createInstitution(data, other_admin) for user in [other_admin]: splab.add_member(user) user.add_institution(splab.key) user.follow(splab.key) create_profile(user, splab) for user in [maiana, luiz, raoni, ruan, tiago, other_admin]: splab.follow(user.key) user.follow(splab.key) # new Institution eciis address_data = { 'number': '456', 'street': 'Rua Francisco Lopes', 'neighbourhood': 'Centenário', 'city': 'Campina Grande', 'cep': '58428-080', 'federal_state': 'Paraíba', 'country': 'Brasil' } address_key = Address.create(address_data) data = { 'name': 'Complexo Industrial da Saude', 'acronym': 'e-ciis', 'cnpj': '18.104.068/0001-30', 'legal_nature': 'PUBLIC', 'address': address_key, 'actuation_area': 'COLLEGE', 'description': 'The mission of the e-CIIS is to promote the development of the state-of-the-art in the theory and practice of Software Engineering.', 'photo_url': 'http://www.paho.org/bra/images/stories/BRA01A/logobireme.jpg', 'email': '*****@*****.**', 'institutional_email': '*****@*****.**', 'phone_number': '83 3322-7865', 'state': 'active', 'leader': 'User' } eciis = createInstitution(data, other_admin) for user in [maiana, luiz, raoni, ruan, tiago, mayza, other_admin]: eciis.add_member(user) user.add_institution(eciis.key) user.follow(eciis.key) create_profile(user, eciis) for user in [mayza, maiana, luiz, raoni, ruan, tiago, other_admin]: eciis.follow(user.key) eciis.parent_institution = splab.key eciis.put() splab.children_institutions = [eciis.key] splab.put() jsonList.append( {"msg": "database initialized with a few institutions"}) other_admin.institutions_admin = [certbio.key, eciis.key, splab.key] other_admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, certbio.key.urlsafe()) other_admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, splab.key.urlsafe()) other_admin.add_permissions(permissions.DEFAULT_ADMIN_PERMISSIONS, eciis.key.urlsafe()) other_admin.put() # POST of Mayza To Certbio Institution mayza_post = Post() mayza_post.title = "Novo edital do CERTBIO" mayza_post.text = TEXT mayza_post.author = mayza.key mayza_post.institution = certbio.key mayza_post.last_modified_by = mayza.key mayza_post.put() add_comments_to_post(mayza, maiana, mayza_post, mayza.institutions[0], 2) mayza.add_permissions(['edit_post', 'remove_post'], mayza_post.key.urlsafe()) # POST of Mayza To Certbio Institution with image post_with_image = Post() post_with_image.title = "Post do CERTBIO com imagem" post_with_image.photo_url = "https://workingatbooking.com/content/uploads/2017/04/womenintech_heroimage.jpg" post_with_image.text = TEXT post_with_image.author = mayza.key post_with_image.institution = certbio.key post_with_image.last_modified_by = mayza.key post_with_image.put() add_comments_to_post(mayza, raoni, post_with_image, mayza.institutions[0], 1) mayza.add_permissions(['edit_post', 'remove_post'], post_with_image.key.urlsafe()) # Side efect of a post mayza.posts = [mayza_post.key, post_with_image.key] mayza.put() eciis.posts = [] eciis.put() certbio.posts = [mayza_post.key] certbio.put() splab.posts = [] splab.put() jsonList.append({"msg": "database initialized with a few posts"}) self.response.write(json.dumps(jsonList))
def get_distance_between_two_addresses(self, first_address, second_address): # check address in db query_first = Address.select().where(Address.name == first_address) query_second = Address.select().where(Address.name == second_address) if query_first.exists() and query_second.exists(): query_distance = DistanceBetweenAddress.select().where( DistanceBetweenAddress.address_id == query_first.get().id, DistanceBetweenAddress.next_address_id == query_second.get().id) if query_distance.exists(): return query_distance.get().distance router = Router(self.calculate_method) # Initialise it coord_s_t = time.time() first_lat, first_lng = (query_first.get().lat, query_first.get().lng) if query_first.exists() else \ self.get_coordinates_from_yandex(first_address) second_lat, second_lng = (query_second.get().lat, query_second.get().lng) if query_second.exists() else \ self.get_coordinates_from_yandex(second_address) coord_e_t = time.time() start = router.findNode(first_lng, first_lat) # Find start and end nodes end = router.findNode(second_lng, second_lat) rout_s_t = time.time() status, route = router.doRoute( start, end) # Find the route - a list of OSM nodes route_e_t = time.time() if status == 'success': routeLatLons = list(map(router.nodeLatLon, route)) # Get actual route coordinates total_distance = 0 # calculate total distance from route coordinates for index in range(1, len(routeLatLons)): total_distance += geopy.distance.vincenty( routeLatLons[index - 1], routeLatLons[index]).km else: total_distance = 0 # это случается, когда 2 точки с одинаковым адресом, надо перепроверить print(f'{route}') first = query_first.get().id if query_first.exists( ) else Address.create(name=first_address, lat=first_lat, lng=first_lng) second = query_second.get().id if query_second.exists( ) else Address.create( name=second_address, lat=second_lat, lng=second_lng) DistanceBetweenAddress.bulk_create([ DistanceBetweenAddress(address_id=first, next_address_id=second, distance=total_distance), DistanceBetweenAddress(address_id=second, next_address_id=first, distance=total_distance) ]) print(f'COORDINATES TIME = {coord_e_t - coord_s_t} sec') print(f'ROUTE TIME = {route_e_t - rout_s_t} sec') print(total_distance, 'Total distance ==============================') return total_distance