Example #1
0
    def setUp(self):
        user = {
            "username": "******",
            "password1": "P4sswordVeryS€cure@",
            "password2": "P4sswordVeryS€cure@",
            "email": "*****@*****.**"
        }
        self.client.post('/consumer/signup', data=user)
        self.token = self.client.post('/user/login',
                                      data={
                                          'email': '*****@*****.**',
                                          'password': '******'
                                      }).json()['key']
        self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)

        cat = Category(name='category')
        cat.save()
        cat = Category(name='category2')
        cat.save()
        p = Product(name='product')
        p.save()
        p.categories.set([Category.objects.all()[0]])
        p.save()
        store = Store(name='store', pnt=GEOSGeometry('POINT(0 0)', srid=SRID))
        store.save()
Example #2
0
    def save_categories(self):
        # Seed Categories
        files = listdir(categories_dir)
        count = 0

        for i in files:
            file_path = categories_dir + "/" + i
            try:
                file_name = path.splitext(i)[0]

                with open(file_path, "rb") as f:
                    img = ImageFile(f)
                    obj = Category(title=file_name,
                                   slug=file_name.replace("_", " "))
                    obj.image.save(i, img, save=True)
            except Exception as e:
                print("Error: \n" + str(e))
            else:
                count += 1

        if count > 0:
            print(
                colored(
                    "Successfully added " + str(count) +
                    " Categories to the database...", "green"))
        else:
            print(colored("No Categories were added to the database...",
                          "red"))
Example #3
0
    def test_order_item_to_string_method(self):
        test_category = Category(name="Kettlebells")
        test_category.save()
        test_discount = Discount(name="30%", rate=0.7)
        test_discount.save()
        test_manufacurer = Manufacturer(name="Great Sports")
        test_manufacurer.save()
        test_product = Product(name="Test", description="A description",
                               image_url="", category=test_category,
                               manufacturer=test_manufacurer,
                               prize=100,
                               discount_rate=test_discount,
                               units_sold=1)

        test_user = User(username="******")
        test_user.save()
        date = datetime.datetime.now()

        test_order = Order(date=date,
                           user=test_user,
                           amount_paid=100,
                           shipping_address="Street",
                           customer_name="Name",
                           customer_email="*****@*****.**")
        test_order.save()

        test_order_item = OrderItem(product=test_product,
                                    order=test_order,
                                    quantity=1)

        self.assertEquals(test_order_item.__str__(), "Test")
Example #4
0
    def handle(self, *args, **options):
        number_categories = options['c']
        number_products = options['p']

        api = OpenFoodFactsAPI(number_categories, number_products)

        # Adding categories
        print(f"Adding {number_categories} categories", end="")
        for api_category in api.categories:
            category = Category(name=api_category)
            category.save()
            print(".", end="")

        # Adding products
        print(
            f"\nAdding {number_categories * number_products} products, it can take a little while..."
        )

        for api_product in api.get_products():
            api_product['category'] = Category.objects.get(
                name=api_product['category'])
            product = Product(**api_product)

            # Taking care of duplicates if any (sanity check even with a set() in api.get_products())
            try:
                product.save()
            except IntegrityError:  # Unicity constraint
                continue

        print(
            f"\nSuccessfully added {len(Product.objects.all())} products and "
            f"{len(Category.objects.all())} categories. Differences may be duplicates."
        )
Example #5
0
    def handle(self, *args, **options):
        file_path = options.get('file')

        if not file_path:
            raise CommandError('File not provided.')

        if not file_path.endswith('.json'):
            raise CommandError('Only .json file supported.')

        file_path = os.path.join('data', file_path)
        try:
            with open(file_path) as import_file:
                categories = json.load(import_file)
        except FileNotFoundError as e:
            raise CommandError('File at %s was not found' %
                               os.path.join('data', file_path))

        for category in categories:
            # print(product['user_id'])
            # user = AuthUserModel.objects.filter(id=product['user_id']).first()
            # print(user.first_name)
            db_category = Category(
                name=category['name'],
                image=category['image'],
            )
            db_category.save()
