def test_product(self):
        product = Product()
        product.name = "A solution book"
        product.price = 200
        product.digital = True
        product.save()

        record = Product.objects.get(pk=1)
        self.assertEqual(record, product)
示例#2
0
def addproduct(request):
    product_name = request.POST.get("name")
    product_price = request.POST.get("price")
    new_product = Product(label=product_name, price=float(product_price))
    new_product.save()

    context = {}
    context["products"] = Product.objects.all()
    return render(request, "store/products.html", context)
示例#3
0
class TestStoreUrls(TestCase):
    """Test Store app urls"""
    def setUp(self):
        # Create a product with its image file
        self.product_data = {
            'name': 'test product name',
            'description': 'test product description',
            'base_price': 49.99,
        }
        with open(f'{settings.BASE_DIR}/store/tests/_test_file_1.png',
                  'rb') as image_file:
            image = ImageFile(image_file)

            self.product = Product(**self.product_data)
            self.product.image.save(new_image_path(self.product, image.name),
                                    image)
            self.product.save()

    def tearDown(self):
        # Remove file in directory after tests
        # Comment out to check path & file creation
        product_path = f'media/products/{self.product.sku}'
        shutil.rmtree(product_path)

    def test_store_landing_url(self):
        """Test Store landing page url and used template"""

        store_page = self.client.get("/store/")
        self.assertEqual(store_page.status_code, 200)
        self.assertTemplateUsed(store_page, 'store/store.html')

    def test_product_details_url(self):
        """Test Store's product details url and used template"""

        product_page = self.client.get(f'/store/{self.product.id}/')
        self.assertEqual(product_page.status_code, 200)
        self.assertTemplateUsed(product_page, 'store/product_details.html')

    def test_store_search_toolbar(self):
        """Test Store's search toolbar returns results to store template"""

        product_page = self.client.get('/store/', {'q': self.product.name})
        self.assertEqual(product_page.status_code, 200)
        self.assertTemplateUsed(product_page, 'store/store.html')

    def test_store_browse_category(self):
        """Test Store's category browsing returns results to store templates"""

        category = Category.objects.create(name='category test name')

        category_page = self.client.get('/store/', {'category': category.name})
        self.assertEqual(category_page.status_code, 200)
        self.assertTemplateUsed(category_page, 'store/store.html')
示例#4
0
def mail(request):
    if request.method == "POST":
        name = (request.POST["name"])
        price = request.POST["price"]
        incoming_prod = Product.objects.filter(name="name")

        if incoming_prod.exists():
            print('email exists')
        else:
            new_product = Product(name=name, price=price)
            new_product.save()

    context = {"webaddress": webaddress[0]}
    return HttpResponse({"webaddress": webaddress[0]})
示例#5
0
def edit_product(request):
    if request.method == 'POST' and request.FILES['image']:
        image = request.FILES['image']

        title = request.POST['title']
        price = request.POST['price']

        description = request.POST['description']
        obj = Product()
        obj.title = title
        obj.description = description
        obj.price = price
        obj.image = image
        obj.save()
        return redirect('/custom-admin')
    return render(request, template_name='store/add_product.html')
示例#6
0
def createproduct(request):
    data = {}
    if request.method != "POST":
        form = ProductForm()
        data['form'] = form
        return render(request, 'store/createproduct.html', data)
    form = ProductForm(request.POST, request.FILES)
    data['form'] = form
    if form.is_valid():
        try:
            pr = Product(**form.cleaned_data)
            pr.save()
            return redirect('createproduct')
        except Exception:
            warning(request, 'Product was not created due to some issue')
            return render(request, 'store/createproduct.html', data)
示例#7
0
def add_product(request):
    if request.method == 'POST':
        form = ProductForm(request.POST, request.FILES)
        product = Product()
        if form.is_valid():
            # product.sub_category = 'ENGINE OIL DIESEL'
            product.name = form.cleaned_data['name']
            product.price = form.cleaned_data['price']
            product.image = form.cleaned_data['image']
            product.author = request.user
            product.save()
            print(request)
            return redirect('products_list')
        else:
            messages.error(request, 'Post error')
            return redirect('add_product')
    form = ProductForm()
    context = {'form': form}
    return render(request, 'staff/product-add.html', context)
