Ejemplo n.º 1
0
def new_product():
    product = Product()
    product.name = request.form['name']
    db.session.add(product)
    db.session.commit()
    products = Product.query.all()
    return render_template('product.html', product=products)
Ejemplo n.º 2
0
def seed_db():
    """Sembrado en la base de datos"""
    db.session.add(Customer(names='nickmostacero'))
    db.session.add(Customer(names='ldramostacero'))
    db.session.add(Order(customer_id='1', date='01/09/09'))
    db.session.add(Order(customer_id='2', date='01/09/09'))
    db.session.add(Product(name='agua'))
    db.session.add(Product(name='gaseosa'))
    db.session.add(Item(order_id='1', product_id='1', quantity='20'))
    db.session.add(Item(order_id='2', product_id='2', quantity='21'))
    db.session.commit()
Ejemplo n.º 3
0
def seed_db():
    """Sembrado en la base de datos"""
    db.session.add(Customer(names='josvillegas'))
    db.session.add(Customer(names='toshivillegas'))
    db.session.add(Order(customer_id='1', date='01/09/09'))
    db.session.add(Order(customer_id='2', date='01/09/09'))
    db.session.add(Product(name='gaseosa'))
    db.session.add(Product(name='helado'))
    db.session.add(Item(order_id='1',product_id='1', quantity='20'))
    db.session.add(Item(order_id='2',product_id='2', quantity='21'))
    db.session.commit()
Ejemplo n.º 4
0
def seed_db():
    """Sembrado en la base de datos: Customers"""
    db.session.add(Customer(name='brandux'))
    db.session.add(Customer(name='toshi'))
    """Sembrando en base datos: Producto"""
    db.session.add(Product(name='Pan Integral'))
    db.session.add(Product(name='Palitos Union'))
    """Sembrando datos en base de datos: orders"""
    db.session.add(Order(customer_id=1, date=datetime.datetime.now()))
    """Sembrando datos en item"""
    db.session.add(Item(order_id=1, product_id=1, quantity=20))

    db.session.commit()
Ejemplo n.º 5
0
def add_product():
    post_data = request.get_json()
    response_object = {'estado': 'falló', 'mensaje': 'Carga inválida.'}
    if not post_data:
        return jsonify(response_object), 400
    nombre = post_data.get('nombre')
    cantidad = post_data.get('cantidad')
    precio = post_data.get('precio')
    descripcion = post_data.get('descripcion')
    categoria = post_data.get('categoria')
    try:
        product = Product.query.filter_by(nombre=nombre).first()
        if not product:
            db.session.add(
                Product(
                    nombre=nombre,
                    cantidad=cantidad,
                    precio=precio,
                    descripcion=descripcion,
                    categoria=categoria,
                ))
            db.session.commit()
            response_object['estado'] = 'satisfactorio'
            response_object['mensaje'] = f'{nombre} fue agregado!!!'
            return jsonify(response_object), 201
        else:
            response_object['estado'] = 'falló'
            response_object['mensaje'] = 'Lo siento, ese nombre ya existe.'
            return jsonify(response_object), 400
    except exc.IntegrityError as e:
        db.session.rollback()
        return jsonify(response_object), 400
Ejemplo n.º 6
0
def add_product(nombre, cantidad, precio, descripcion, categoria):
    product = Product(nombre=nombre,
                      cantidad=cantidad,
                      precio=precio,
                      descripcion=descripcion,
                      categoria=categoria)
    db.session.add(product)
    db.session.commit()
    return product
Ejemplo n.º 7
0
class PriceTestCase(TestCase):
    ''' Test suite for price model '''
    def setUp(self):
        User = get_user_model()

        self.shop = Shop(name='hexαδακτυλος',
                         address='Αριστοφανους 32',
                         coordinates=Point(22.18339, 39.89279))
        self.shop.save()

        self.product = Product(name='Αντρικιο',
                               description='Γυναικειο',
                               category='κουρεμα')
        self.product.save()

        userinfo = dict(username='******', password='******')
        self.user = User(**userinfo)
        self.user.save()
        grp, _ = Group.objects.get_or_create(name='Volunteer')
        self.user.groups.add(grp)

        self.entry = Price(shop=self.shop,
                           product=self.product,
                           user=self.user,
                           price=10.0)

    def test_can_add_price(self):
        ''' check if adding price works '''
        prev_count = Price.objects.count()
        self.entry.save()

        self.assertEqual(Price.objects.count(), prev_count + 1)

    def test_can_use_add_price(self):
        res = Price.add_price(shop=self.shop,
                              product=self.product,
                              user=self.user,
                              date_to=Price.parse_date('2018-10-10'),
                              date_from=Price.parse_date('2018-09-09'),
                              price=10.0)

        self.assertTrue(res)
        self.assertEqual(Price.objects.count(), 1)
