예제 #1
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())
예제 #2
0
    def test_put__success(self):
        data_address = self.create_address(self.user)

        new_data_address = {
            'user_id': self.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())
예제 #3
0
    def test_put__success(self):
        data_address = self.create_address(self.user)

        new_data_address = {
            'nation': 'Italia',
            'city': 'Firenze',
            'postal_code': '505050',
            'local_address': 'Via Baracca 15',
            'phone': '0550550550',
        }

        current_user = User.get(User.email == self.user.email)

        resp = self.open_with_auth('/addresses/{}'.format(data_address.uuid),
                                   'put',
                                   self.user.email,
                                   'p4ssw0rd',
                                   data=new_data_address)
        new_data_address['user'] = str(current_user.uuid)
        address_from_db = Address.get()
        expected_data = {
            'user': str(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())
예제 #4
0
    def test_get__address_found(self):
        address = self.create_address(self.user)

        resp = self.app.get('/addresses/{}'.format(address.uuid))
        query = Address.get()
        assert resp.status_code == OK
        assert query.json() == json.loads(resp.data.decode())
예제 #5
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())
예제 #6
0
    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())
예제 #7
0
    def test_put_address__success(self):
        addr_id = '943d754e-5826-4d5c-b878-47edc478b789'
        user = add_user('*****@*****.**',
                        '123',
                        id='943d754e-5826-4d5c-b878-47edc478b789')
        add_address(user,
                    city="Firenze",
                    post_code='50132',
                    address="Via Rossi 10",
                    id=addr_id)
        addr1 = new_addr(user,
                         city="Roma",
                         post_code="10000",
                         address="Via Bianchi 20")

        addr1 = format_jsonapi_request('address', addr1)

        resp = open_with_auth(self.app,
                              '/addresses/{}'.format(addr_id),
                              'PATCH',
                              user.email,
                              TEST_USER_PSW,
                              data=json.dumps(addr1),
                              content_type='application/json')

        assert resp.status_code == OK
        upd_addr = Address.get(Address.uuid == addr_id).json()
        expected_result = EXPECTED_RESULTS['put_address__success']
        # Check that the response data is what is expected and is also
        # the same as what has ben actually saved
        assert_valid_response(resp.data, expected_result)
        assert expected_result == json.loads(upd_addr)
예제 #8
0
def handle(data):
    if data.get('type') != 'wallet:addresses:new-payment':
        return
    address = data.get('data', {}).get('address')
    amount = float(
        data.get('additional_data', {}).get('amount', {}).get('amount'))
    if not address or amount:
        logger.error('address = {}, amount = {}'.format(address, amount))
    try:
        addr = Address.get(Address.address == address)
    except Address.DoesNotExist:
        logger.warning('{} not found'.format(address))
        return
    with config.DB.atomic() as tnx:
        try:
            if amount != addr.balance:
                if addr.post.count():
                    addr.post[0].send(amount)
                elif addr.reaction.count():
                    addr.reaction[0].send(amount)
                logger.info('addr = {} ({}) accepted'.format(
                    addr.address, addr.id))
            addr.balance += amount
            addr.save()
            tnx.commit()
        except Exception as e:
            logger.error(e)
            tnx.rollback()
예제 #9
0
    def get(self, address_uuid):
        try:
            addr = Address.get(
                Address.user == auth.current_user,
                Address.uuid == address_uuid
            )
            return generate_response(addr.json(), OK)

        except Address.DoesNotExist:
            return None, NOT_FOUND
예제 #10
0
    def test_get__address_found(self):
        address = self.create_address(self.user)

        resp = self.open_with_auth('/addresses/{}'.format(address.uuid),
                                   'get',
                                   self.user.email,
                                   'p4ssw0rd',
                                   data='')
        query = Address.get()
        assert resp.status_code == OK
        assert query.json() == json.loads(resp.data.decode())