Example #6
0
    def setUpTestData(cls):
        """Method called to prepare the test fixture."""
        cls.category = Category(
            id_category="1a",
            name="category_test",
            products=1,
            visible=True
        )
        cls.category.save()

        cls.User = get_user_model()
        cls.user = cls.User.objects.create_user(
            username='******',
            email='*****@*****.**',
            password='******'
        )

        nb_products = 11

        for id_product in range(nb_products):
            cls.product = Product(
                id_product="key%s" % id_product,
                product_name_fr="test_%s" % id_product,
                nutriscore_score=0,
                nutriscore_grade='A'
            )
            cls.product.save()
            cls.product.categories.add(cls.category)
            cls.product.favorites.add(cls.user)

        cls.client_login = Client(HTTP_REFERER=reverse('home'))
        cls.logged_in = cls.client_login.login(
            username='******', password='******')
def create_default_products(apps, schema_editor):
    with open('products/data/products.json', 'r') as file:
        context = json.load(file)

    categories = []

    for product in context['products']:
        if product['category'] not in categories:
            categories.append(product['category'])
            query = Category.objects.filter(title=product['category']).count()
            if not query:
                new_category = Category(title=product['category'])
                new_category.save()
        new_product = Product(
            name=product['name'],
            title=product['title'],
            alt=product['alt'],
            description=product['description'],
            characteristics=product['characteristics'],
            details=product['details'],
            image=Image.objects.get(title='default'),
            url_key=product['url_key'],
            category=Category.objects.get(title=product['category']),
        )
        new_product.save()
Example #8
0
    def setUp(self):
        """Method called to prepare the test fixture."""

        self.options = ChromeOptions()
        # self.options.add_experimental_option("excludeSwitches",
        #                                      ["enable-logging"])
        self.options.add_argument('--headless')
        self.options.add_argument('--disable-gpu')
        self.options.add_argument('--remote-debugging-port=9222')
        self.options.add_argument('--window-size=1920x1080')
        self.browser = Chrome(chrome_options=self.options)

        User = get_user_model()
        self.user = User.objects.create_user(username='******',
                                             email='*****@*****.**',
                                             password='******')

        self.category = Category(id_category="1à",
                                 name="category_test",
                                 products=1,
                                 visible=True)
        self.category.save()

        for id_product in range(7):
            self.product = Product(id_product="key%s" % id_product,
                                   product_name_fr="test_%s" % id_product,
                                   nutriscore_score=0,
                                   nutriscore_grade='A',
                                   brands='brand_test')
            self.product.save()
            self.product.categories.add(self.category)
Example #9
0
 def setUp(self):
     category = Category(name='maria_sharia')
     category.save()
     product = Product(name='name',
                       description='description',
                       offer='99.00')
     product.save()
Example #10
0
    def setUp(self):
        # Create the model instances required for the relationship
        self.new_difficulty = Difficulty(name="Very Tough")
        self.new_difficulty.save()

        self.new_category = Category(name="Solid Cakes")
        self.new_category.save()
        # Create the raw data for testing
        raw_data = {
            "name": "Cherry Cake",
            "price": 3000,
            "average_class_size": 25,
            "difficulty_level": self.new_difficulty,
            "description": "Good Stuff",
        }
        product_raw_data = {
            "name": "Fairy Cake",
            "price": 3000,
            "category": self.new_category,
            "description": "Great Cake!",
            "sizes": "S"
        }
        #Pass the dictionary as named parameters to a function call
        self.new_lesson = Lesson(**raw_data)
        self.new_lesson.save()

        self.new_product = Product(**product_raw_data)
        self.new_product.save()

        self.user = User.objects.create_user(username='******',
                                             password='******')
        self.client.login(username='******', password='******')
Example #11
0
    def handle(self, *args, **options):

        print("**************************************************")
        print("STARTING DATABASE_UPDATE - {}".format(datetime.now()))
        print("**************************************************")
        for nutriment in settings.NUTRIMENTS:
            if not Nutriment.objects.filter(name__iexact=nutriment):
                new_nutriment = Nutriment(
                    name=nutriment,
                    unit=settings.NUTRIMENTS[nutriment]["unit"])
                new_nutriment.save()
                print("Adding new nutriment to database :", nutriment)
            else:
                print("Existing nutriment :", nutriment)

        print("--------------------------------------------------")
        for category in settings.PRODUCTS_CATEGORIES:
            if not Category.objects.filter(name__iexact=category):
                new_category = Category(name=category)
                new_category.save()
                print("Adding new category to database :", category)
            else:
                print("Existing category :", category)

        print("--------------------------------------------------")
        for category in Category.objects.all():
            self.get_products_for_category(category.name)

        print("**************************************************")
        print("END OF DATABASE_UPDATE - {}".format(datetime.now()))
        print("**************************************************")
