Exemplo n.º 1
0
def test_simple_search_word_finder(rf):
    cache.clear()
    view = SearchView.as_view()
    name = "Savage Garden"
    sku = UNLIKELY_STRING
    prod = create_product(
        sku=sku,
        name=name,
        keywords="truly, madly, deeply",
        description="Descriptive text",
        shop=get_default_shop()
    )

    resp = view(apply_request_middleware(rf.get("/")))
    assert prod not in resp.context_data["object_list"], "No query no results"

    partial_sku = sku[:int(len(sku)/2)]
    valid_searches = ["Savage", "savage", "truly", "madly", "truly madly", "truly garden", "text", sku, partial_sku]
    for query in valid_searches:
        resp = view(apply_request_middleware(rf.get("/", {"q": query})))
        assert name in resp.rendered_content

    invalid_searches = ["saavage", "", sku[::-1]]
    for query in invalid_searches:
        resp = view(apply_request_middleware(rf.get("/", {"q": query})))
        assert name not in resp.rendered_content
Exemplo n.º 2
0
def test_single_page_checkout_with_login_and_register(browser, live_server, settings):
    cache.clear()  # Avoid caches from past tests

    # initialize
    product_name = "Test Product"
    get_default_shop()
    get_default_payment_method()
    get_default_shipping_method()
    product = create_orderable_product(product_name, "test-123", price=100)
    OrderStatus.objects.create(
        identifier="initial",
        role=OrderStatusRole.INITIAL,
        name="initial",
        default=True
    )

    # Initialize test and go to front page
    browser = initialize_front_browser_test(browser, live_server)

    wait_until_condition(browser, lambda x: x.is_text_present("Welcome to Default!"))
    navigate_to_checkout(browser, product)

    # Let's assume that after addresses the checkout is normal
    wait_until_condition(browser, lambda x: x.is_text_present("Checkout Method"))
    test_username = "******"
    test_email = "*****@*****.**"
    test_password = "******"
    register_test(browser, live_server, test_username, test_email, test_password)

    login_and_finish_up_the_checkout(browser, live_server, test_username, test_email, test_password)
def test_get_random_products_cache_bump():
    from E-Commerce.front.template_helpers import general

    supplier = get_default_supplier()
    shop = get_default_shop()

    products = [create_product("sku-%d" % x, supplier=supplier, shop=shop) for x in range(2)]
    children = [create_product("SimpleVarChild-%d" % x, supplier=supplier, shop=shop) for x in range(2)]

    for child in children:
        child.link_to_parent(products[0])

    context = get_jinja_context()
    cache.clear()
    set_cached_value_mock = mock.Mock(wraps=context_cache.set_cached_value)
    def set_cache_value(key, value, timeout=None):
        if "random_products" in key:
            return set_cached_value_mock(key, value, timeout)

    with mock.patch.object(context_cache, "set_cached_value", new=set_cache_value):
        assert set_cached_value_mock.call_count == 0

        assert general.get_random_products(context, n_products=10)
        assert set_cached_value_mock.call_count == 1

        # call again, the cache should be returned instead and the set_cached_value shouldn't be called again
        assert general.get_random_products(context, n_products=10)
        assert set_cached_value_mock.call_count == 1

        # change a shop product, the cache should be bumped
        ShopProduct.objects.filter(shop=shop).first().save()
        assert general.get_random_products(context, n_products=10)
        assert set_cached_value_mock.call_count == 2
Exemplo n.º 4
0
 def __get_all_facesdescriptor(self):
     host = config.get("db", "host")
     port = config.get("db", "port")
     user = config.get("db", "user")
     password = config.get("db", "password")
     db = config.get("db", "db")
     dbdialect = config.get("db", "dbdialect")
     try:
         connection = self.getConnection(dbdialect, host, port, user,
                                         password, db)
     except:
         logger.error("connect db failed")
         return
     try:
         with connection.cursor() as cursor:
             allFaceDescriptorsSql = "select * from t_face_descriptor"
             cursor.execute(allFaceDescriptorsSql)
             result = cursor.fetchall()
             if len(result) > 0:
                 # 清空缓存数据
                 cache.clear()
                 for t in result:
                     dict = {}
                     dict["employeeNo"] = t["employeeNo"]
                     descriptor = t["face_descriptor"]
                     descriptor = descriptor.split(",")
                     descriptor = [float(i) for i in descriptor]
                     numpyArray = np.array(descriptor)
                     dict["face_descriptor"] = numpyArray
                     cache.append(dict)
     except:
         logger.error("get data from db failed")
     finally:
         connection.close()
