Beispiel #1
0
    def test_thumbnails_are_generated_on_save(self):
        """
        This test has a small problem: the test pic won't be deleted if the
        test fails to pass.
        """
        product = models.Product(
            name=self.TEST_PROD_NAME, price=self.TEST_PROD_PRICE
        )
        product.save()

        with open(
            file=f"main/fixtures/{self.TEST_PROD_FILENAME}.jpg", mode="rb"
        ) as f:
            image = models.ProductImage(
                product=product,
                image=ImageFile(f, name="testpic_testsignal.jpg"),
            )

            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open(
            file=f"main/fixtures/{self.TEST_PROD_FILENAME}.thumb.jpg",
            mode="rb",
        ) as f:
            expected_content = f.read()

            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #2
0
    def test_thumbnails_are_created_on_save(self):
        product = models.Product(
            name="The cathedral and the bazaar",
            price=Decimal("20.00")
        )
        product.save()

        with open("main/fixtures/the-cathedral-the-bazaar.jpg", "rb") as f:
            image = models.ProductImage(
                product=product,
                image=ImageFile(f, name="tctb.jpg"),
            )
            logger = logging.getLogger("main")
            with self.assertLogs(logger, level="INFO") as cm:
                image.save()

            self.assertGreaterEqual(len(cm.output), 1)
            image.refresh_from_db()

            with open("main/fixtures/the-cathedral-the-bazaar.thumb.jpg", "rb") as tn:
                expected_content = tn.read()
                thumbnail = image.thumbnail.read()
                assert thumbnail == expected_content

            image.thumbnail.delete(save=False)
            image.image.delete(save=False)
 def test_thumbnails_are_generated_on_save(self):
     product = models.Product(name="The cathedral and the bazaar", price = Decimal("10.00"))
     product.save()
     with open("main/fixtures/the-cathedral-the-bazaar.jpg", "rb") as f:
         image = models.ProductImage(product=product),
                                     image=ImageFile(f, name="tctb.jpg"),
                                     )
    def test_thumbnails_generated_on_save(self):
        product = models.Product(
            name='Test product',
            price=Decimal('10.0'),
        )
        product.save()

        with open('main/fixtures/test_image.jpg', 'rb') as f:
            image = models.ProductImage(
                product=product,
                image=ImageFile(f, name='test_image.jpg'),
            )
            with self.assertLogs('main', level='INFO') as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open('main/fixtures/test_image.thumb.jpg', 'rb') as f:
            expected_content = f.read()

            self.assertEqual(image.thumbnail.read(), expected_content)

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
    def test_thumbnails_are_generated_on_save(self):
        """
        Overview
        1. product init inst & save
        2. product image (original)
        3. product image (thumbnail)

        The 'signals.py' lies between "models" & "views",
        you don't actually can see it 
        """

        product = models.Product(name="The Cathedral and the bazaar",
                                 price=Decimal("3.00"))

        product.save()

        with open("main/fixtures/the-cathedral-the-bazaar.jpg", "rb") as fi:
            image = models.ProductImage(product=product,
                                        image=ImageFile(fi, name="tctb.jpg"))

            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open("main/fixtures/the-cathedral-the-bazaar.thumb.jpg",
                  "rb") as fi:
            expected_content = fi.read()
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #6
0
    def test_image_model_and_thumbnails_are_generated_on_save(self):
        #user image
        with open("main/fixtures/test_image.jpg", "rb") as f:
            image = models.UserImage(user=self.user1,
                                     image=ImageFile(f, name="tctb.jpg"))

            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()
        with open(os.path.join(MEDIA_ROOT, image.thumbnail.name), "rb") as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)

        #product image
        with open("main/fixtures/test_image.jpg", "rb") as f:
            image = models.ProductImage(product=self.product,
                                        image=ImageFile(f, name="tctb.jpg"))

            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()
        with open(os.path.join(MEDIA_ROOT, image.thumbnail.name), "rb") as f:
            expected_content = f.read()

            assert image.thumbnail.read() == expected_content
        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
    def test_product_page_switches_images_correctly(self):
        product = models.Product.objects.create(
            name="The cathedral and the bazaar",
            slug="cathedral-bazaar",
            price=Decimal("10.00"),
        )
        for fname in ["cb1.jpg", "cb2.jpg", "cb3.jpg"]:
            with open("main/fixtures/cb/%s" % fname, "rb") as f:
                image = models.ProductImage(
                    product=product,
                    image=ImageFile(f, name=fname),
                )
                image.save()

        self.selenium.get("%s%s" % (
            self.live_server_url,
            reverse(
                "product",
                kwargs={"slug": "cathedral-bazaar"},
            ),
        ))
        current_image = self.selenium.find_element_by_css_selector(
            ".current-image > img:nth-child(1)").get_attribute("src")
        self.selenium.find_element_by_css_selector(
            "div.image:nth-child(3) > img:nth-child(1)").click()
        new_image = self.selenium.find_element_by_css_selector(
            ".current-image > img:nth-child(1)").get_attribute("src")
        self.assertNotEqual(current_image, new_image)