Example #12
0
    def setUp(self):
        # Create the model instances required for the relationship
        self.new_difficulty = Difficulty(name="Very Tough")
        self.new_difficulty.save()

        self.new_category = Category(name="Solid Cakes")
        self.new_category.save()
        # Create the raw data for testing
        lesson_raw_data = {
            "name":"Cherry Cake",
            "price": 3000,
            "average_class_size": 25,
            "difficulty_level": self.new_difficulty,
            "description": "Good Stuff",
        }
        product_raw_data = {
            "name": "Fairy Cake",
            "price": 3000,
            "category":self.new_category,
            "description": "Great Cake!",
            "sizes": "S"
        }
        self.new_lesson = Lesson(**lesson_raw_data)
        self.new_lesson.save()
        self.new_product = Product(**product_raw_data)
        self.new_product.save()
Example #13
0
def add_product(request):
    import pdb
    pdb.set_trace()
    if request.method == 'POST':
        data = request.POST
        categorySerializer = ProductSerializer(data=request.POST)
        # subCategorySerializer = SubCategorySerializers(data=request.POST)
        if categorySerializer.is_valid():
            category = Category()
            category.name = request.POST.get('name')
            category.save(using='products')
            subCategory = SubCategory()
            subCategory.sub_name = request.POST.get('subcategory')
            subCategory.category_id = category.id
            subCategory.save(using='products')
            message = {'message': 'Product Added Successfully'}
            response = json.dumps(message)
            return HttpResponse(response, content_type="application/json")
        else:
            content = {'message': 'Unable to add the product'}
            response = json.dumps(content)
            return HttpResponse(response, content_type="application/json")
    else:
        content = {'message': 'Something went wrong'}
        response = json.dumps(content)
        return HttpResponse(response, content_type="application/json")
Example #14
0
    def insert_data(self):
        """
        Method that insert categories and aliments into
        database with a many to many relationship
        """

        with transaction.atomic():
            categories = self.get_categories(30)
            aliments = self.get_aliments(categories)

            # keep only needed product information
            for cat, elements in aliments.items():
                aliments[cat] = self.cleaned_data(elements)

            # insert categories in database
            if Category.objects.exists():
                pass
            else:
                for cat in categories:
                    category = Category(name=cat)
                    category.save()

            # insert products in database with a many to many
            # relationship with categories
            for cat, elements in aliments.items():
                category = Category.objects.get(name=cat)
                for data in elements:
                    category.products.get_or_create(barcode=data[0],
                                                    name=data[1],
                                                    nutriscore=data[2],
                                                    image=data[3],
                                                    small_image=data[4],
                                                    url=data[5],
                                                    nutrition_img=data[6])
Example #15
0
 def setUp(self):
     super().setUp()
     user = {
         "username": "******",
         "password1": "P4sswordVeryS€cure@",
         "password2": "P4sswordVeryS€cure@",
         "email": "*****@*****.**"
     }
     self.client.post('/consumer/signup', data=user)
     self.token = self.client.post('/user/login',
                                   data={
                                       'email': '*****@*****.**',
                                       'password': '******'
                                   }).json()['key']
     self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)
     c = Consumer.objects.all()[0]
     cat = Category(name='category')
     cat.save()
     cat = Category(name='category2')
     cat.save()
     p = Product(name='product')
     p.save()
     p.categories.set([Category.objects.all()[0]])
     p.save()
     p = Product(name='product2')
     p.save()
     p.categories.set(Category.objects.all())
     p.save()
     p = Product(name='product3')
     p.save()
     p.categories.set([Category.objects.all()[1]])
     p.save()
     r = Report(product=Product.objects.all()[0],
                price=10,
                pnt='POINT(-100.0208 44.0489)',
                consumer=c)
     r.save()
     r = Report(product=Product.objects.all()[1],
                price=50,
                pnt='POINT(-100.0208 44.0489)',
                consumer=c)
     r.save()
     r = Report(product=Product.objects.all()[2],
                price=100,
                pnt='POINT(-100.0208 44.0489)',
                consumer=c)
     r.save()