def test_get_listed_products_cache_bump():
    supplier = get_default_supplier()
    shop = get_default_shop()
    product_1 = create_product("test-sku-1", supplier=supplier, shop=shop,)

    from E-Commerce.front.template_helpers import general
    filter_dict = {"id": product_1.pk}

    cache.clear()
    context = get_jinja_context()

    set_cached_value_mock = mock.Mock(wraps=context_cache.set_cached_value)
    def set_cache_value(key, value, timeout=None):
        if "listed_products" in key:
            return set_cached_value_mock(key, value, timeout)

    with mock.patch.object(context_cache, "set_cached_value", new=set_cache_value):
        assert set_cached_value_mock.call_count == 0

        for cache_test in range(2):
            assert general.get_listed_products(context, n_products=2, filter_dict=filter_dict, orderable_only=False)
            assert set_cached_value_mock.call_count == 1

        # bump cache
        product_1.save()
        for cache_test in range(2):
            assert general.get_listed_products(context, n_products=2, filter_dict=filter_dict, orderable_only=False)
            assert set_cached_value_mock.call_count == 2

        # use other filters
        from django.db.models import Q
        for cache_test in range(2):
            assert general.get_listed_products(context, n_products=2, extra_filters=Q(translations__name__isnull=False))
            assert set_cached_value_mock.call_count == 3
Exemplo n.º 6
0
def test_product_descriptions(browser, live_server, settings):
    activate("en")
    cache.clear()
    shop = get_default_shop()
    product = create_product("product1",
                             shop=shop,
                             description="<b>My HTML description</b>",
                             short_description="some short of description instead",
                             supplier=get_default_supplier())
    sp = ShopProduct.objects.get(product=product, shop=shop)
    sp.primary_category = get_default_category()
    sp.categories.add(get_default_category())
    sp.save()

    # initialize test and go to front page
    browser = initialize_front_browser_test(browser, live_server)

    # view product detail page
    url = reverse("E-Commerce:product", kwargs={"pk": product.pk, "slug": product.slug})
    browser.visit("%s%s" % (live_server, url))
    wait_until_condition(browser, lambda x: x.is_text_present(product.short_description))
    assert product.description in browser.html

    # product preview
    url = reverse("E-Commerce:all-categories")
    browser.visit("%s%s" % (live_server, url))
    product_div_name = "product-{}".format(product.pk)
    wait_until_condition(browser, lambda x: x.find_by_css("#{} button.btn".format(product_div_name)))
    browser.execute_script("$('#{} button.btn').click();".format(product_div_name))
    assert product.short_description == browser.find_by_css("#{} p.description".format(product_div_name))[0].html
Exemplo n.º 7
0
def test_manufacturer_filter_get_fields(rf):
    cache.clear()

    shop = factories.get_default_shop()

    request = apply_request_middleware(rf.get("/"))
    assert ManufacturerProductListFilter().get_fields(request, None) is None

    manufacturer = Manufacturer.objects.create(name="Random Brand Inc")
    assert ManufacturerProductListFilter().get_fields(request, None) is None

    category = factories.get_default_category()
    product = factories.create_product("sku", shop=shop)
    shop_product = product.get_shop_instance(shop=shop)
    shop_product.primary_category = category
    shop_product.save()

    assert ManufacturerProductListFilter().get_fields(request, category) is None

    # Now once we link manufacturer to product we should get
    # form field for manufacturer
    product.manufacturer = manufacturer
    product.save()
    form_field = ManufacturerProductListFilter().get_fields(request, category)[0][1]
    assert form_field is not None
    assert form_field.label == "Manufacturers"

    with override_settings(E-Commerce_FRONT_OVERRIDE_SORTS_AND_FILTERS_LABELS_LOGIC={"manufacturers": "Brands"}):
        form_field = ManufacturerProductListFilter().get_fields(request, category)[0][1]
        assert form_field is not None
        assert form_field.label == "Brands"
Exemplo n.º 8
0
def main_menu():
   
    if len(Addon.getSetting("username"))>0:
      cookie_member,ok=cache.get(testlogin,12,'real', table='id')
      if ok:
        xbmc.executebuiltin((u'Notification(%s,%s)' % ('Movix', 'ברוך הבא לקוח פרימיום'.decode('utf8'))).encode('utf-8'))
      else:
        xbmc.executebuiltin((u'Notification(%s,%s)' % ('Movix', 'כשלון בהתחברות!! בדוק פרטי חשבון'.decode('utf8'))).encode('utf-8'))
        cache.clear(['id'])
    html=read_site_html('http://movix.live/')
    regex='a href="(.+?)">(.+?)</a></li>'
    match=re.compile(regex).findall(html)
    all_img=[u'https://wsdg.com/wp-content/uploads/casa-cor-home-cinema-2009-3.jpg', u'http://www.movies-site.com/wp-content/uploads/2013/04/gi-joe-retaliation.jpeg', u'https://www.pitria.com/wp-content/uploads/2015/08/170.jpg?x27391', u'http://images.huffingtonpost.com/2015-11-18-1447856895-9700-gang.png', u'http://2.bp.blogspot.com/__J1uTFOVfZY/TRPuGg4iN_I/AAAAAAAAA58/572xDBA2q2E/s1600/gif_9_drama_masks.gif', u'http://www.jugrnaut.com/wp-content/uploads/mysterybox.jpg', u'http://www.billboard.com/files/media/Michael-Jackson-Thriller-3d-promo-billboard-1548.jpg', u'http://www.brostrick.com/wp-content/uploads/2017/02/best-quotes-from-pulp-fiction-gifs-scenes.jpg', u'https://www.hdwallpaper.nu/wp-content/uploads/2015/06/3D-skull-horror-wallpaper-2560x1600.jpg', u'https://s3.amazonaws.com/university-prod/uploads/attachments/354/original/motion.png?1444883111', u'http://www.publicdomainpictures.net/pictures/190000/velka/fantasy-landschaft-1471278439FaB.jpg', u'https://prod01-cdn04.cdn.firstlook.org/wp-uploads/sites/1/2017/05/Korean-war-mehdi-hasan-1493757632-feature-hero.jpg', u'https://i.ytimg.com/vi/f6ZmXM6ZT0c/hqdefault.jpg', u'http://www.onefamily.ie/wp-content/uploads/bulgarian-imge.jpg', u'http://www.brisbanekids.com.au/wp-content/uploads/2013/06/KidsBrush.jpg', u'https://www.outerplaces.com/images/user_upload/imdb-chart.jpg', u'https://raw.githubusercontent.com/DanielHadley/YouTubeNotMusic/master/YouTube.png', u'http://image.tmdb.org/t/p/original/fQHP3rzL8QYROBq8RHsCaLul51M.jpg', u'https://www.youthareawesome.com/wp-content/uploads/2015/05/Wholly-icons-wallpaper-twilight-series-2849585-1280-800.jpg']
    import requests
    headers = {

    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    }
    i=0
    for link,name in match:
     
      name=replace_all_names(name)
      if len(all_img)>i:
        f_img=all_img[i]
      else:
        f_img=' '
      i=i+1
      if 'ראשי' not in name:
        addDir3(name,link,2,f_img,f_img,name)
    
    addDir3('[COLOR aqua][I]חיפוש[/I][/COLOR]','www',5,' ',' ','חיפוש')
