Beispiel #1
0
 def save_item(self, item_dict):
     try:
         item = Item.create(**item_dict)
         item = item.to_unicode()
     except peewee.IntegrityError as e:
         print type(e), e
         item = self.query_db(item_dict['name'])
     return item
Beispiel #2
0
 def save_item(self, item_dict):
     # if no example, do not save to db, but if added to xml, save it to db.
     if item_dict['example']:
         try:
             item = Item.create(**item_dict)
         except peewee.IntegrityError as e:
             print type(e), e
             item = self.query_db(item_dict['name'])
     else:
         item = Item(**item_dict)
     return item
Beispiel #3
0
    def test_modify_item__failure_field_wrong_type(self):
        item = Item.create(uuid=uuid.uuid4(),
                           name='Item one',
                           price=5,
                           description='Description one',
                           category='Category one')

        modified_content = {
            'name': 'Item one',
            'price': 'Ten',
            'description': 'Description two',
            'category': 'Category two'
        }
        resp = self.app.put('/item/{}'.format(item.uuid),
                            data=modified_content)
        assert resp.status_code == BAD_REQUEST

        item_from_db = Item.get(uuid=item.uuid).json()
        assert item.json() == item_from_db
def item_creator(num_item):
    LIST_CATEGORIES = [
        'scarpe', 'accessori', 'abbigliamento uomo', 'abbigliamento donna'
    ]
    for i in range(num_item):
        item_id = fake.uuid4()
        item_name = fake.sentence(nb_words=3, variable_nb_words=True)
        item_price = fake.pyfloat(left_digits=2, right_digits=2, positive=True)
        item_category = random.choice(LIST_CATEGORIES)
        item = Item.create(
            uuid=item_id,
            name=item_name,
            price=item_price,
            description=fake.paragraph(nb_sentences=3,
                                       variable_nb_sentences=True),
            availability=random.randint(35, 60),
            category=item_category,
        )
        picture_creator(num_item, i, item)
Beispiel #5
0
    def cria(dados):
        """

        :type dados: list
        """
        try:
            pe = Personagem.get(Personagem.usuario == dados[0])
        except:
            try:
                nome = dados[1]
                usuario = dados[0]
                classe = dados[2]
            except:
                return "Erro, tente : /criapersonagem Nome Classe"

            forca = randint(5, 20)
            inteligencia = randint(5, 20)
            resiliencia = randint(10, 20)
            destreza = randint(5, 20)
            agilidade = randint(5, 20)
            vida = resiliencia * 10
            mao1 = Item.create(nome="graveto", ataque=5, defesa=0)
            mao2 = Item.create(nome="tabua", ataque=0, defesa=5)
            peito = Item.create(nome="Camisa_rasgada", ataque=0, defesa=2)
            perna = Item.create(nome="tanga", ataque=0, defesa=2)
            cabeca = Item.create(nome="cabeça", ataque=0, defesa=0)
            sapato = Item.create(nome="sapato", ataque=0, defesa=1)

            try:
                personagem = Personagem.create(vida=vida,
                                               vidamax=vida,
                                               usuario=usuario,
                                               nome=nome,
                                               classe=classe,
                                               cabeca=cabeca,
                                               bra_dir=mao1,
                                               bra_esq=mao2,
                                               peito=peito,
                                               perna=perna,
                                               sapato=sapato,
                                               forca=forca,
                                               inteligencia=inteligencia,
                                               resiliencia=resiliencia,
                                               destreza=destreza,
                                               agilidade=agilidade)
            except:
                return "Erro ao criar personagem"
            return "criado: %s classe: %s " % (personagem.nome,
                                               personagem.classe)
        return "Você possui já um personagem: %s " % pe.nome
Beispiel #6
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, required=True)
        parser.add_argument('price', type=int, required=True)
        parser.add_argument('description', type=str, required=True)
        parser.add_argument('category', type=str, required=True)
        args = parser.parse_args(strict=True)
        try:
            utils.non_empty_str(args['name'], 'name')
        except ValueError:
            return None, BAD_REQUEST

        obj = Item.create(
            uuid=uuid.uuid4(),
            name=args["name"],
            price=args["price"],
            description=args["description"],
            category=args["category"]
        )

        return obj.json(), CREATED