Example #16
0
 def handle(self, *args, **options):
     Category.objects.all().delete()
     category_names = [
         "category_{}".format(str(i))
         for i in range(options['number_of_categories'])
     ]
     categories = [Category(name=name) for name in category_names]
     Category.objects.bulk_create(categories)
Example #17
0
def create_cat(cat_name, count, report, create_report=0):
    """ create a category and save it"""
    new_cat = Category(name=cat_name)
    if create_report == 1:
        print(cat_name)
        report += f"{cat_name}\n"
    new_cat.save()
    return new_cat, report
Example #18
0
 def insert_categories(self, categories_list: list):
     """Check if a category already exist in db before insertion."""
     for category in categories_list:
         try:
             Category.objects.get(name=category)
         except Category.DoesNotExist:
             add = Category(name=category)
             add.save()
Example #19
0
 def test_ProductsView(self, mock_similar):
     mock_category = Category(id="fruits:fr", name="Fruits")
     mock_similar.return_value = [
         Product(code='1234', name='toto', category=mock_category)
     ]
     url = reverse('products:search')
     response = self.client.get(url, data={'q': 'toto'})
     self.assertContains(response, 'Toto')
Example #20
0
 def test_product_duplicate_name(self):
     url = '/product/add'
     cat = Category(name='new_category')
     cat.save()
     response = self.client.post(url, data={'name': 'product', 'categories': [Category.objects.all()[0].pk]})
     self.assertEqual(response.status_code, status.HTTP_201_CREATED)
     response = self.client.post(url, data={'name': 'product', 'categories': [Category.objects.all()[0].pk]})
     self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
Example #21
0
def create_products():
    bttp = Category(code="BTTP", name="Bê Tông")
    bttp.save()
    bom = Category(code="BOM", name="Bơm")
    bom.save()
    Product(category=bttp,
            code="M100",
            name="Mác 100",
            attributes="+-14",
            listed_price=890000).save()
    Product(category=bttp,
            code="M150",
            name="Mác 150",
            attributes="+-14",
            listed_price=1000000).save()
    Product(category=bttp,
            code="M200",
            name="Mác 200",
            attributes="+-14",
            listed_price=1200000).save()
    Product(category=bttp,
            code="M250",
            name="Mác 250",
            attributes="+-14",
            listed_price=1100000).save()
    Product(category=bttp,
            code="M300",
            name="Mác 300",
            attributes="+-14",
            listed_price=1300000).save()
    Product(category=bttp,
            code="M350",
            name="Mác 350",
            attributes="+-14",
            listed_price=1120000).save()
    Product(category=bom,
            code="BOM37",
            name="Bơm 37m",
            attributes="+-14",
            listed_price=2000000).save()
    Product(category=bom,
            code="BOM45",
            name="Bơm 45m",
            attributes="+-14",
            listed_price=3000000).save()
    def test_delete_from_quantity(self):

        """
        Creates a test Product.
        First sends a post request with the id of the product
        to add the product to the bag to add_to_bag view.
        Then sends another post request to delete_from_quantity to
        remove one item of that product from the bag.
        Ensures that the Product quantity is decreased in the bag by
        displaying the correct message returned by the request.
        Ensures correct redirect status code is returned.
        """

        test_category = Category(name="Kettlebells")
        test_category.save()
        test_discount = Discount(name="30%", rate=0.7)
        test_discount.save()
        test_manufacurer = Manufacturer(name="Great Sports")
        test_manufacurer.save()
        test_product = Product(name="Test", description="A description",
                               image_url="", category=test_category,
                               manufacturer=test_manufacurer,
                               prize=100,
                               discount_rate=test_discount,
                               units_sold=1)
        test_product.save()

        self.client.post("/bag/add_to_bag/1/", {"quantity-input": 1})
        test_response = self.client.post("/bag/delete_from_quantity/1/")

        self.client.post("/bag/add_to_bag/1/", {"quantity-input": 1})
        test_response_message = self.client.post(
            "/bag/delete_from_quantity/1/", follow=True)

        intended_message = "Item was deleted"
        message = ""

        get_stored_messages = test_response_message.context["messages"]
        for message in get_stored_messages:
            message = message

        self.assertEquals(test_response.status_code, 302)
        self.assertEquals(intended_message, message.__str__())

        # Add a quantity of two
        # Ensure the bag content contains one item after deleting one

        self.client.post("/bag/add_to_bag/1/", {"quantity-input": 2})
        test_response_message = self.client.post(
            "/bag/delete_from_quantity/1/", follow=True)

        intended_bag_content = {'1': {'quantity': 1}, 'total_cost': 70}
        shopping_bag = self.client.session["shopping_bag"]

        self.assertEquals(test_response.status_code, 302)
        self.assertEquals(intended_bag_content, shopping_bag)