Exemplo n.º 9
0
def initialize_admin_browser_test(browser, live_server, settings, username="******", password="******",
                                  onboarding=False, language="en", shop=None, tour_complete=True):
    if not onboarding:
        settings.E-Commerce_SETUP_WIZARD_PANE_SPEC = []
    activate("en")
    cache.clear()

    shop = shop or get_default_shop()

    if tour_complete:
        from django.contrib.auth import get_user_model
        user = get_user_model().objects.get(username=username)
        set_tour_complete(shop, "dashboard", True, user)
        set_tour_complete(shop, "home", True, user)
        set_tour_complete(shop, "product", True, user)
        set_tour_complete(shop, "category", True, user)

    url = live_server + "/sa"
    browser.visit(url)
    browser.fill('username', username)
    browser.fill('password', password)
    browser.find_by_css(".btn.btn-primary.btn-lg.btn-block").first.click()

    if not onboarding:
        # set shop language to eng
        browser.find_by_id("dropdownMenu").click()
        browser.find_by_xpath('//a[@data-value="%s"]' % language).first.click()

    return browser
Exemplo n.º 10
0
def test_get_orderable_variation_children(rf):
    supplier = get_default_supplier()
    shop = get_default_shop()

    variable_name = "Color"
    parent = create_product("test-sku-1", shop=shop)
    variation_variable = ProductVariationVariable.objects.create(product=parent, identifier="color", name=variable_name)
    red_value = ProductVariationVariableValue.objects.create(variable=variation_variable, identifier="red", value="Red")
    blue_value =ProductVariationVariableValue.objects.create(variable=variation_variable, identifier="blue", value="Blue")
    combinations = list(parent.get_all_available_combinations())
    assert len(combinations) == 2
    for combo in combinations:
        assert not combo["result_product_pk"]
        child = create_product("xyz-%s" % combo["sku_part"], shop=shop, supplier=get_default_supplier(), default_price=20)
        child.link_to_parent(parent, combination_hash=combo["hash"])

    combinations = list(parent.get_all_available_combinations())
    assert len(combinations) == 2
    parent.refresh_from_db()
    assert parent.is_variation_parent()
    request = apply_request_middleware(rf.get("/"))

    cache.clear()
    for time in range(2):
        orderable_children, is_orderable = get_orderable_variation_children(parent, request, None)
        assert len(orderable_children)
        for var_variable, var_values in dict(orderable_children).items():
            assert var_variable == variation_variable
            assert red_value in var_values
            assert blue_value in var_values
def test_get_listed_products_filter():
    context = get_jinja_context()
    shop = get_default_shop()
    supplier = get_default_supplier()

    product_1 = create_product(
        "test-sku-1",
        supplier=supplier,
        shop=shop,
    )
    product_2 = create_product(
        "test-sku-2",
        supplier=supplier,
        shop=shop,
    )

    cache.clear()
    from E-Commerce.front.template_helpers import general
    filter_dict = {"id": product_1.id}
    for cache_test in range(2):
        product_list = general.get_listed_products(context, n_products=2, filter_dict=filter_dict)
        assert product_1 in product_list
        assert product_2 not in product_list

    for cache_test in range(2):
        product_list = general.get_listed_products(context, n_products=2, filter_dict=filter_dict, orderable_only=False)
        assert product_1 in product_list
        assert product_2 not in product_list
Exemplo n.º 12
0
def test_simple_search_get_ids_works(rf):
    cache.clear()
    prod = get_default_product()
    bit = prod.name[:5]
    request = apply_request_middleware(rf.get("/"))
    assert prod.pk in get_search_product_ids(request, bit)
    assert prod.pk in get_search_product_ids(request, bit)  # Should use cache