Ejemplo n.º 8
0
    def setUp(self):
        # _
        User = get_user_model()

        self.factory = ApiRequestFactory()
        self.view = ParseUrlEncodedParametersMiddleware(PricesView.as_view())

        shop = Shop(id=10,
                    name='hexαδακτυλος',
                    address='Αριστοφανους 32',
                    coordinates=Point(22.18339, 39.89279))
        shop_away = Shop(id=11,
                         name='χεξadaktylos',
                         address='Devils horn',
                         coordinates=Point(10, 10))
        shop.save()
        shop_away.save()

        product = Product(id=20,
                          name='Αντρικιο',
                          description='Γυναικειο',
                          category='κουρεμα')
        product.save()

        userinfo = dict(username='******', password='******')
        self.user = User(**userinfo)
        self.user.save()

        grp, _ = Group.objects.get_or_create(name='Volunteer')
        self.user.groups.add(grp)

        # proto request
        self.request = dict(shopId=10,
                            productId=20,
                            dateFrom='2018-10-30',
                            dateTo='2018-11-30',
                            price=10.7)

        self.request_away = dict(shopId=11,
                                 productId=20,
                                 dateFrom='2018-10-30',
                                 dateTo='2018-12-15',
                                 price=31)
Ejemplo n.º 9
0
    def setUp(self):
        User = get_user_model()

        self.shop = Shop(name='hexαδακτυλος',
                         address='Αριστοφανους 32',
                         coordinates=Point(22.18339, 39.89279))
        self.shop.save()

        self.product = Product(name='Αντρικιο',
                               description='Γυναικειο',
                               category='κουρεμα')
        self.product.save()

        userinfo = dict(username='******', password='******')
        self.user = User(**userinfo)
        self.user.save()
        grp, _ = Group.objects.get_or_create(name='Volunteer')
        self.user.groups.add(grp)

        self.entry = Price(shop=self.shop,
                           product=self.product,
                           user=self.user,
                           price=10.0)
Ejemplo n.º 10
0
def add_receipt():
    post_data = request.get_json()

    error_response = {'status': 'fail', 'message': 'wrong json'}

    if not post_data:
        return jsonify(error_response), 400

    receipt = post_data.get('receipt')

    company_id = receipt.get('company_id')
    emission_date = receipt.get('emission_date')
    emission_place = receipt.get('emission_place')
    cnpj = receipt.get('cnpj')
    tax_value = receipt.get('tax_value')
    total_price = receipt.get('total_price')
    title = receipt.get('title')
    description = receipt.get('description')
    tag_id = receipt.get('tag_id')

    products = receipt.get('products')

    if products is None:
        return jsonify(error_response), 400

    try:
        receipt = Receipt(company_id, emission_date, emission_place, cnpj,
                          tax_value, total_price, title, description, tag_id)
        db.session.add(receipt)
        db.session.flush()

        for product in products:
            db.session.add(
                Product(receipt.id, product.get('quantity'),
                        product.get('unit_price')))

        db.session.commit()

        response = {
            'status': 'success',
            'data': {
                'message': 'Receipt was created!'
            }
        }
        return jsonify(response), 201

    except exc.IntegrityError:
        db.session.rollback()
        return jsonify(error_response), 400
Ejemplo n.º 11
0
def index():
    if request.method == 'POST':
        nombre = request.form['nombre']
        cantidad = int(request.form['cantidad'])
        precio = float(request.form['precio'])
        descripcion = request.form['descripcion']
        categoria = request.form['categoria']
        db.session.add(
            Product(nombre=nombre,
                    cantidad=cantidad,
                    precio=precio,
                    descripcion=descripcion,
                    categoria=categoria))
        db.session.commit()
    products = Product.query.all()
    return render_template('index.html', products=products)