Beispiel #7
0
    def test_delete_order__fail_not_own_order(self):
        user = add_user('*****@*****.**', TEST_USER_PSW)
        addr_A = add_address(user=user)

        item1 = Item.create(
            uuid='429994bf-784e-47cc-a823-e0c394b823e8',
            name='mario',
            price=20.20,
            description='svariati mariii',
            availability=2,
            category='scarpe',
        )
        order1 = Order.create(delivery_address=addr_A, user=user)
        order1.add_item(item1, 2)

        user_B = add_user('*****@*****.**', TEST_USER_PSW)
        path = 'orders/{}'.format(order1.uuid)
        resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'DELETE',
                              user_B.email, TEST_USER_PSW, None, None)

        assert resp.status_code == UNAUTHORIZED
Beispiel #8
0
    def test_update_order__failure_availability(self, mocker):
        mocker.patch('views.orders.database', new=self.TEST_DB)

        user = add_user('*****@*****.**',
                        TEST_USER_PSW,
                        id='90c3e1c1-b51c-4224-b69d-17f84f6a8dfc')
        addr = add_address(user=user,
                           id='8f3b518e-9c17-4103-9a47-b274740726e7')
        item = Item.create(
            uuid='429994bf-784e-47cc-a823-e0c394b823e8',
            name='mario',
            price=20.20,
            description='svariati mariii',
            availability=4,
            category='scarpe',
        )
        order = Order.create(
            delivery_address=addr,
            user=user,
        ).add_item(item, 2)

        update_order = {
            'relationships': {
                'items': [{
                    'id': '429994bf-784e-47cc-a823-e0c394b823e8',
                    'type': 'item',
                    'quantity': 5
                }]
            }
        }
        post_data = format_jsonapi_request('order', update_order)
        path = 'orders/{}'.format(order.uuid)
        resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'PATCH',
                              '*****@*****.**', TEST_USER_PSW,
                              'application/json', json.dumps(post_data))

        assert resp.status_code == BAD_REQUEST
        assert OrderItem.select().count() == 1
        assert OrderItem.get() == order.order_items[0]
        assert order.order_items[0].quantity == 2
Beispiel #9
0
    def test_patch_allitems__success(self):
        item = Item.create(**TEST_ITEM)
        post_data = format_jsonapi_request('item', {
            'name': 'new-name',
            'price': 40.20,
            'description': 'new-description',
            'availability': 2,
            'category': 'new-category'
        })
        resp = self.app.patch('/items/{uuid}'.format(uuid=item.uuid),
                              data=json.dumps(post_data),
                              content_type='application/json')

        assert resp.status_code == client.OK
        expected_result = EXPECTED_RESULTS['patch_allitems__success']
        assert_valid_response(resp.data, expected_result)

        # validate patch functionality checking for updated values
        item = Item.get()
        assert item.name == 'new-name'
        assert float(item.price) == 40.20
        assert item.description == 'new-description'
def write(df):
    items_added = 0
    transactions_added = 0
    transaction_record_added = 0
    item_set = set()
    transaction_set = set()
    transaction_record_set = set()

    for index, row in df.iterrows():
        item_set.add(extract_item(row))
        transaction_set.add(extract_transaction(index, row))
        transaction_record_set.add(extract_transaction_item(index, row))

    for item in item_set:
        is_added = Item.create(**dict(item))
        if is_added:
            items_added += 1

    for transaction in transaction_set:
        is_added = Transaction.create(**dict(transaction))
        if is_added:
            transactions_added += 1

    for record in transaction_record_set:
        record = dict(record)
        item = Item.get(name=record['item_name'])
        if item is None:
            continue
        record['item_id'] = item.id
        del record['item_name']
        is_added = Transaction_Item.create(**record)
        if is_added:
            transaction_record_added += 1
    print('\rItems added: {}\nTransactions added: {}\nRecords added: {}\n'.
          format(items_added, transactions_added, transaction_record_added),
          flush=True)
Beispiel #11
0
    def post(self):
        if not g.current_user.superuser:
            return None, UNAUTHORIZED

        jsondata = request.get_json()

        try:
            utils.non_empty_str(jsondata['name'], 'name')
        except ValueError:
            return None, BAD_REQUEST

        try:
            Item.verify_json(jsondata)
        except ValidationError as ver_json_error:
            return ver_json_error.message, BAD_REQUEST

        obj = Item.create(uuid=uuid.uuid4(),
                          name=jsondata['name'],
                          price=jsondata['price'],
                          description=jsondata['description'],
                          category=jsondata['category'],
                          availability=jsondata['availability'])

        return obj.json(), CREATED