Exemplo n.º 13
0
def test_category_product_filters_2(browser, live_server, settings):
    cache.clear()  # Avoid cache from past tests
    shop, first_cat, second_cat, third_cat, first_manufacturer = initialize_db()

    # Activate limit page size changer for the shop
    set_configuration(
        shop=shop,
        data={
            "sort_products_by_name": True,
            "sort_products_by_name_ordering": 1,
            "sort_products_by_price": True,
            "sort_products_by_price_ordering": 2,
            "limit_product_list_page_size": True
        }
    )

    # initialize test and go to front page
    browser = initialize_front_browser_test(browser, live_server)

    # check that front page actually loaded
    wait_until_condition(browser, lambda x: x.is_text_present("Welcome to Default!"))

    url = reverse("E-Commerce:category", kwargs={"pk": first_cat.pk, "slug": first_cat.slug})
    browser.visit("%s%s" % (live_server, url))
    wait_until_condition(browser, lambda x: x.is_text_present("First Category"))
    wait_until_condition(browser, lambda x: x.is_text_present("Sort"))
    assert not browser.is_text_present("Manufacturers")  # Since not in default configuration
    second_category_sort_test(browser, live_server, shop, second_cat)
    second_category_sort_with_price_filter(browser, second_cat)
Exemplo n.º 14
0
def second_category_sort_test(browser, live_server, shop, category):
    url = reverse("E-Commerce:category", kwargs={"pk": category.pk, "slug": category.slug})
    browser.visit("%s%s" % (live_server, url))

    wait_until_condition(browser, lambda x: x.is_element_present_by_css("button[data-id='id_limit']"), timeout=30)
    # Set limit to 24
    click_element(browser, "button[data-id='id_limit']")
    click_element(browser, "button[data-id='id_limit'] + .dropdown-menu li[data-original-index='1'] a")
    wait_until_condition(browser, lambda x: len(x.find_by_css(".product-card")) == 13, timeout=30)

    # Check that visibility change affects the product count
    shop_products = ShopProduct.objects.filter(primary_category_id=category.id)[:3]
    for sp in shop_products:
        sp.visibility = ShopProductVisibility.NOT_VISIBLE
        sp.save()

    cache.clear()
    browser.reload()
    wait_until_condition(browser, lambda x: len(x.find_by_css(".product-card")) == 10)

    for sp in shop_products:
        sp.visibility = ShopProductVisibility.ALWAYS_VISIBLE
        sp.save()

    cache.clear()
    browser.reload()
    wait_until_condition(browser, lambda x: len(x.find_by_css(".product-card")) == 13, timeout=30)
Exemplo n.º 15
0
def initialize_db():
    activate("en")
    # initialize
    cache.clear()
    shop = get_default_shop()

    for name, identifier in CATEGORY_DATA:
        category = Category()
        category.name = name
        category.identifier = identifier
        category.status = CategoryStatus.VISIBLE
        category.save()
        category.shops.add(shop)

    for name, identifier in MANUFACTURER_DATA:
        Manufacturer.objects.create(name=name, identifier=identifier)

    first_cat = Category.objects.filter(identifier="cat-1").first()
    second_cat = Category.objects.filter(identifier="cat-2").first()
    third_cat = Category.objects.filter(identifier="cat-3").first()
    assert first_cat.pk != second_cat.pk
    for name, sku, price in FIRST_CATEGORY_PRODUCT_DATA:
        product = create_orderable_product(name, sku, price=price)
        shop_product = product.get_shop_instance(shop)
        cat = Category.objects.first()
        shop_product.primary_category = first_cat
        shop_product.save()
        shop_product.categories.add(first_cat)

    # Add some variation products
    add_variations(
        shop, Product.objects.filter(sku="test-sku-1").first(),
        ["Black", "Yellow"], ["Big", "Small"]
    )

    add_variations(
        shop, Product.objects.filter(sku="test-sku-2").first(),
        ["Brown", "Pink"], ["S", "L", "XL"]
    )

    add_variations(
        shop, Product.objects.filter(sku="test-sku-3").first(),
        ["Brown", "Black"], ["S", "L", "XL", "Big"]
    )

    for i in range(1, 14):
        product = create_orderable_product("Test product", "sku-%s" % i, price=i)
        shop_product = product.get_shop_instance(shop)
        cat = Category.objects.first()
        shop_product.primary_category = second_cat
        shop_product.save()
        shop_product.categories.add(second_cat)


    # Set manufacturer for first product only
    first_manufacturer = Manufacturer.objects.first()
    Product.objects.filter(sku="test-sku-1").update(manufacturer_id=first_manufacturer.id)

    return shop, first_cat, second_cat, third_cat, first_manufacturer
Exemplo n.º 16
0
def test_shop_instance_cache():
    from E-Commerce.core import cache
    cache.clear()

    shop = get_default_shop()
    product = create_product("product", shop)
    shop_product = product.get_shop_instance(shop)
    assert shop_product == product.get_shop_instance(shop)