Beispiel #8
0
    def handle(self, *args, **options):
        self.stdout.write("Importing products")
        c = Counter()
        
        reader = csv.DictReader(options.pop("csvfile"))
        for row in reader:
            product, created = models.Product.objects.get_or_create(name=row["name"], price=row["price"], brand_id=row["brand"])
            product.description = row["description"]
            product.slug = slugify(row["name"])
            for import_tag in row["tags"].split("|"):
                tag, tag_created = models.ProductTag.objects.get_or_create(name=import_tag)
                product.tags.add(tag)
                c["tags"] += 1
                if tag_created:
                    c["tags_created"] += 1
            with open(os.path.join(options["image_basedir"], row["image_filename"], ), "rb",) as f:
                image = models.ProductImage(product=product, image=ImageFile(f, name=row["image_filename"]),)
                image.save()
                c["images"] += 1
            product.save()
            c["products"] += 1
            if created:
                c["products_created"] += 1

        self.stdout.write("Products processed=%d (created=%d)" % (c["products"], c["products_created"]))
        self.stdout.write("Tags processed=%d (created=%d)" % (c["tags"], c["tags_created"]))
        self.stdout.write("Images processed=%d" % c["images"])
Beispiel #9
0
    def test_thumbnails_are_generated_on_server(self):
        product = models.Product(
            name='The cathedral and the bazaar',
            price=Decimal('10.00'),
        )
        product.save()

        with open('main/fixtures/the-cathedral-the-bazaar.jpg', 'rb') as f:
            image = models.ProductImage(
                product=product,
                image=ImageFile(f, name='tctb.jpg'),
            )
            with self.assertLogs("main", level='INFO') as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open('main/fixtures/the-cathedral-the-bazaar.thumb.jpg',
                  'rb') as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content

            image.thumbnail.delete(save=False)
            image.image.delete(save=False)
Beispiel #10
0
    def test_thumbnails_are_generated_on_save(self):
        product = models.Product(
            name="The cathedral the bazaar",
            price=Decimal("10.00"),
        )
        product.save()

        with open("main/fixtures/the-catheral-the-bazaar.thumb.jpg" "rb") as f:
            image = models.ProductImage(product=product,
                                        image=ImageFile(f, name="tctb.jpg"))
            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open(
                "main/fixtures/the-cathederal-the-bazaar.thumb.jpg",
                "rb",
        ) as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #11
0
    def handle(self, *args, **options):
        self.stdout.write('Importing products')
        c = Counter()
        reader = csv.DictReader(options.pop('csvfile'))
        for row in reader:
            product, created = models.Product.objects.get_or_create(
                name=row['name'], price=row['price'])
            product.description = row['description']
            product.slug = slugify(row['name'])
            for import_tag in row['tags'].split('|'):
                tag, tag_created = models.ProductTag.objects.get_or_create(
                    name=import_tag)
                product.tags.add(tag)
                c['tags'] += 1
                if tag_created:
                    c['tag_created'] += 1
            with open(
                    os.path.join(options['image_basedir'],
                                 row['image_filename']), 'rb') as f:
                image = models.ProductImage(product=product,
                                            image=ImageFile(
                                                f, name=row['image_filename']))
                image.save()
                c['images'] += 1
                product.save()
                c['products'] += 1
                if created:
                    c['products_created'] += 1

                self.stdout.write('Products processed=%d (created=%d)' %
                                  (c['products'], c['products_created']))

                self.stdout.write('Tags processed=%d (created=%d)' %
                                  (c['tags'], c['tags_created']))
                self.stdout.write('Images processed=%d' % c['images'])