Example #23
0
 def test_view_cart(self):
     categories = Category(name="Category Name")
     categories.save()
     product_detail = Product(name="Test product",
                              price=999.00,
                              description="Test product description",
                              image="test.jpg")
     product_detail.save()
     response = self.client.get("/cart/")
     self.assertEqual(response.status_code, 200)
Example #24
0
 def fill_categories(self, cat):
     for index, value in enumerate(cat):
         try:
             categories = Category(name=value)
             if Category.objects.filter(name=value).exists():
                 continue
             else:
                 categories.save()
         except KeyError as e:
             print(e)
 def test_view_bag(self):
     categories = Category(name="Category Name")
     categories.save()
     service_detail = Service(name="Test service",
                              price=999.00,
                              description="Test service description",
                              image="test.jpg")
     service_detail.save()
     response = self.client.get("/bag/")
     self.assertEqual(response.status_code, 200)
Example #26
0
 def save_categories(self, categories):
     """
     This function saves in bulk all categories given to it.
     It usually makes only one query to the database, making
     it really fast.
     """
     Category.objects.bulk_create(
         [Category(name=category['name']) for category in categories],
         # Ignore the conflicts to be able to
         # just add categories
         ignore_conflicts=True)
Example #27
0
 def setUp(self):
     """datas call before each funtion"""
     #a cat
     self.category = Category(name="jus de fruits")
     self.category.save()
     #a product
     self.product1 = Product(
         name="Pur jus d'orange sans pulpe", 
         image_url="https://static.openfoodfacts.org/images/products/350/211/000/9449/front_fr.80.400.jpg",
         url="https://world.openfoodfacts.org/product/3502110009449/pur-jus-d-orange-sans-pulpe-tropicana", 
         nutriscore=3, packaging="carton")
     self.product1.save()
Example #28
0
 def test_can_create_a_category(self):
     category = Category(
         title='category',
         slug='catslug',
         featured=False,
         image='test.png',
     )
     category.save()
     self.assertEqual(category.title, 'category')
     self.assertEqual(category.slug, 'catslug')
     self.assertEqual(category.featured, False)
     self.assertEqual(category.image, 'test.png')
Example #29
0
 def setUp(self):
     self.cli = Client()
     cat = Category()
     cat.name = 'conserves'
     cat.save()
     alim = Product()
     alim.id = '3245412718649'
     alim.name = 'abricots'
     alim.save()
     alim.categories.add(cat)
     alim.save()
     self.food = alim
Example #30
0
 def setUp(self):
     self.user, self.profile = create_user_and_profile("test", "test")
     self.logged_in = self.client.login(username="******", password="******")
     self.category = Category(name="jus de fruits")
     self.category.save()
     self.product1 = Product(
         name="Pur jus d'orange sans pulpe",
         image_url=
         "https://static.openfoodfacts.org/images/products/350/211/000/9449/front_fr.80.400.jpg",
         url=
         "https://world.openfoodfacts.org/product/3502110009449/pur-jus-d-orange-sans-pulpe-tropicana",
         nutriscore=3,
         packaging="carton")
     self.product1.save()