Exemplo n.º 17
0
def test_simple_search_no_results(rf):
    cache.clear()
    with translation.override("xx"):  # use built-in translation
        get_default_shop()
        view = SearchView.as_view()
        resp = view(apply_request_middleware(rf.get("/", {"q": UNLIKELY_STRING})))
        assert NO_RESULTS_FOUND_STRING in resp.rendered_content
        resp = view(apply_request_middleware(rf.get("/")))
        assert NO_RESULTS_FOUND_STRING in resp.rendered_content, "No query string no results"
Exemplo n.º 18
0
def test_normalize_spaces(rf):
    cache.clear()
    view = SearchView.as_view()
    create_product(sku=UNLIKELY_STRING, name="Savage Garden", shop=get_default_shop())
    query = "\t Savage \t \t \n \r Garden \n"

    resp = view(apply_request_middleware(rf.get("/")))
    assert query not in resp.rendered_content
    resp = view(apply_request_middleware(rf.get("/", {"q": query})))
    assert query in resp.rendered_content
Exemplo n.º 19
0
def test_basic_order_flow_registered(regular_user):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    get_test_script("test script", "order_received")
    # paths
    addresses_path = reverse("E-Commerce:checkout", kwargs={"phase": "addresses"})
    methods_path = reverse("E-Commerce:checkout", kwargs={"phase": "methods"})
    confirm_path = reverse("E-Commerce:checkout", kwargs={"phase": "confirm"})

    template_data = STEP_DATA[0]["actions"][0]["template_data"]

    LANG_CODE = {
        "en": "US",
        "fi": "FI"
    }

    for lang in ["en", "fi"]:
        n_outbox_pre = len(mail.outbox)
        contact = get_person_contact(regular_user)
        contact.language = lang
        contact.save()

        c = SmartClient()
        c.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD)

        product_ids = _populate_client_basket(c)

        addresses_soup = c.soup(addresses_path)
        address = get_address(country=LANG_CODE[lang])

        inputs = fill_address_inputs(addresses_soup, address)
        response = c.post(addresses_path, data=inputs)
        assert response.status_code == 302  # Should redirect forth

        methods_soup = c.soup(methods_path)
        assert c.post(methods_path, data=extract_form_fields(methods_soup)).status_code == 302  # Should redirect forth

        confirm_soup = c.soup(confirm_path)
        Product.objects.get(pk=product_ids[0]).soft_delete()
        assert c.post(confirm_path, data=extract_form_fields(confirm_soup)).status_code == 200  # user needs to reconfirm
        data = extract_form_fields(confirm_soup)
        data['product_ids'] = ','.join(product_ids[1:])
        assert c.post(confirm_path, data=data).status_code == 302  # Should redirect forth

        n_orders_post = Order.objects.count()
        assert n_orders_post > n_orders_pre, "order was created"
        assert (len(mail.outbox) == n_outbox_pre + 1), "Sending email failed"
        latest_mail = mail.outbox[-1]

        # mail is always sent in fallback language since user is not registered
        assert latest_mail.subject == template_data[lang]["subject"], "Subject doesn't match"
        assert latest_mail.body == template_data[lang]["body"], "Body doesn't match"
Exemplo n.º 20
0
def init():
    if caching_enabled == "true":
        cache.clear()

    #Create the DB schmea if it doesn't exist
    postgres.createSchema()

    #Add init data if it doesn't exist
    data = getData()
    if len(data) == 0:
        insertInitData()
Exemplo n.º 21
0
def test_simple_search_view_works(rf):
    cache.clear()
    view = SearchView.as_view()
    prod = create_product(sku=UNLIKELY_STRING, shop=get_default_shop())
    query = prod.name[:8]

    # This test is pretty cruddy. TODO: Un-cruddify this test.
    resp = view(apply_request_middleware(rf.get("/")))
    assert query not in resp.rendered_content
    resp = view(apply_request_middleware(rf.get("/", {"q": query})))
    assert query in resp.rendered_content
Exemplo n.º 22
0
def test_xtheme_snippet_injection(browser, admin_user, live_server, settings):
    shop = factories.get_default_shop()
    initialize_admin_browser_test(browser, live_server, settings)

    url = reverse("E-Commerce_admin:xtheme_snippet.new")
    browser.visit("%s%s" % (live_server, url))
    wait_until_condition(browser, lambda x: x.is_text_present("New Snippet"))
    browser.execute_script("$(\"[name='location']\").val('body_end').trigger('change')")
    browser.execute_script("$(\"[name='snippet_type']\").val('inline_js').trigger('change')")
    browser.execute_script("window.CodeMirror.editors['id_snippet-snippet'].setValue('alert(\"works\")');")
    click_element(browser, "button[type='submit']")
    wait_until_appeared(browser, "div[class='message success']")

    url = reverse("E-Commerce:index")
    browser.visit("%s%s" % (live_server, url))

    def has_alert(browser):
        try:
            return browser.get_alert().text == "works"
        except:
            return False

    wait_until_condition(browser, has_alert)
    browser.get_alert().accept()

    theme = get_current_theme(shop)
    snippet = Snippet.objects.filter(shop=shop).first()
    snippet.themes = [theme.identifier]
    snippet.save()

    cache.clear()
    browser.visit("%s%s" % (live_server, url))
    wait_until_condition(browser, has_alert)
    browser.get_alert().accept()

    snippet.themes = ["doesnt-exist"]
    snippet.save()

    cache.clear()
    browser.visit("%s%s" % (live_server, url))
    wait_until_condition(browser, lambda x: x.is_text_present("Welcome to Default!"))

    with pytest.raises(Exception):
        browser.get_alert()

    # delete the snippet
    url = reverse("E-Commerce_admin:xtheme_snippet.edit", kwargs=dict(pk=snippet.pk))
    browser.visit("%s%s" % (live_server, url))
    assert Snippet.objects.filter(shop=shop).exists()

    click_element(browser, ".E-Commerce-toolbar button.btn.btn-danger")
    browser.get_alert().accept()
    wait_until_condition(browser, lambda x: not Snippet.objects.filter(shop=shop).exists())