示例#8
0
def add_product(request):

    if request.method == "POST":
        form = ProductForm(request.POST)
        if form.is_valid():
            cleaned = (form.cleaned_data)
            name = cleaned['name']
            price = cleaned['price']
            incoming_prod = Product.objects.filter(name="name")

            if incoming_prod.exists():
                print('product exists')

            if request.FILES['image']:
                image = request.FILES['image']
                new_product = Product(name=name, price=price, image=image)
                new_product.save()
                print(new_product.image.path)
                shrink(new_product.image.path)
            else:
                try:
                    if request.FILES['image']:
                        image = request.FILES['image']
                        shrink(image)
                        new_product = Product(name=name,
                                              price=price,
                                              image=image)
                        new_product.save()
                except:

                    new_product = Product(name=name, price=price)
                    new_product.save()
    context = {"webaddress": webaddress[0]}
    return tables(request)
    def handle(self, *args, **options):
        if Category.objects.exists() or Category.objects.exists():
            print('Product already loaded...existing.')
            print(ALREADY_LOADED_ERROR_MESSAGE)
            return

        print('Creating category data')
        for name in CATEGORY_IMAGE_NAMES.keys():
            category = Category(categoryName=name)
            category.categoryImgPath = CATEGORY_IMAGE_NAMES[name]
            category.save()

        print('Loading product data from csv file')
        for line in DictReader(open('./product_data.csv')):
            product = Product()
            product.productName = line['productName']
            product.productPrice = line['productPrice']
            product.productDescription = line['productDescription']
            product.productImgPath = line['productImgPath']
            product.category = Category.objects.get(
                categoryName=line['productCategory'])
            product.save()
示例#10
0
def qchange(request, pk):
    id = request.session['logid']
    q = int(request.POST.get("quantity", ""))
    pl = Plist.objects.all().filter(tfield=pk)
    for i in pl:
        a = 0
    p = Plist()
    i.quantity = q
    j = Product()

    p = Product.objects.all()
    for j in p:
        if (j == i.product_id):
            i.price = q * j.price
            j.quantity -= q
            i.save()
            j.save()
            if (id == 64):
                return redirect('/bill')
            else:
                return redirect('/cart')

        return redirect('/cart')
示例#11
0
    def write_product(self, url, category):
        page = html.parse(url)
        name = unicode(page.xpath('.//div[@class="product_title"]/h1')[0].text_content())
        print 'Writing product : ' + name

        try:
            product = Product.objects.get(categories=category, name=name, store=self.store)
        except Product.DoesNotExist:
            product = Product(name=name, store=self.store)

        # try:
        #     product_info = ProductInfo.objects.get(product=product, store=self.store)
        # except ProductInfo.DoesNotExist:
        #     product_info = ProductInfo(product=product, store=self.store)

        price_els = page.xpath('.//div[@class="product-info"]//div[@class="price"]')
        if len(price_els):
            price_el = price_els[0]
        else:
            return
        old_price_els = price_el.xpath('./span[@class="price-old"]')
        if len(old_price_els):
            old_price_el = old_price_els[0]
            old_price_content = old_price_el.text_content()
            old_price = float(re.search('Rs\.([\d,\.]+)', old_price_content).group(1).replace(',', ''))
            product.original_price = old_price
            new_price_els = price_el.xpath('./span[@class="price-new"]')
            new_price_el = new_price_els[0]
            new_price_content = new_price_el.text_content()
            new_price = float(re.search('Rs\.([\d,\.]+)', new_price_content).group(1).replace(',', ''))
            product.price = new_price
        else:
            price_with_comma = re.search('Price:\s+Rs\.([\d,\.]+)', price_el.text_content()).group(1)
            product.price = float(price_with_comma.replace(',', ''))

        product.currency = self.currency
        description_text = page.xpath('.//div[@class="product-info"]//div[@class="description"]')[0].text_content()
        product.code = re.search('Product Code:\s(.+)\\n', description_text).group(1)
        availability_text = re.search('Availability:\s(.+)', description_text).group(1)

        # TODO: get vendor
        if availability_text == 'In Stock':
            product.availability = 0
        description_el = page.xpath('//div[@id="tab-description"]')[0]
        product.description = tostring(description_el)
        product.purchase_url = url
        product.save()
        product.categories.add(category)
        # TODO: write only if images are new
        # delete existing images first
        images = product.images.all()
        # product.images.clear()
        for image in images:
            image.delete()

        primary_image_url = page.xpath('//div[@class="product-info"]//div[@class="image"]/a')[0].get('href')
        image = Image(image_url=primary_image_url)
        image.save()
        product.images.add(image)
        additional_image_links = page.xpath('//div[@class="image-additional"]/a')
        for image in additional_image_links:
            image_url = image.get('href')
            image = Image(image_url=image_url)
            image.save()
            product.images.add(image)
            # product.save()