Beispiel #12
0
    def test_modify_item__failure_missing_argument(self):
        user = self.create_user()

        item = Item.create(uuid=uuid.uuid4(),
                           name='Item one',
                           price=5,
                           description='Description one',
                           category='Category one',
                           availability=11)

        modified_content = {
            'name': 'Item two',
            'price': 10,
            'description': 'Description two'
        }

        resp = self.open_with_auth('items/{}'.format(item.uuid),
                                   'put',
                                   user.email,
                                   'p4ssw0rd',
                                   data=modified_content)
        item_from_db = Item.get(Item.uuid == item.uuid).json()
        assert item.json() == item_from_db
        assert resp.status_code == BAD_REQUEST
 def create_item(self, body):
     """Create item model with fields from body"""
     item = Item.create(**body)
     return item # Return model
Beispiel #14
0
            return

        log.debug("%s - %d entries in %fs" %
                  (netloc, len(entries), time.time() - now))
        now = time.time()

        records = 0
        now = time.time()
        ix = open_dir(settings.index)
        writer = AsyncWriter(ix)

        for entry in entries:
            try:
                item = Item.get(guid=entry['guid'])
            except Item.DoesNotExist:
                item = Item.create(**entry)
            records += 1

            if len(entry['html']):
                soup = BeautifulSoup(entry['html'], settings.fetcher.parser)
                plaintext = ''.join(soup.find_all(text=True))
                writer.add_document(id=item.id,
                                    guid=unicode(item.guid),
                                    title=entry['title'],
                                    text=plaintext,
                                    when=datetime.datetime.utcfromtimestamp(
                                        item.when))

                hrefs = get_link_references(soup)
            else:
                hrefs = []
 def save(self, item_dict):
     if item_dict['example']:
         self.item = Item.create(**item_dict)
     else:
         self.item = Item(**item_dict)
Beispiel #16
0
    def test_get_item__success(self):
        item = Item.create(**TEST_ITEM)
        resp = self.app.get('/items/{item_uuid}'.format(item_uuid=item.uuid))

        assert resp.status_code == client.OK
        assert_valid_response(resp.data, EXPECTED_RESULTS['get_item__success'])
Beispiel #17
0
def create_items():
    Item.create(title='House', descr='sdfsdfsdf')
    Item.create(title='HoUSE', descr='dsfgdfgghhgf')
    Item.create(title='house', descr='ds234rfdghhgf')
    Item.create(title='дом', descr='ds234rfdghhgf')
    Item.create(title='ДОМ', descr='ds2ываываdghhgf')
    Item.create(title='Дом', descr='ds2ываываdghhgf')
Beispiel #18
0
    def test_order_add_remove_item(self):
        """
        Test add_item and remove_item function from Order and OrderItem
        models.
        """
        user = add_user(None, TEST_USER_PSW)
        addr = add_address(user=user)

        item1 = Item.create(
            uuid=uuid4(),
            name='Item',
            description='Item description',
            price=10,
            availability=2,
            category='scarpe',
        )
        item2 = Item.create(
            uuid=uuid4(),
            name='Item 2',
            description='Item 2 description',
            price=15,
            availability=2,
            category='accessori',
        )
        item3 = Item.create(
            uuid=uuid4(),
            name='Item 3',
            description='Item 3 description',
            price=15,
            availability=2,
            category='scarpe',
        )
        order = Order.create(delivery_address=addr, user=user)
        order.add_item(item1, 2).add_item(item2, 2)

        assert len(order.order_items) == 2
        assert OrderItem.select().count() == 2
        assert count_order_items(order) == 4

        # test removing one of two item1
        order.update_items({item1: 1})
        assert len(order.order_items) == 2
        assert count_order_items(order) == 3

        # remove more item1 than existing in order
        with pytest.raises(WrongQuantity):
            order.update_items({item1: -1})
        assert len(order.order_items) == 2
        assert OrderItem.select().count() == 2
        assert count_order_items(order) == 3

        # Check that the total price is correctly updated
        assert order.total_price == item1.price + item2.price * 2

        # remove non existing item3 from order
        with pytest.raises(WrongQuantity):
            order.update_items({item3: 0})
        assert count_order_items(order) == 3
        assert len(order.order_items) == 2

        order.empty_order()
        assert len(order.order_items) == 0
        assert OrderItem.select().count() == 0