예제 #11
0
    def patch(self, order_uuid):
        """ Modify a specific order. """
        res = request.get_json(force=True)

        errors = Order.validate_input(res, partial=True)
        if errors:
            return errors, BAD_REQUEST

        data = res['data']['relationships']
        req_items = data.get('items', {})
        req_address = data.get('delivery_address')

        with database.atomic():
            try:
                order = Order.get(uuid=str(order_uuid))
            except Order.DoesNotExist:
                abort(NOT_FOUND)

            address = None
            if req_address:
                try:
                    address = Address.get(
                        Address.uuid == req_address['data']['id'])
                except Address.DoesNotExist:
                    abort(BAD_REQUEST)
                order.delivery_address = address

            # get the user from the flask.g global object registered inside the
            # auth.py::verify() function, called by @auth.login_required decorator
            # and match it against the found user.
            # This is to prevent uses from modify other users' order.
            if auth.current_user != order.user and auth.current_user.admin is False:
                return ({
                    'message': "You can't delete another user's order"
                }, UNAUTHORIZED)

            # Generate the dict of {<Item>: <int:quantity>} to call Order.update_items
            items_uuids = [e['id'] for e in req_items.get('data', [])]
            items = list(Item.select().where(Item.uuid << items_uuids))
            if len(items) != len(items_uuids):
                abort(BAD_REQUEST)
            items_to_add = {
                item: req_item['quantity']
                for item in items for req_item in req_items.get('data', [])
                if str(item.uuid) == req_item['id']
            }
            try:
                order.update_items(items_to_add, new_address=address)
            except InsufficientAvailabilityException:
                abort(BAD_REQUEST)

        return generate_response(order.json(), OK)
예제 #12
0
    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())
예제 #13
0
    def patch(self, address_uuid):
        try:
            obj = Address.get(Address.user == auth.current_user,
                              Address.uuid == address_uuid)
        except Address.DoesNotExist:
            return None, NOT_FOUND

        res = request.get_json(force=True)

        errors = Address.validate_input(res)
        if errors:
            return errors, BAD_REQUEST

        data = res['data']['attributes']

        country = data.get('country')
        city = data.get('city')
        post_code = data.get('post_code')
        address = data.get('address')
        phone = data.get('phone')

        if country and country != obj.country:
            obj.country = country

        if city and city != obj.city:
            obj.city = city

        if post_code and post_code != obj.post_code:
            obj.post_code = post_code

        if address and address != obj.address:
            obj.address = address

        if phone and phone != obj.phone:
            obj.phone = phone

        obj.save()

        return generate_response(obj.json(), OK)
예제 #14
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
예제 #15
0
 def address_with_id(self, address_id):
     return Address.get(Address.id == address_id)
예제 #16
0
    def post(self):
        """ Insert a new order."""
        res = request.get_json(force=True)

        errors = Order.validate_input(res)
        if errors:
            return errors, BAD_REQUEST

        # Extract data to create the new order
        req_items = res['data']['relationships']['items']['data']
        req_address = res['data']['relationships']['delivery_address']['data']
        req_user = res['data']['relationships']['user']['data']

        # Check that the address exist
        try:
            user = User.get(User.uuid == req_user['id'])
        except User.DoesNotExist:
            abort(BAD_REQUEST)

        # get the user from the flask.g global object registered inside the
        # auth.py::verify() function, called by @auth.login_required decorator
        # and match it against the found user.
        # This is to prevent users from creating other users' order.
        if auth.current_user != user and auth.current_user.admin is False:
            return ({
                'message': "You can't create a new order for another user"
            }, UNAUTHORIZED)

        # Check that the items exist
        item_ids = [req_item['id'] for req_item in req_items]
        items = Item.select().where(Item.uuid << item_ids)
        if items.count() != len(req_items):
            abort(BAD_REQUEST)

        # Check that the address exist
        try:
            address = Address.get(Address.uuid == req_address['id'])
        except Address.DoesNotExist:
            abort(BAD_REQUEST)

        # Generate the dict of {<Item>: <int:quantity>} to call Order.create_order
        items_to_add = {}
        for req_item in req_items:
            item = next(i for i in items if str(i.uuid) == req_item['id'])
            items_to_add[item] = req_item['quantity']
        with database.atomic():
            try:
                order = Order.create(
                    delivery_address=address,
                    user=auth.current_user,
                )

                for item in items:
                    for req_item in req_items:
                        # if names match add item and quantity, once per
                        # req_item
                        if str(item.uuid) == req_item['id']:
                            order.add_item(item, req_item['quantity'])
                            break
                notify_new_order(address=order.delivery_address,
                                 user=order.user)
            except InsufficientAvailabilityException:
                abort(BAD_REQUEST)

        return generate_response(order.json(), CREATED)