Exemplo n.º 1
0
    def test_post__success_empty_db(self):
        data_user = User.get()
        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()
        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 == data_address
        assert resp.status_code == CREATED
        assert len(query) == 1
        assert query.get().json() == json.loads(resp.data.decode())
Exemplo n.º 2
0
    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())
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
    def put(self, address_id):
        json = request.get_json()
        try:
            address = (Address.select().where(
                Address.uuid == address_id).where(
                    Address.user == g.current_user).get())
        except Address.DoesNotExist:
            return None, NOT_FOUND

        try:
            Address.verify_json(json)
        except ValidationError as err:
            return {"message": err.message}, BAD_REQUEST

        if address.user.uuid == g.current_user.uuid:
            address.nation = json['nation']
            address.city = json['city']
            address.postal_code = json['postal_code']
            address.local_address = json['local_address']
            address.phone = json['phone']
            address.save()

            return address.json(), CREATED
        else:
            return '', BAD_REQUEST
Exemplo n.º 5
0
def address_create():
	address_form = AddressForm(request.form)
	user = auth.get_logged_in_user()
	if request.method == "POST":
		address = Address(
			user = user,
			street=address_form.street.data,
			zipcode=address_form.zipcode.data,
			state=address_form.state.data,
			country=address_form.country.data
			)
		address.save()
		flash("Address successfully saved")
		return redirect(url_for("dashboard"))
	elif request.method == "GET":
		try:
			exist = Address.select().where(Address.user == user).get()
			return redirect(url_for("address"))
		except Address.DoesNotExist:
			if request.method == "POST":
				address = Address(
					user = user,
					street=address_form.street.data,
					zipcode=address_form.zipcode.data,
					state=address_form.state.data,
					country=address_form.country.data
					)
				address.save()
				flash("Address successfully saved")
				return redirect(url_for("dashboard"))
			else:
				return render_template("address_create.html", address_form=address_form)