Ejemplo n.º 12
0
def add_product():
    post_data = request.get_json()
    response_object = {'status': 'failed', 'message': 'Carga invalida.'}
    if not post_data:
        return jsonify(response_object), 400
    name = post_data.get('name')
    try:
        product = Product.query.filter_by(name=name).first()
        if not product:
            db.session.add(Product(name=name))
            db.session.commit()
            response_object['status'] = 'success'
            response_object['message'] = f'{name} ha sido agregado !'
            return jsonify(response_object), 201
        else:
            response_object['message'] = 'Lo siento. El usuario ya existe'
            return jsonify(response_object), 400
    except exc.IntegrityError:
        db.session.rollback()
        return jsonify(response_object), 400
Ejemplo n.º 13
0
def add_product(name):
    product = Product(name=name)
    db.session.add(product)
    db.session.commit()
    return product
Ejemplo n.º 14
0
    def setUp(self):
        User = get_user_model()

        self.factory = ApiRequestFactory()
        self.view = ParseUrlEncodedParametersMiddleware(PricesView.as_view())

        # create two shops
        self.shop = Shop(id=10,
                         name='hexαδακτυλος',
                         address='Αριστοφανους 32',
                         coordinates=Point(22.18339, 39.89279))
        self.shop_away = Shop(id=11,
                              name='χεξadaktylos',
                              address='Devils horn',
                              coordinates=Point(10, 10))
        self.shop.save()
        self.shop_away.save()

        # add a few tags
        shoptag = ShopTag('shoptag')
        shoptag.save()
        self.shop.tags.add(shoptag)
        self.shop.save()
        commontag_shop = ShopTag('commontag')
        commontag_shop.save()
        self.shop_away.tags.add(commontag_shop)
        self.shop_away.save()

        # create two products
        self.product = Product(id=20,
                               name='Αντρικιο',
                               description='Γυναικειο',
                               category='κουρεμα')
        self.product.save()
        self.product_2 = Product(id=21,
                                 name='λαδι μαλλιων',
                                 description='αντρικο',
                                 category='αναλωσιμο')
        self.product_2.save()

        # add tags
        producttag = ProductTag('producttag')
        producttag.save()
        self.product_2.tags.add(producttag)
        self.product_2.save()
        commontag_prod = ProductTag('commontag')
        commontag_prod.save()
        self.product.tags.add(commontag_prod)
        self.product.save()

        # create a user
        userinfo = dict(username='******', password='******')
        self.user = User(**userinfo)
        self.user.save()

        # add a few prices
        price_1 = Price(shop=self.shop,
                        product=self.product,
                        user=self.user,
                        date_from=Price.parse_date('2018-10-15'),
                        date_to=Price.parse_date('2018-10-20'),
                        price=10)
        price_1.save()

        price_2 = Price(shop=self.shop_away,
                        product=self.product,
                        user=self.user,
                        date_from=Price.parse_date('2018-10-16'),
                        date_to=Price.parse_date('2018-10-21'),
                        price=20)
        price_2.save()

        price_3 = Price(shop=self.shop,
                        product=self.product_2,
                        user=self.user,
                        date_from=Price.parse_date('2018-10-10'),
                        date_to=Price.parse_date('2018-10-23'),
                        price=20)
        price_3.save()