def test_cross_sell_plugin_count():
    shop = get_default_shop()
    supplier = get_default_supplier()
    product = create_product("test-sku", shop=shop, supplier=supplier)
    context = get_jinja_context(product=product)
    total_count = 5
    trim_count = 3

    type = ProductCrossSellType.RELATED
    _create_cross_sell_products(product, shop, supplier, type, total_count)
    assert ProductCrossSell.objects.filter(product1=product, type=type).count() == total_count
    cache.clear()
    assert len(list(product_helpers.get_product_cross_sells(context, product, type, trim_count))) == trim_count
Exemplo n.º 24
0
def test_category_product_filters_4(browser, live_server, settings):
    """
    Do not show manufacturer option if there is any product
    """
    cache.clear()  # Avoid cache from past tests
    shop, first_cat, second_cat, third_cat, first_manufacturer = initialize_db()

    # remove manufacturers from all products
    Product.objects.all().update(manufacturer=None)
    # show manufacturer filter
    set_configuration(
        category=first_cat,
        data={
            "override_default_configuration": True,
            "sort_products_by_name": True,
            "sort_products_by_name_ordering": 1,
            "sort_products_by_price": True,
            "sort_products_by_price_ordering": 2,
            "filter_products_by_manufacturer": True
        }
    )

    # initialize test and go to front page
    browser = initialize_front_browser_test(browser, live_server)

    # check that front page actually loaded
    wait_until_condition(browser, lambda x: x.is_text_present("Welcome to Default!"))

    url = reverse("E-Commerce:category", kwargs={"pk": first_cat.pk, "slug": first_cat.slug})
    browser.visit("%s%s" % (live_server, url))
    wait_until_condition(browser, lambda x: x.is_text_present("First Category"))
    wait_until_condition(browser, lambda x: x.is_text_present("Sort"))
    assert not browser.is_text_present("Manufacturers")  # Since there is no product with manufacturer

    # add the manufacturer to the last product so the manufacturer filter is show
    last_product = Product.objects.last()
    last_product.manufacturer = first_manufacturer
    last_product.save()
    browser.visit("%s%s" % (live_server, url))
    assert browser.is_text_present("Manufacturers")

    # set the shop product hidden
    shop_product = last_product.get_shop_instance(shop)
    shop_product.visibility = ShopProductVisibility.NOT_VISIBLE
    shop_product.save()

    # the manufacturer filter is removed
    browser.visit("%s%s" % (live_server, url))
    assert not browser.is_text_present("Manufacturers")
Exemplo n.º 25
0
def test_simple_search_with_non_public_products(rf):
    cache.clear()
    shop = get_default_shop()
    name = "Some Test Name For Product"
    product = create_product("sku", name=name, shop=shop)
    shop_product = product.get_shop_instance(shop)
    shop_product.visibility = ShopProductVisibility.SEARCHABLE
    shop_product.visibility_limit = ProductVisibility.VISIBLE_TO_LOGGED_IN
    shop_product.save()

    view = SearchView.as_view()
    request = apply_request_middleware(rf.get("/", {"q": "Test name"}))
    request.customer = create_random_person()
    resp = view(request)
    assert bool(name in resp.rendered_content)
Exemplo n.º 26
0
def test_product_searchability(rf, visibility, show_in_search):
    cache.clear()
    view = SearchView.as_view()
    name = "Savage Garden"
    sku = UNLIKELY_STRING

    shop = get_default_shop()
    product = create_product(sku, name=name, shop=shop)
    shop_product = product.get_shop_instance(shop)

    shop_product.visibility = visibility
    shop_product.save()

    resp = view(apply_request_middleware(rf.get("/", {"q": "savage"})))
    assert (name in resp.rendered_content) == show_in_search
Exemplo n.º 27
0
def test_checkout_empty_basket(rf):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    c = SmartClient()
    product_ids = _populate_client_basket(c)
    addresses_path = reverse("E-Commerce:checkout", kwargs={"phase": "addresses"})
    addresses_soup = c.soup(addresses_path)
    inputs = fill_address_inputs(addresses_soup)
    for product_id in product_ids:
        Product.objects.get(pk=product_id).soft_delete()
    response, soup = c.response_and_soup(addresses_path, data=inputs, method="post")
    assert response.status_code == 200  # Should redirect forth
    assert b"Your shopping cart is empty." in soup.renderContents()