示例#12
0
            product.product_SubCategory_id = 4
        elif row[1] == 'Bookcases':
            product.product_SubCategory_id = 5
        elif row[1] == 'Chairs & Chairmats':
            product.product_SubCategory_id = 6
        elif row[1] == 'Tables':
            product.product_SubCategory_id = 7
        elif row[1] == 'Office Furnishings':
            product.product_SubCategory_id = 8
        elif row[1] == 'Paper':
            product.product_SubCategory_id = 9
        elif row[1] == 'Envelopes':
            product.product_SubCategory_id = 10
        elif row[1] == 'Appliances':
            product.product_SubCategory_id = 11
        elif row[1] == 'Labels':
            product.product_SubCategory_id = 12
        elif row[1] == 'Pens & Art Supplies':
            product.product_SubCategory_id = 13
        elif row[1] == 'Rubber Bands':
            product.product_SubCategory_id = 14
        elif row[1] == 'Scissors, Rulers and Trimmers':
            product.product_SubCategory_id = 15
        elif row[1] == 'Binders and Binder Accessories':
            product.product_SubCategory_id = 16
        else:
            product.product_SubCategory_id = 17
        product.product_Name = row[2]
        product.product_Price = row[3]
        product.save()
示例#13
0
 def test_modify_quantity(self):
     product = Product(name="m", quantity=5, price=1)
     product.save()
     product.modify_quantity(2)
     prod = Product.objects.first()
     self.assertEqual(product, prod)
示例#14
0
 def test_product_duplicate_name_not_saved(self):
     product = Product(name="m", price=1)
     product.save()
     product2 = Product(name="m", price=1)
     with self.assertRaises(IntegrityError):
         product2.save()
示例#15
0
 def test_product_empty_string_name_not_saved(self):
     product = Product(name="", price=1)
     with self.assertRaises(ValidationError):
         product.save()
         product.full_clean()
from store.models import Category, Product
import random
import string

pics = ['cpu_amd.jpeg', 'cpu_intel.jpeg', 'GPU.jpeg', 'gpu_amd.jpg', 'gpu_nvidia.jpeg', 'index.jpeg', 'keyboard.jpg', 'keyboard_hp.jpg', 'keyboard_razor.png']

IsInShoppingCart = [True, False]
iteration = 0

for i in range(10000):
	for j in pics:
		a = Category()
		a.name = ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
		a.category_logo = random.choice(pics)
		a.save()

		for k in range(10):
			b = Product()
			b.maker = ''.join(random.choice(string.ascii_uppercase) for _ in range(6))
			b.model = ''.join(random.choice(string.digits) for _ in range(6))
			b.description = 'descr' + str(i) + ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(25))
			b.price = ''.join(random.choice(string.digits) for _ in range(3))
			b.category = a
			b.product_logo = random.choice(pics)
			b.is_in_shopCart = random.choice(IsInShoppingCart)
			b.save()
			iteration += 1
			print "iteration: {}".format(iteration)