Ejemplo n.º 15
0
class PriceGetTestCase(TestCase):
    def setUp(self):
        User = get_user_model()

        self.factory = ApiRequestFactory()
        self.view = ParseUrlEncodedParametersMiddleware(PricesView.as_view())

        # create two shops
        self.shop = Shop(id=10,
                         name='hexαδακτυλος',
                         address='Αριστοφανους 32',
                         coordinates=Point(22.18339, 39.89279))
        self.shop_away = Shop(id=11,
                              name='χεξadaktylos',
                              address='Devils horn',
                              coordinates=Point(10, 10))
        self.shop.save()
        self.shop_away.save()

        # add a few tags
        shoptag = ShopTag('shoptag')
        shoptag.save()
        self.shop.tags.add(shoptag)
        self.shop.save()
        commontag_shop = ShopTag('commontag')
        commontag_shop.save()
        self.shop_away.tags.add(commontag_shop)
        self.shop_away.save()

        # create two products
        self.product = Product(id=20,
                               name='Αντρικιο',
                               description='Γυναικειο',
                               category='κουρεμα')
        self.product.save()
        self.product_2 = Product(id=21,
                                 name='λαδι μαλλιων',
                                 description='αντρικο',
                                 category='αναλωσιμο')
        self.product_2.save()

        # add tags
        producttag = ProductTag('producttag')
        producttag.save()
        self.product_2.tags.add(producttag)
        self.product_2.save()
        commontag_prod = ProductTag('commontag')
        commontag_prod.save()
        self.product.tags.add(commontag_prod)
        self.product.save()

        # create a user
        userinfo = dict(username='******', password='******')
        self.user = User(**userinfo)
        self.user.save()

        # add a few prices
        price_1 = Price(shop=self.shop,
                        product=self.product,
                        user=self.user,
                        date_from=Price.parse_date('2018-10-15'),
                        date_to=Price.parse_date('2018-10-20'),
                        price=10)
        price_1.save()

        price_2 = Price(shop=self.shop_away,
                        product=self.product,
                        user=self.user,
                        date_from=Price.parse_date('2018-10-16'),
                        date_to=Price.parse_date('2018-10-21'),
                        price=20)
        price_2.save()

        price_3 = Price(shop=self.shop,
                        product=self.product_2,
                        user=self.user,
                        date_from=Price.parse_date('2018-10-10'),
                        date_to=Price.parse_date('2018-10-23'),
                        price=20)
        price_3.save()

    def _request(self, params=None):
        if isinstance(params, dict):
            req = self.factory.get(settings.API_ROOT, params)
        elif isinstance(params, str):
            req = self.factory.get(settings.API_ROOT + params)
        else:
            req = self.factory.get(settings.API_ROOT)
        r = self.view(req)

        # print(r.content)

        return r

    def test_can_send_no_parameters(self):
        res = self._request()
        self.assertEqual(res.status_code, 200)

    def test_can_send_start(self):
        res = self._request({'start': 10})
        self.assertEqual(res.status_code, 200)

        self.assertEqual(json.loads(res.content)['start'], 10)

    def test_can_detect_false_start(self):
        res = self._request({'start': 'asd'})
        self.assertEqual(res.status_code, 400)

    def test_can_send_count(self):
        res = self._request({'count': 56})
        self.assertEqual(res.status_code, 200)
        self.assertEqual(json.loads(res.content)['count'], 56)

    def test_can_request_zero_count(self):
        res = self._request({'count': 0})
        self.assertEqual(res.status_code, 200)
        j = json.loads(res.content)
        self.assertEqual(j['count'], 0)
        self.assertEqual(len(j['prices']), 0)

    def test_can_detect_false_count(self):
        res = self._request({'count': 'asf'})
        self.assertEqual(res.status_code, 400)

    def test_can_send_start_n_count(self):
        res = self._request({'start': 10, 'count': 20})
        self.assertEqual(res.status_code, 200)
        self.assertEqual(json.loads(res.content)['start'], 10)
        self.assertEqual(json.loads(res.content)['count'], 20)

    def test_cannot_send_one_geo(self):
        res = self._request({'geoDist': 3})
        self.assertEqual(res.status_code, 400)

    def test_cannot_send_two_geos(self):
        res = self._request({'geoLat': 4.564, 'geoLng': 78.23546})
        self.assertEqual(res.status_code, 400)

    def test_can_send_all_geos(self):
        res = self._request({
            'geoDist': 3,
            'geoLat': 34.46354634,
            'geoLng': 46.346
        })
        self.assertEqual(res.status_code, 200)

    def test_can_detect_wrong_dist(self):
        res = self._request({
            'geoDist': 3.45,
            'geoLat': 34.46354634,
            'geoLng': 46.346
        })
        self.assertEqual(res.status_code, 400)

    def test_can_detect_wrong_lat(self):
        res = self._request({
            'geoDist': 3,
            'geoLat': 90.000001,
            'geoLng': 46.346
        })
        self.assertEqual(res.status_code, 400)

    def test_can_detect_wrong_lng(self):
        res = self._request({
            'geoDist': 3,
            'geoLat': 34.46354634,
            'geoLng': 180.000001
        })
        self.assertEqual(res.status_code, 400)

    def test_cannot_send_one_date(self):
        res = self._request({'dateFrom': '2018-12-23'})
        self.assertEqual(res.status_code, 400)

    def test_can_send_correct_dates(self):
        res = self._request({'dateFrom': '2018-12-21', 'dateTo': '2018-12-25'})
        self.assertEqual(res.status_code, 200)

    def test_can_send_same_dates(self):
        res = self._request({'dateFrom': '2018-12-21', 'dateTo': '2018-12-21'})
        self.assertEqual(res.status_code, 200)

    def test_cannot_send_not_correctly_formatted_dates(self):
        res = self._request({'dateFrom': '2018-2-21', 'dateTo': '2018-12-21'})
        self.assertEqual(res.status_code, 400)

    def test_cannot_send_out_of_order_dates(self):
        res = self._request({'dateFrom': '2018-12-27', 'dateTo': '2018-12-21'})
        self.assertEqual(res.status_code, 400)

    def test_can_send_lists(self):
        res = self._request('?shops=12&shops=123')
        self.assertEqual(res.status_code, 200)

    def test_can_send_sort(self):
        res = self._request('?sort=price|ASC&sort=date|ASC')
        self.assertEqual(res.status_code, 200)

    def test_cannot_send_bollocks_sort(self):
        res = self._request('?sort=price|ASC&sort=size|ASC')
        self.assertEqual(res.status_code, 400)

    def test_cannot_send_duplicate_sort(self):
        res = self._request('?sort=price|ASC&sort=date|DESC&sort=price|ASC')
        self.assertEqual(res.status_code, 400)

    def test_cannot_send_conflicting_sort(self):
        res = self._request('?sort=price|ASC&sort=price|DESC')
        self.assertEqual(res.status_code, 400)

    def test_can_send_complex_query(self):
        res = self._request(
            '?start=0&count=50&geoDist=3&geoLng=37.977328&geoLat=23.727811'
            '&dateFrom=2018-12-21&dateTo=2018-12-25&shops=123&shops=11&shops=89'
            '&products=1&products=23&products=233&tags=laptop&sort=price|ASC')
        self.assertEqual(res.status_code, 200)

    # Below this, some things are hardcoded, but who cares

    def test_sort_by_price_works(self):
        res = self._request(
            '?sort=price|ASC&dateFrom=2018-10-18&dateTo=2018-10-18')

        j = json.loads(res.content.decode())
        self.assertEqual(j['prices'][0]['price'], 10)
        self.assertEqual(j['prices'][2]['price'], 20)

        res = self._request(
            '?sort=price|ASC&dateFrom=2018-10-18&dateTo=2018-10-18')
        j = json.loads(res.content.decode())
        self.assertEqual(j['prices'][2]['price'], 20)
        self.assertEqual(j['prices'][0]['price'], 10)

    def test_sort_by_dist_works(self):
        res = self._request(
            '?sort=geoDist|DESC&geoLng=38&geoLat=27&geoDist=10000&dateFrom=2018-10-18&dateTo=2018-10-18'
        )
        j = json.loads(res.content.decode())
        self.assertGreaterEqual(j['prices'][0]['shopDist'],
                                j['prices'][2]['shopDist'])

        res = self._request(
            '?sort=geoDist|ASC&geoLng=38&geoLat=27&geoDist=10000&dateFrom=2018-10-18&dateTo=2018-10-18'
        )
        j = json.loads(res.content.decode())
        self.assertGreaterEqual(j['prices'][2]['shopDist'],
                                j['prices'][0]['shopDist'])

        #  print(json.dumps(j, indent=4, ensure_ascii=False))

    def test_sort_by_date_works(self):
        res = self._request(
            '?sort=date|DESC&dateFrom=2018-10-18&dateTo=2018-10-18')
        j = json.loads(res.content.decode())
        self.assertGreaterEqual(j['prices'][0]['date'], j['prices'][2]['date'])

        res = self._request(
            '?sort=date|ASC&dateFrom=2018-10-18&dateTo=2018-10-18')
        j = json.loads(res.content.decode())
        self.assertGreaterEqual(j['prices'][2]['date'], j['prices'][0]['date'])

    def test_sort_with_secondary_works(self):
        res = self._request(
            '?dateFrom=2018-10-18&dateTo=2018-10-18&geoLng=38&geoLat=27&geoDist=10000&sort=geoDist|DESC&sort=price|ASC'
        )
        j = json.loads(res.content.decode())

        # check (price, shop_id) pairs
        self.assertEqual((j['prices'][0]['price'], j['prices'][0]['shopId']),
                         (20, 11))
        self.assertEqual((j['prices'][1]['price'], j['prices'][1]['shopId']),
                         (10, 10))
        self.assertEqual((j['prices'][2]['price'], j['prices'][2]['shopId']),
                         (20, 10))

        res = self._request(
            '?dateFrom=2018-10-18&dateTo=2018-10-18&geoLng=38&geoLat=27&geoDist=10000&sort=geoDist|DESC&sort=price|DESC'
        )
        j = json.loads(res.content.decode())

        # check (price, shop_id) pairs
        self.assertEqual((j['prices'][0]['price'], j['prices'][0]['shopId']),
                         (20, 11))
        self.assertEqual((j['prices'][1]['price'], j['prices'][1]['shopId']),
                         (20, 10))
        self.assertEqual((j['prices'][2]['price'], j['prices'][2]['shopId']),
                         (10, 10))

    def test_checking_for_product_and_shop_ids_works(self):
        res = self._request('?dateFrom=2015-01-01&dateTo=2030-01-01&shops=10')
        j = json.loads(res.content.decode())
        for p in j['prices']:
            self.assertEqual(p['shopId'], 10)

        res = self._request(
            '?dateFrom=2015-01-01&dateTo=2030-01-01&shops=10&shops=11')
        j = json.loads(res.content.decode())
        for p in j['prices']:
            self.assertIn(p['shopId'], [10, 11])

        res = self._request(
            '?dateFrom=2015-01-01&dateTo=2030-01-01&products=20')
        j = json.loads(res.content.decode())
        for p in j['prices']:
            self.assertEqual(p['productId'], 20)

        res = self._request(
            '?dateFrom=2015-01-01&dateTo=2030-01-01&products=20&products=21')
        j = json.loads(res.content.decode())
        for p in j['prices']:
            self.assertIn(p['productId'], [20, 21])

        res = self._request(
            '?dateFrom=2015-01-01&dateTo=2030-01-01&products=20&shops=11')
        j = json.loads(res.content.decode())
        for p in j['prices']:
            self.assertEqual(p['productId'], 20)
            self.assertEqual(p['shopId'], 11)

    def test_checking_date_works(self):
        # check that only `price_3` is returned
        res = self._request('?dateFrom=2015-01-01&dateTo=2018-10-10')
        j = json.loads(res.content.decode())

        p = j['prices'][0]
        self.assertEqual(j['total'], 1)
        self.assertEqual((p['price'], p['shopId'], p['productId']),
                         (20, 10, 21))

        # check that `price_3` and `price_2` are returned, in that order
        # (because we sort by date ascending, and 2018-10-10 < 2018-10-16)
        res = self._request(
            '?dateFrom=2018-10-18&dateTo=2018-10-19&sort=date|ASC')
        j = json.loads(res.content.decode())

        # print(j)
        prev = j['prices'][0]['date']
        for p in j['prices']:
            self.assertGreaterEqual(p['date'], prev)
            prev = p['date']

    def test_checking_distance_works(self):
        for x in range(10):
            distance = x * 1000

            res = self._request(
                f'?dateFrom=2015-01-01&dateTo=2028-10-10&geoLng=38&geoLat=27&geoDist={distance}'
            )
            j = json.loads(res.content.decode())
            for p in j['prices']:
                self.assertLessEqual(p['shopDist'], distance)

    def test_checking_tags_works(self):

        # check with tag of product
        res = self._request(
            f'?dateFrom=2018-10-18&dateTo=2018-10-18&tags=producttag')
        j = json.loads(res.content.decode())

        # assert all returned prices have that product/shop tag
        shop_ids = []
        product_ids = []
        for p in j['prices']:
            shop_ids.append(p['shopId'])
            product_ids.append(p['productId'])
            self.assertIn('producttag', p['shopTags'] + p['productTags'])

        # also that all products and shops with those tags are in the results
        self.assertEqual(j['total'], 1)
        self.assertIn(21, product_ids)

        # check with tag of shop
        res = self._request(
            f'?dateFrom=2018-10-18&dateTo=2018-10-18&tags=shoptag')
        j = json.loads(res.content.decode())

        shop_ids = []
        product_ids = []
        for p in j['prices']:
            shop_ids.append(p['shopId'])
            product_ids.append(p['productId'])
            self.assertIn('shoptag', p['shopTags'] + p['productTags'])

        # also that all products and shops with those tags are in the results
        self.assertEqual(j['total'], 2)
        self.assertIn(10, shop_ids)

        # check with shared tag
        res = self._request(
            f'?dateFrom=2018-10-18&dateTo=2018-10-18&tags=commontag')
        j = json.loads(res.content.decode())

        shop_ids = []
        product_ids = []
        for p in j['prices']:
            shop_ids.append(p['shopId'])
            product_ids.append(p['productId'])
            self.assertIn('commontag', p['shopTags'] + p['productTags'])

        # also that all products and shops with those tags are in the results
        self.assertEqual(j['total'], 2)
        self.assertIn(10, shop_ids)
        self.assertIn(20, product_ids)