def test_bought_with_template_helper():
    shop = get_default_shop()
    supplier = get_default_supplier()
    product = create_product("test-sku", shop=shop, supplier=supplier)
    context = get_jinja_context(product=product)

    type = ProductCrossSellType.COMPUTED
    visible_count = 10
    hidden_count = 4
    _create_cross_sell_products(product, shop, supplier, type, visible_count)
    _create_cross_sell_products(product, shop, supplier, type, hidden_count, hidden=True)
    assert ProductCrossSell.objects.filter(product1=product, type=type).count() == (visible_count + hidden_count)

    # Make sure quantities returned by plugin match
    cache.clear()
    assert len(list(product_helpers.get_products_bought_with(context, product, visible_count))) == visible_count
Exemplo n.º 29
0
def test_get_sorts_and_filters(rf):
    context = get_jinja_context()

    supplier = get_default_supplier()
    shop = get_default_shop()
    product1 = create_product("product1", shop, supplier, 10)
    product2 = create_product("product2", shop, supplier, 20)

    request = apply_request_middleware(rf.get("/"))
    queryset = Product.objects.all()

    cache.clear()
    for time in range(2):
        products = list(get_product_queryset(queryset, request, None, {}))
        assert len(products) == 2
        assert product1 in products
        assert product2 in products
Exemplo n.º 30
0
def test_variation_templates(browser, admin_user, live_server, settings):
    cache.clear()  # Avoid cache from past tests
    shop = get_default_shop()
    configuration_key = "saved_variation_templates"
    assert configuration.get(shop, configuration_key, None) is None
    product = create_product("test_sku", shop, default_price=10, mode=ProductMode.VARIABLE_VARIATION_PARENT)
    assert product.is_variation_parent()
    initialize_admin_browser_test(browser, live_server, settings)
    browser.driver.set_window_size(800, 1000)
    url = reverse("E-Commerce_admin:shop_product.edit_variation", kwargs={"pk": product.pk})
    browser.visit("%s%s" % (live_server, url + "#variables-section"))
    click_element(browser, '#variables-section > div:nth-child(1) > a:nth-child(2)')
    wait_until_condition(browser, lambda x: x.is_text_present("New template"))

    assert len(ProductVariationVariable.objects.filter(product=product)) == 0 # Size
    assert len(ProductVariationVariableValue.objects.all()) == 0  # Assert no variations are active
    click_element(browser, '.fa.fa-plus')

    wait_until_condition(browser, lambda x: x.is_text_present("New template"))
    browser.fill("variables-template_name", printable_gibberish())  # variables-template_name
    click_element(browser, '#save_template_name')
    wait_until_condition(browser, lambda x: not x.is_text_present("New template"))
    assert len(configuration.get(shop, configuration_key, [])) == 1
    click_element(browser, '#variables-section > div:nth-child(1) > a:nth-child(2)')
    click_element(browser, "#variation-variable-editor")
    browser.find_by_xpath('//*[@id="variation-variable-editor"]/div/div/select/option[2]').first.click()
    wait_until_condition(browser, lambda x: x.is_text_present("Add new variable"))
    click_element(browser, ".btn.btn-lg.btn-text")
    browser.find_by_xpath('//*[@id="product-variable-wrap"]/div/div[2]/div[1]/table/tbody[1]/tr/td[1]/input').first.fill("Size")
    click_element(browser, ".btn.btn-xs.btn-text")
    browser.find_by_xpath('//*[@id="product-variable-wrap"]/div/div[2]/div[1]/table/tbody[2]/tr/td[1]/input').first.fill("S")
    click_element(browser, "#id_variables-activate_template")  # Activate template
    click_element(browser, ".fa.fa-check-circle")  # Save

    assert len(ProductVariationVariable.objects.filter(product=product)) == 1 # Size
    assert len(ProductVariationVariableValue.objects.all()) == 1  # S

    click_element(browser, '#variables-section > div:nth-child(1) > a:nth-child(2)')
    click_element(browser, "#variation-variable-editor") # id_variables-data
    cache.clear()  # Avoid cache from past tests
    assert len(configuration.get(shop, configuration_key, [])) == 1

    browser.find_by_xpath('//*[@id="variation-variable-editor"]/div/div/select/option[2]').first.click()
    template_data = configuration.get(shop, configuration_key, [])[0].get('data')[0]
    browser_data = json.loads(browser.find_by_css("#id_variables-data").value).get('variable_values')[0]
    assert browser_data == template_data  # assert shown template data matches template data in the db
Exemplo n.º 31
0
    def test_cache_timing(self):
        """ Bit of a wonky test: test actual caching by comparing time
        to load a page uncached and time to load it cached. The latter
        should be shorter.
        Might fail with a false negative if filesystem is being slow 
        at the moment, but in general it should work pretty well. """

        page = "Melbourne"
        cache.clear(page)

        time1 = time.time()
        climate.get_climate_data(page)
        time_with_no_cache = time.time() - time1

        time2 = time.time()
        climate.get_climate_data(page)
        time_with_cache = time.time() - time2

        self.assertTrue(time_with_cache < time_with_no_cache)