Exemplo n.º 6
0
    def test_post__success_empty_db(self):
        data_address = {
            'nation': 'Italia',
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.open_with_auth('/addresses/',
                                   'post',
                                   self.user.email,
                                   'p4ssw0rd',
                                   data=data_address)

        address_from_db = Address.get()
        expected_data = {
            '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 == data_address
        assert resp.status_code == CREATED
        assert len(Address.select()) == 1
        assert address_from_db.json() == json.loads(resp.data.decode())
Exemplo n.º 7
0
 def test_delete__empty_db_address_id_not_exists(self):
     resp = self.open_with_auth('/addresses/{}'.format(uuid.uuid4()),
                                'delete',
                                self.user.email,
                                'p4ssw0rd',
                                data='')
     assert resp.status_code == NOT_FOUND
     assert len(Address.select()) == 0
Exemplo n.º 8
0
    def test_get_addresses_list__success(self):
        add_address(
            self.user, id='4373d5d7-cae5-42bc-b218-d6fc6d18626f')

        addr_list = [a for a in Address.select()]
        data = AddressSchema.jsonapi_list(addr_list)

        expected_result = EXPECTED_ADDRESSES['get_addresses_list__success']
        assert_valid_response(data, expected_result)
Exemplo n.º 9
0
    def get(self, address_id):
        try:
            address = (Address.select().where(
                Address.uuid == address_id).where(
                    Address.user == g.current_user).get())
        except Address.DoesNotExist:
            return None, NOT_FOUND

        return address.json(), OK
Exemplo n.º 10
0
def order_creator(num_order):
    for i in range(num_order):
        order_id = fake.uuid4()
        Order.create(uuid=order_id,
                     user=User.select().order_by(fn.Random()).get(),
                     total_price=0,
                     delivery_address=Address.select().order_by(
                         fn.Random()).get(),
                     items=[])
Exemplo n.º 11
0
    def test_create_address__not_json_failure(self):
        user = add_user('*****@*****.**', '123')
        addr = new_addr(user)

        resp = open_with_auth(self.app, '/addresses/', 'POST', user.email,
                              TEST_USER_PSW, 'application/json',
                              wrong_dump(addr))

        assert resp.status_code == BAD_REQUEST
        assert len(Address.select()) == 0
Exemplo n.º 12
0
    def delete(self, address_id):
        try:
            address = (Address.select().where(
                Address.uuid == address_id).where(
                    Address.user == g.current_user).get())
        except Address.DoesNotExist:
            return None, NOT_FOUND

        address.delete_instance()
        return None, NO_CONTENT
Exemplo n.º 13
0
    def test_delete_address__success(self):
        user = add_user('*****@*****.**', '123')
        addr = add_address(user,
                           city="Firenze",
                           post_code='50132',
                           address="Via Rossi 10")

        resp = open_with_auth(self.app, '/addresses/{}'.format(addr.uuid),
                              'DELETE', user.email, TEST_USER_PSW, None, None)
        assert resp.status_code == NO_CONTENT
        assert not Address.select().exists()
Exemplo n.º 14
0
def run_mailing(subject_field: Entry, text_field: Text, addresses_field: Text):
    save_email_addresses(addresses_field)
    subject = subject_field.get()
    text = text_field.get(1.0, END)
    save_email(subject_field.get(), text_field.get(1.0, END))

    addresses = Address.select()
    for address in addresses:
        logger.info(f'Sending: {address.email}')
        send_email(email=address.email, subject=subject, text=text)

        time.sleep(1)
Exemplo n.º 15
0
    def test_delete__success(self):
        data_address1 = self.create_address(self.user)

        # TODO: Is ok to have a duplicated address for a single user?
        data_address2 = self.create_address(self.user)

        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
Exemplo n.º 16
0
    def test_post__field_not_exists(self):
        data_address = {
            'user_id': self.user.uuid,
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.app.post('/addresses/', data=data_address)
        assert resp.status_code == BAD_REQUEST
        assert len(Address.select()) == 0
Exemplo n.º 17
0
    def test_put__address_id_not_exists(self):
        data = {
            'user_id': self.user.uuid,
            'nation': 'Italia',
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.app.put('/addresses/{}'.format(uuid.uuid4()), data=data)
        assert resp.status_code == NOT_FOUND
        assert len(Address.select()) == 0
Exemplo n.º 18
0
 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
Exemplo n.º 19
0
    def test_create_address__success(self):
        user = add_user('*****@*****.**',
                        '123',
                        id='1777e816-3051-4faf-bbba-0c8a87baf08f')
        addr = format_jsonapi_request('address', new_addr(user))

        resp = open_with_auth(self.app, '/addresses/', 'POST', user.email,
                              TEST_USER_PSW, 'application/json',
                              json.dumps(addr))

        assert resp.status_code == CREATED
        assert len(Address.select()) == 1

        expected_result = EXPECTED_RESULTS['create_address__success']
        assert_valid_response(resp.data, expected_result)
Exemplo n.º 20
0
    def test_create_address__failure_missing_field(self):
        user = add_user('*****@*****.**', '123')
        addr = new_addr(user)
        del addr['country']
        addr = format_jsonapi_request('address', addr)

        resp = open_with_auth(self.app, '/addresses/', 'POST', user.email,
                              TEST_USER_PSW, 'application/json',
                              json.dumps(addr))

        assert resp.status_code == BAD_REQUEST
        assert len(Address.select()) == 0
        expected_result = EXPECTED_RESULTS[
            'create_address__failure_missing_field']
        assert_valid_response(resp.data, expected_result)
Exemplo n.º 21
0
    def test_post__field_not_exists(self):
        data_address = {
            'city': 'Prato',
            'postal_code': '59100',
            'local_address': 'Via Roncioni 10',
            'phone': '0574100100',
        }

        resp = self.open_with_auth('/addresses/',
                                   'post',
                                   self.user.email,
                                   'p4ssw0rd',
                                   data=data_address)
        assert resp.status_code == BAD_REQUEST
        assert len(Address.select()) == 0
Exemplo n.º 22
0
    def test_delete__success(self):
        data_address1 = self.create_address(self.user)

        # TODO: Is ok to have a duplicated address for a single user?
        data_address2 = self.create_address(self.user)

        resp = self.open_with_auth('/addresses/{}'.format(data_address1.uuid),
                                   'delete',
                                   self.user.email,
                                   'p4ssw0rd',
                                   data='')
        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
Exemplo n.º 23
0
    def test_delete_user__cascade(self):
        Item.create(
            uuid='429994bf-784e-47cc-a823-e0c394b823e8',
            name='mario',
            price=20.20,
            description='svariati mariii',
            availability=1,
            category='scarpe',
        )
        Item.create(
            uuid='577ad826-a79d-41e9-a5b2-7955bcf03499',
            name='GINO',
            price=30.20,
            description='svariati GINIIIII',
            availability=1,
            category='accessori',
        )
        email = '*****@*****.**'
        user = add_user(email, TEST_USER_PSW)
        user1 = add_user('*****@*****.**', TEST_USER_PSW)
        addr = add_address(user=user)
        addr1 = add_address(user=user1)
        Order.create(delivery_address=addr, user=user)
        order1 = Order.create(delivery_address=addr1, user=user1)

        user_path = 'users/'
        resp = open_with_auth(self.app, API_ENDPOINT.format(user_path), 'DELETE',
                              email, TEST_USER_PSW, None, None)
        assert resp.status_code == NO_CONTENT
        assert Address.select().count() == 1
        assert Order.select().count() == 1
        assert User.select().count() == 1
        addr2 = Address.get()
        assert addr2 == addr1
        order2 = Order.get()
        assert order2 == order1
        user2 = User.get()
        assert user2 == user1
Exemplo n.º 24
0
    def put(self, address_id):
        try:
            address = (Address.select().where(
                Address.uuid == address_id).where(
                    Address.user == g.current_user).get())
        except Address.DoesNotExist:
            return None, NOT_FOUND

        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

        if address.user.uuid == g.current_user.uuid:
            address.nation = args['nation']
            address.city = args['city']
            address.postal_code = args['postal_code']
            address.local_address = args['local_address']
            address.phone = args['phone']
            address.save()

            return address.json(), CREATED
        else:
            return '', BAD_REQUEST
Exemplo n.º 25
0
def load_addresses_to_field(field: Text):
    field.delete(1.0, END)

    field_text = '\n'.join(
        [f"{address.email}" for address in Address.select()])
    field.insert(INSERT, field_text)
Exemplo n.º 26
0
    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
Exemplo n.º 27
0
    def test_delete__address_id_not_exists(self):
        self.create_address(self.user)

        resp = self.app.delete('/addresses/{}'.format(uuid.uuid4()))
        assert resp.status_code == NOT_FOUND
        assert len(Address.select()) == 1
Exemplo n.º 28
0
def get_user_address_records(uid):
    records = Address.select().where(Address.owner == uid)
    return [record.get_display_data() for record in records]
Exemplo n.º 29
0
 def addresses(self):
     addresses = []
     for address in Address.select():
         addresses.append(address.dict())
     return addresses
Exemplo n.º 30
0
    def get(self):
        user_addrs = list(Address.select().where(
            Address.user == auth.current_user))

        return generate_response(Address.json_list(user_addrs), OK)