Beispiel #12
0
 def test_product_page_switches_images_correctly(self):
     product = models.Product.objects.create(
         name='The cathedral and the bazaar',
         slug='cathedral-bazaar',
         price=Decimal('10.00'),
     )
     # создать продукт с тремя изображениями
     for fname in ['cb1.jpg', 'cb2.jpg', 'cb3.jpg']:
         with open('main/fixtures/cb/%s' % fname, 'rb') as f:
             image = models.ProductImage(
                 product=product,
                 image=ImageFile(f, name=fname),
             )
             image.save()
     self.selenium.get("%s%s" % (
         self.live_server_url,
         reverse(
             "product",
             kwargs={"slug": "cathedral-bazaar"},
         ),
     ))
     current_image = self.selenium.find_element_by_css_selector(
         ".current-image > img:nth-child(1)").get_attribute("src")
     self.selenium.find_element_by_css_selector(
         "div.image:nth-child(3) > img:nth-child(1)").click()
     new_image = self.selenium.find_element_by_css_selector(
         ".current-image > img:nth-child(1)").get_attribute("src")
     # Полное изображение изменилось на то, по которому щелкнул тест.
     self.assertNotEqual(current_image, new_image)
Beispiel #13
0
    def test_thumbnails_are_generated_on_save(self):
        product = models.Product(
            name='Learning Python 3.8',
            price=Decimal("20.00"),
        )
        product.save()

        # input("press any key to continue")

        with open("main/fixtures/learning-python-38.jpg", "rb") as f:
            image = models.ProductImage(
                product=product,
                image=ImageFile(f, name="lp38.jpg"),
            )
            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open(
                "main/fixtures/learning-python-38-thumb.jpg",
                "rb",
        ) as f:
            expected_content = f.read()
            print(type(expected_content))
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #14
0
    def test_thumbnails_are_generated_on_save(self):
        product = ProductFactory()

        with open('main/fixtures/cat.jpeg', 'rb') as f:
            image = models.ProductImage(product=product, image=ImageFile(f, name='cat.jpeg'))
            image.save()
        image.refresh_from_db()
        with open('media/product-thumbnails/cat.jpeg', 'rb') as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content
        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
    def test_thumbnails_are_generated_on_product_save(self):
        product = models.Product(name="Harry Potter", price=Decimal("10.00"))
        product.save()

        with open("main/fixtures/sample-images/harry-potter.jpg", "rb") as f:
            image = models.ProductImage(product=product,
                                        image=ImageFile(f, name="hp.jpg"))
            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #16
0
    def test_thumbnail_are_generated_on_save(self):
        product = models.Product(name='Laptop',price=Decimal('150.00'),)
        product.save()

        with open('main/fixtures/jacket.jpg',"rb") as f:
            image = models.ProductImage(product=product,image=ImageFile(f,name="tctb.jpg"),)
            with self.assertLogs("main",level="INFO") as cm:
                image.save()
        self.assertGreaterEqual(len(cm.output),1)
        image.refresh_from_db()
        with open("main/fixtures/jacket.thumb.jpg","rb",) as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #17
0
    def test_thumbnails_are_generated_on_save(self):
        product = models.Product(name="Breguet-Classique-Automatic-40mm", price=Decimal("10000.00"),)
        product.save()

        with open("main/fixtures/Breguet-Classique-Automatic-40mm.jpg", "rb") as f:
            image = models.ProductImage(product=product, image=ImageFile(f, name="xxx.jpg"),)
            with self.assertLogs("main", level="INFO") as cm:
                image.save()

        self.assertGreaterEqual(len(cm.output), 1)
        image.refresh_from_db()

        with open("main/fixtures/Breguet-Classique-Automatic-40mm.jpg", "rb",) as f:
            expected_content = f.read()
            assert image.thumbnail.read() == expected_content

        image.thumbnail.delete(save=False)
        image.image.delete(save=False)
Beispiel #18
0
    def handle(self, *args, **options):
        self.stdout.write("Importing Products")
        c = Counter()
        c['tags_created'] = 0
        c['products_created'] = 0
        reader = csv.DictReader(options.pop("csvfile"))
        for row in reader:
            product, created = models.Product.objects.get_or_create(
                name=row['name'], price=row['price'])
            product.description = row['description']
            product.slug = slugify(row['name'])
            for import_tag in row['tags'].split('|'):
                tag, tag_created = models.ProductTag.objects.get_or_create(
                    name=import_tag)
                product.tags.add(tag)
                c['tags'] += 1
                if tag_created:
                    c['tags_created'] += 1
            with open(
                    os.path.join(
                        options['image_basedir'],
                        row['image_filename'],
                    ), "rb") as f:
                image = models.ProductImage(
                    product=product,
                    image=ImageFile(f, name=row["image_filename"]),
                )
                image.save()
                c["images"] += 1
            product.save()
            c["products"] += 1
            if created:
                c['products_created'] += 1

        # self.stdout.write(
        # "Products Processed = % (Created=%)", (
        #   c["products"], c["products_created"])
        # )
        self.stdout.write(
            f'Products processed = {c["products"]} (created = {c["products_created"]})'
        )
        self.stdout.write(
            f'Tags processed = {c["tags"]} (created = {c["tags_created"]})')
        self.stdout.write(f'Images processed = {c["images"]}')