Beispiel #19
0
 def create(self, schema_in: schema = None):
     return Item.create(**schema_in.dict())
Beispiel #20
0
 def test_delete_item__success(self):
     item = Item.create(**TEST_ITEM2)
     resp = self.app.delete('/items/{item_uuid}'.format(item_uuid=item.uuid))
     assert resp.status_code == client.NO_CONTENT
     assert not Item.select().exists()
Beispiel #21
0
    def test_update_order__success(self):
        item1 = Item.create(
            uuid='429994bf-784e-47cc-a823-e0c394b823e8',
            name='mario',
            price=20.20,
            description='svariati mariii',
            availability=5,
            category='scarpe',
        )
        item2 = Item.create(
            uuid='577ad826-a79d-41e9-a5b2-7955bcf03499',
            name='GINO',
            price=30.20,
            description='svariati GINIIIII',
            availability=2,
            category='accessori',
        )

        user = add_user('*****@*****.**',
                        TEST_USER_PSW,
                        id='90c3e1c1-b51c-4224-b69d-17f84f6a8dfc')
        addr = add_address(user=user,
                           id='8f3b518e-9c17-4103-9a47-b274740726e7')
        add_address(user=user, id='284ac7f6-40c2-4da6-b722-5d8cd248b1cc')
        order = Order.create(
            delivery_address=addr,
            user=user,
            uuid='9d899e2d-66e8-4728-aee5-fee733807b4a').add_item(
                item1, 2).add_item(item2)

        post_data = {
            'relationships': {
                'items': [{
                    'id': '429994bf-784e-47cc-a823-e0c394b823e8',
                    'type': 'item',
                    'quantity': 5
                }, {
                    'id': '577ad826-a79d-41e9-a5b2-7955bcf03499',
                    'type': 'item',
                    'quantity': 1
                }],
                'delivery_address': {
                    'type': 'address',
                    'id': '284ac7f6-40c2-4da6-b722-5d8cd248b1cc'
                },
                'user': {
                    'type': 'user',
                    'id': '90c3e1c1-b51c-4224-b69d-17f84f6a8dfc'
                }
            }
        }
        post_data = format_jsonapi_request('order', post_data)
        path = 'orders/{}'.format(order.uuid)
        resp = open_with_auth(self.app, API_ENDPOINT.format(path), 'PATCH',
                              user.email, TEST_USER_PSW, 'application/json',
                              json.dumps(post_data))

        expected_result = EXPECTED_RESULTS['update_order__success']

        assert resp.status_code == OK
        assert_valid_response(resp.data, expected_result)
Beispiel #22
0
def save(item_dict):
    item = Item.create(**item_dict)
    return item
 def test_get_item_pictures__empty(self):
     item = Item.create(**TEST_ITEM)
     resp = self.app.get(
         '/items/{item_uuid}/pictures/'.format(item_uuid=item.uuid))
     pictures = json.loads(resp.data)
     assert not pictures
Beispiel #24
0
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()
Beispiel #25
0
            return

        log.debug("%s - %d entries in %fs" % (netloc, len(entries),time.time()-now))
        now = time.time()
        
        
        records = 0
        now = time.time()
        ix = open_dir(settings.index)
        writer = AsyncWriter(ix)

        for entry in entries:
            try:
                item = Item.get(guid = entry['guid'])
            except Item.DoesNotExist:
                item = Item.create(**entry)
            records += 1

            if len(entry['html']):
                soup = BeautifulSoup(entry['html'], settings.fetcher.parser)
                plaintext = ''.join(soup.find_all(text=True))
                writer.add_document(
                    id = item.id,
                    guid = unicode(item.guid),
                    title = entry['title'],
                    text = plaintext,
                    when = datetime.datetime.utcfromtimestamp(item.when)
                )

                hrefs = get_link_references(soup)
            else:
 def save(self, item_dict):
     if item_dict['example']:
         self.item = Item.create(**item_dict)
     else:
         self.item = Item(**item_dict)