class TestStoreFirefox(StaticLiveServerTestCase):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.selenium = Firefox()
        cls.selenium.implicitly_wait(5)

        cls.django_cat = Category.objects.create(name='django')

    @classmethod
    def tearDownClass(cls):
        cls.selenium.quit()
        super().tearDownClass()

    def setUp(self):
        """
        Create a product with its required fields and media files before
        each tests
        """

        self.django_cat = Category.objects.create(name='django')
        self.product_data = {
            'name': 'test product name',
            'description': 'test product description',
            'base_price': 49.99,
        }
        with open(f'{settings.BASE_DIR}/store/tests/_test_file_1.png',
                  'rb') as image_file:
            image = ImageFile(image_file)

            self.product = Product(**self.product_data)
            self.product.image.save(
                new_image_path(self.product, image.name), image)
            self.product.category = self.django_cat
            self.product.save()

    def tearDown(self):
        """
        Remove product's media file in directory after tests,
        test database is automatically cleared
        """
        # Comment out to check path & file creation
        product_path = f'media/products/{self.product.sku}'
        shutil.rmtree(product_path)

    def test_nav_to_store(self):
        """Test navigation to the store's product via the side bar nav"""

        self.selenium.get(f'{self.live_server_url}/')
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.selenium.find_element_by_class_name("slide-in-btn").click()
        self.selenium.find_element_by_link_text("Everything").click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(self.selenium.current_url,
                         f'{self.live_server_url}/store/')

    def test_query_specific_category(self):
        """Should render the store page with a specific category"""

        self.selenium.get(f'{self.live_server_url}/')
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.selenium.find_element_by_class_name("slide-in-btn").click()
        self.selenium.find_element_by_link_text("Marvel").click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(self.selenium.current_url,
                         f'{self.live_server_url}/store/?category=marvel')

    def test_query_multiple_categories(self):
        """Should render the store page with multiple selected categories"""

        self.selenium.get(f'{self.live_server_url}/')
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.selenium.find_element_by_class_name("slide-in-btn").click()
        self.selenium.find_element_by_link_text("Home & Garden").click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(self.selenium.current_url,
                         f'{self.live_server_url}/store/?category=home,garden')

    def test_nav_to_a_product_details_page(self):
        """
        Product(s) should be rendered as cards in store template containing
        image and text links to the product_details template
        """

        self.selenium.get(f'{self.live_server_url}/')
        self.selenium.get(f'{self.live_server_url}/store/')
        WebDriverWait(self.selenium, 10).until(ec.url_changes)

        # Store product(s) should be rendered as an article with 2 links
        # containing its product id
        product_img_link = self.selenium.find_element_by_xpath(
            "//article//a")
        self.assertEqual(
            product_img_link.get_attribute('href'),
            f'{self.live_server_url}/store/{self.product.id}/')

        product_txt_link = self.selenium.find_element_by_xpath(
            "//article//h5//a")
        self.assertEqual(
            product_txt_link.get_attribute('href'),
            f'{self.live_server_url}/store/{self.product.id}/')

        self.selenium.find_element_by_class_name(
            "store-card-img").click()
        self.assertEqual(self.selenium.current_url,
                         f'{self.live_server_url}/store/{self.product.id}/')

    def test_search_toolbar(self):
        """
        Using search toolbar should return store template with product(s)
        containing the keyword(s)
        Test is run twice to search for product name and description matching
        """

        keywords = ['product name', 'product description']

        for keyword in keywords:

            self.selenium.get(f'{self.live_server_url}/')

            self.selenium.find_element_by_xpath(
                "//div[@class='search-bar']//input[@name='q']")\
                .send_keys(keyword)
            self.selenium.find_element_by_xpath(
                "//div[@class='search-bar']//button[@type='submit']")\
                .click()

            # Text query search should be in url
            self.assertIn(
                self.selenium.current_url,
                [f'{self.live_server_url}/store/?q=product+name',
                 f'{self.live_server_url}/store/?q=product+description'])

            # Search key word should be in card's name or description
            product_title = self.selenium.find_element_by_xpath(
                "//article//h5//a")
            product_description = self.selenium.find_element_by_xpath(
                "//article//p")
            full_text = ', '.join([product_title.text,
                                   product_description.text])
            self.assertIn(keyword, full_text)

    def test_sort_results_by_price(self):
        """
        Results should be sorted by highest price then lowest first
        Sort bar should be updated
        """

        self.selenium.get(f'{self.live_server_url}/store/')
        self.selenium.find_element_by_id('sort-selector').click()
        self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@value="price_asc"]'
        ).click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(
            self.selenium.current_url,
            f'{self.live_server_url}/store/?sort=price&direction=asc')
        bar = self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@selected]')
        self.assertEqual(bar.text.strip(), 'Lowest price')

        self.selenium.find_element_by_id('sort-selector').click()
        self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@value="price_desc"]'
        ).click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(
            self.selenium.current_url,
            f'{self.live_server_url}/store/?sort=price&direction=desc')
        bar = self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@selected]')
        self.assertEqual(bar.text.strip(), 'Highest price')

    def test_sort_results_by_date(self):
        """
        Results should be sorted by latest products then oldest
        Sort bar should be updated
        """

        self.selenium.get(f'{self.live_server_url}/store/')
        self.selenium.find_element_by_id('sort-selector').click()
        self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@value="date_desc"]'
        ).click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(
            self.selenium.current_url,
            f'{self.live_server_url}/store/?sort=date&direction=desc')
        bar = self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@selected]')
        self.assertEqual(bar.text.strip(), 'Latest')

        self.selenium.find_element_by_id('sort-selector').click()
        self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@value="date_asc"]'
        ).click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(
            self.selenium.current_url,
            f'{self.live_server_url}/store/?sort=date&direction=asc')
        bar = self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@selected]')
        self.assertEqual(bar.text.strip(), 'Oldest')

    def test_reset_sort_param(self):
        """
        Should set back the Product sorting to its Model's default
        (latest then name). Requires fixtures to test this further
        """

        self.selenium.get(f'{self.live_server_url}/store/')
        self.selenium.find_element_by_id('sort-selector').click()
        self.selenium.find_element_by_xpath(
            '//select[@id="sort-selector"]//option[@value="reset"]'
        ).click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)
        self.assertEqual(
            self.selenium.current_url,
            f'{self.live_server_url}/store/')

    def test_search_query_results_feedback(self):
        """
        Search result string (top of results) should contain categories and
        keywords the user has selected
        """

        self.selenium.get(f'{self.live_server_url}/')
        self.selenium.find_element_by_xpath(
            "//div[@class='search-bar']//input[@name='q']") \
            .send_keys('product name')
        self.selenium.find_element_by_xpath(
            "//div[@class='search-bar']//button[@type='submit']") \
            .click()

        search_string = self.selenium.find_element_by_css_selector(
            '.main-wrapper header p')
        self.assertEqual(search_string.text,
                         "1 Product found for ' product name '")

        self.selenium.find_element_by_id(
            "categories-selector").click()
        self.selenium.find_element_by_css_selector(
            "#categories-selection li").click()
        self.selenium.find_element_by_xpath(
            "//div[@class='search-bar']//button[@type='submit']") \
            .click()
        search_string = self.selenium.find_element_by_css_selector(
            '.main-wrapper header p')

        # First letter of category capitalized by template filter
        self.assertEqual(search_string.text,
                         "1 Product found for ' product name ' in Django")

    def test_search_bar_category(self):
        """
        Available categories should be in search bar dropdown to filter search
        results. Categories should remain selected on search results.
        """

        self.selenium.get(f'{self.live_server_url}/')
        self.selenium.find_element_by_id("categories-selector").click()

        categories_selection = self.selenium.find_elements_by_css_selector(
            "#categories-selection li")
        categories = Category.objects.all()
        self.assertEqual(len(categories), len(categories_selection))

        category = self.selenium.find_element_by_css_selector(
            "#categories-selection li")

        category.click()
        self.selenium.find_element_by_id("categories-selector").click()
        self.assertEqual(category.get_attribute('class'),
                         'dropdown-item active-selection')

        self.selenium.find_element_by_xpath(
            "//div[@class='search-bar']//button[@type='submit']") \
            .click()
        WebDriverWait(self.selenium, 10).until(ec.url_changes)

        self.selenium.find_element_by_id("categories-selector").click()
        category = self.selenium.find_element_by_css_selector(
            "#categories-selection li")
        self.assertEqual(category.get_attribute('class'),
                         'dropdown-item active-selection')
for i in range(0, len(movies)):

    if (i == 0):
        continue

    lst = movies[i].split("\t")

    id = lst[0]
    title = lst[1]
    genre = lst[2]
    runtime = lst[3]
    adult = lst[4]
    bob = False
    if (adult == "Yes"):
        bob = True
    url = lst[5]
    disc = lst[6]

    p = Product(ID=id,
                originalTitle=title,
                isAdult=bob,
                runtime=runtime,
                genres=genre,
                poster=url,
                description=disc,
                isBooked=False,
                price=random.randint(80, 101))

    p.save()