Beispiel #19
0
    def test_product_page_switches_images_correctly(self):
        product = models.Product.objects.create(
            name='Joker',
            slug='joker',
            price=Decimal('10.00'),
        )
        for fname in ['1.jpg', '2.jpg', '3.jpg']:
            with open(f'main/fixtures/joker/{fname}', 'rb') as f:
                image = models.ProductImage(
                    product=product,
                    image=ImageFile(f, name=fname)
                )
                image.save()

        self.selenium.get(
            "%s%s"
            % (
                self.live_server_url,
                reverse(
                    'product',
                    kwargs={'slug': 'joker'}
                ),
            )
        )

        current_image = self.selenium.find_element_by_css_selector(
            '.current-image > img:nth-child(1)'
        ).get_attribute(
            'src'
        )

        self.selenium.find_element_by_css_selector(
            'div.image:nth-child(3) > img:nth-child(1)'
        ).click()
        new_image = self.selenium.find_element_by_css_selector(
            '.current-image > img:nth-child(1)'
        ).get_attribute('src')
        self.assertNotEqual(current_image, new_image)
Beispiel #20
0
	def test_product_page_switches_images_correctly(self):
		product = models.Product.objects.create(
			name='The cathedral and the bazaar',
			slug='cathedral-bazaar', 
			price=Decimal('10.00'), 
		)

		for fname in ['cb1.jpg', 'cb2.jpg', 'cb3.jpg']:
			with open('main/fixtures/cb/%s' % fname, 'rb') as f:
				image = models.ProductImage(
					product=product, 
					image=ImageFile(f, name=fname), 
				)
				image.save()

		self.selenium.get(
			'%s%s' % (
				self.live_server_url, 
				reverse(
					'product', 
					kwargs={'slug': 'cathedral-bazaar'},
				),
			)
		)

		current_image = self.selenium.find_element_by_css_selector(
			'.current-image > img:nth-child(1)'
		).get_attribute('src')

		self.selenium.find_element_by_css_selector(
			'div.image:nth-child(3) > img:nth-child(1)'
		).click()

		new_image = self.selenium.find_element_by_css_selector(
			'.current-image > img:nth-child(1)' 
		).get_attribute('src')

		self.assertNotEqual(current_image, new_image)
    def handle(self, *args, **options):
        """ The logic code will be put in here.
        
        How to use this management command?
        >> ./manage.py import_data YOUR_CSV_FILE_PATH YOUR_IMAGES_FILE_PATH
        """

        self.stdout.write("Importing products")

        # Load the data
        c = Counter()
        reader = csv.DictReader(options.pop("csvfile"))

        for row in reader:

            # Generate data :: Product
            product, created = models.Product.objects.get_or_create(
                name=row["name"], price=row["price"])

            product.description = row["description"]
            product.slug = slugify(row["name"])

            # Parse multiple tags if there is
            # that means the "delim" depends on the data (may not '|')
            for import_tag in row["tags"].split("|"):

                # Generate data :: ProductTag
                tag, tag_created = models.ProductTag.objects.get_or_create(
                    name=import_tag)

                product.tags.add(tag)

                c["tags"] += 1
                if tag_created:
                    c["tag_created"] += 1

            with open(
                    os.path.join(options["image_basedir"],
                                 row["image_filename"]), "rb") as fi:

                # Generate data :: ProductImage
                image = models.ProductImage(
                    product=product,
                    image=ImageFile(fi, name=row["image_filename"]))

                image.save()
                c["images"] += 1

            product.save()
            c["products"] += 1

            if created:
                c["products_created"] += 1

        self.stdout.write("Products processed=%d (created=%d)" %
                          (c["products"], c["products_created"]))

        # self.stdout.write(
        #     "Tags processed=%d (created=%d)"
        #     % (c["tags"], c["tags_created"])
        # )

        self.stdout.write("Images processed=%d" % (c["images"]))