Exemplo n.º 32
0
Arquivo: tdb.py Projeto: epu/rsvndump
def main():
	# Parse arguments
	if len(sys.argv) < 2:
		print_help()
		return 1
	action = sys.argv[1]

	if action == "help":
		if len(sys.argv) > 2:
			print_help(sys.argv[2])
		else:
			print_help()
		return 0
	elif action == "list":
		for t in test.all_tests():
			print(t+" - "+test.info(t))
	elif action == "run":
		args = []
		tests = [sys.argv[2]]
		if len(sys.argv) > 3:
			args = sys.argv[3:]
		return runtests(tests, args)
	elif action == "all":
		args = []
		tests = test.all_tests()
		if len(sys.argv) > 2:
			args = sys.argv[2:]
		return runtests(tests, args)
	elif action == "clear":
		test.cleanup()
		if len(sys.argv) > 2 and sys.argv[2] == "--cache":
			cache.clear()
	else:
		print("Unkown command "+action)
		return 1
	return 0
Exemplo n.º 33
0
    def test_cache_clear(self):
        """ Test cache clearing by downloading a page (and thus 
        creating the cached version), then asking for it to be cleared,
        and checking if the file still exists """

        # download a test page first - make sure it is cached
        climate.get_climate_data("Melbourne")

        # clear, and see if it reports successful
        paths = cache.clear("Melbourne")
        self.assertEqual(cache.exists("Melbourne"), False)

        # check if file physically exists
        for path in paths:
            self.assertFalse(os.path.exists(path))
Exemplo n.º 34
0
                print batch
                batcher.track(batch, remote, debug)
        elif (action == "review"):
            batch_ = batcher.interpret_batches(study, portfolio, batches, remote)
            for batch in batch_:
                print batch
                batcher.review(batch, remote, debug)
        elif (action == "dump" or action == "export"):
            key = util.get_str_input("key (report) : ", "report")
            xpath = util.get_str_input("xpath () : ", "")
            showParams = util.get_bool_input("show search values (false) : ", False)
            batch_ = batcher.interpret_batches(study, portfolio, batches, remote)
            batcher.dump_multiple(study, portfolio, batch_, remote, key, xpath, action == "export", showParams)
        elif (action == "clear"):
            key = util.get_str_input("key (batch/%s-%s) : " % (study, portfolio), "batch/%s-%s" % (study, portfolio))
            if (remote):
                k = cloud.call(cache.delete_prefix, key)
                logging.info(k)
            else:
                cache.clear(key, False)
        elif (action == "quit"):
            sys.exit()
        else:
            print "action %s unknown" % action
    except (KeyboardInterrupt):
        pass
        print ""
    except:
        print sys.exc_info()
        pass
Exemplo n.º 35
0
def ClearCache():
	cache.clear(['cookies', 'pages'])
Exemplo n.º 36
0
def vanilla_site(parent, name, db_name, base_url=None, rewrite_base=None):
    """Setup a complete, vanilla Drupal install

    Download Drupal, configure the settings.php database file, configure
    the .htaccess file, and then populate the database with the default
    Drupal structure.

    Args:
        parent: Parent directory where the site will be created
        name: Directory name for the site
        db_name: Name of the database that will be created for this site
        base_url: Base URL value to write in the settings.php file.
            If left blank, this value will remain commented out in settings.php
            ( default=None )
        rewrite_base: RewriteBase value to write in the .htaccess file.
            If left blank, this value will remain commented out in .htaccess
            ( default=None )

    Usage:
        $ fab -H 127.0.0.1 vanilla_site:'/path/to/web/dir','vanilla','drupal_vanilla'

        Will create a site at /path/to/web/dir/vanilla on your local machine.
        It will create a database called drupal_vanilla, populating with with
        the base Drupal tables.

        $ fab -H example.com vanilla_site:'/var/www/html,'special','drupal_dev_01','http://www.example.com/special','/special'

        Will create a site at http://example.com/special with the appropriate
        Apache config options to make it work in a sub-directory. Results
        will depend on your Apache configuration.
    """

    # TODO check for trailing slash
    path = parent + '/' + name

    print _header("Checking dependencies")
    if exists(path):
        warning = """
A folder already exists at your destination path.

Do you wish to overwrite?
"""
        confirm_overwrite(warning)
        run("chmod -R u+w %s" % path)
        run("rm -rf %s" % path)

    if db.mysql_cnf_password_set():
        password = db.get_mysql_pass()
        print
        print green("You're ready to build a Drupal site.")
        print
    else:
        exit('No MySQL credentials were found. Quitting.')

    print _header("Downloading Drupal.")
    download(parent, name)

    print _header("Configuring the RewriteBase in the .htaccess file.")
    rewrite_base_enable(path, rewrite_base)

    print _header("Making the files directory and a settings.php file")
    files.setup_files(path)
    files.setup_settings(path, db_name)

    print _header("Creating the database and loading Drupal structure.")
    site_install(path, 'bkennedy', password, '127.0.0.1', db_name)

    with cd(path):
        cache.clear()

    print _header("Your Drupal site is ready to go.")
Exemplo n.º 37
0
Arquivo: wiki.py Projeto: joshz/weeki
 def get(self):
     cache.clear()
     self.redirect('/')