Ejemplo n.º 16
0
 def build(self):
     product = Product(self._stock_pcs, self._price, self._shop_id,
                       self._vip)
     product._id = self._id
     product._orders = self._orders
     return product
Ejemplo n.º 17
0
    def handle(self, *args, **options):
        fake = Faker('el_GR')
        lorem = fake.provider('faker.providers.lorem')
        name_provider = fake.provider('faker.providers.person')
        uncommon_words = lorem.word_list[2 * len(lorem.common_words):]
        company_names = uncommon_words + name_provider.last_names

        # categories
        categories = fake.words(NUM_CATEGORIES, ext_word_list=uncommon_words)

        # shop and product tags
        product_tags = fake.words(NUM_TAGS,
                                  ext_word_list=uncommon_words,
                                  unique=True)
        product_tags = [ProductTag(tag=x) for x in product_tags]
        ProductTag.objects.bulk_create(product_tags)
        product_tags = ProductTag.objects.all()

        shop_tags = fake.words(NUM_TAGS,
                               ext_word_list=uncommon_words,
                               unique=True)
        shop_tags = [ShopTag(tag=x) for x in shop_tags]
        ShopTag.objects.bulk_create(shop_tags)
        shop_tags = ShopTag.objects.all()

        # shops
        shops = []
        shop_names = fake.words(options['count'], ext_word_list=company_names)
        for name in shop_names:
            s = Shop(name=name.capitalize(),
                     address=fake.address(),
                     coordinates=Point(float(fake.local_longitude()),
                                       float(fake.local_latitude())))
            s.save()
            shops.append(s)

            for t in pick_max_count(shop_tags, 2):
                s.tags.add(t)

        # products
        products = []
        product_names = fake.words(options['count'],
                                   ext_word_list=uncommon_words)
        for name in product_names:
            p = Product(name=name.capitalize(),
                        description=fake.text(max_nb_chars=200,
                                              ext_word_list=None),
                        category=random.choice(categories))
            p.save()
            products.append(p)

            for t in pick_max_count(product_tags, 2):
                p.tags.add(t)

        # user is asoures
        User = get_user_model()
        asoures_user = User.objects.get(username='******')

        # for each shop, add prices for at most `products/3` products

        prices = []
        for s in shops:
            prods = pick_max_count(products, options['count'] // 3)
            for prod in prods:
                date_from = fake.date_between('-30d', 'today')
                date_to = fake.date_between('today', '+30d')
                p = Price(
                    shop=s,
                    product=prod,
                    user=asoures_user,
                    price=random.randint(5, 60),
                    date_from=date_from,
                    date_to=date_to,
                )
                prices.append(p)

        Price.objects.bulk_create(prices)