Ejemplo n.º 1
0
def test_category_links_plugin_with_customer(rf, show_all_categories):
    """
    Test plugin for categories that is visible for certain group
    """
    shop = get_default_shop()
    group = get_default_customer_group()
    customer = create_random_person()
    customer.groups.add(group)
    customer.save()

    request = rf.get("/")
    request.shop = get_default_shop()
    apply_request_middleware(request)
    request.customer = customer

    category = get_default_category()
    category.status = CategoryStatus.VISIBLE
    category.visibility = CategoryVisibility.VISIBLE_TO_GROUPS
    category.visibility_groups.add(group)
    category.shops.add(shop)
    category.save()

    vars = {"request": request}
    context = get_jinja_context(**vars)
    plugin = CategoryLinksPlugin({"categories": [category.pk], "show_all_categories": show_all_categories})
    assert category.is_visible(customer)
    assert category in plugin.get_context_data(context)["categories"]

    customer_without_groups = create_random_person()
    customer_without_groups.groups.clear()

    assert not category.is_visible(customer_without_groups)
    request.customer = customer_without_groups
    context = get_jinja_context(**vars)
    assert category not in plugin.get_context_data(context)["categories"]
def get_request_for_contact_tests(rf):
    activate("en")
    request = rf.get("/")
    request.shop = get_shop(prices_include_tax=True)
    get_payment_method(request.shop)
    apply_request_middleware(request)
    return request
Ejemplo n.º 3
0
def get_request_for_contact_tests(rf):
    activate("en")
    request = rf.get("/")
    request.shop = get_shop(prices_include_tax=True)
    get_payment_method(request.shop)
    apply_request_middleware(request)
    return request
Ejemplo n.º 4
0
def test_user_detail_contact_seed(rf):
    get_default_shop()
    contact = create_random_person()

    # Using random data for name and email would need escaping when
    # checking if it is rendered, therefore use something very basic instead
    contact.name = "Matti Perustyyppi"
    contact.email = "*****@*****.**"
    contact.save()

    view_func = UserDetailView.as_view()
    # Check that fields populate . . .
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}))
    response = view_func(request)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
    # POST the password too to create the user . . .
    post = extract_form_fields(BeautifulSoup(content))
    post["password"] = "******"
    request.method = "POST"
    request.POST = post
    response = view_func(request)
    assert response.status_code < 500
    # Check this new user is visible in the details now
    user = Contact.objects.get(pk=contact.pk).user
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}))
    response = view_func(request, pk=user.pk)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
Ejemplo n.º 5
0
def test_basket_shipping_error(rf):
    StoredBasket.objects.all().delete()
    shop = get_default_shop()
    supplier = get_default_supplier()
    shipped_product = create_product(
        printable_gibberish(), shop=shop, supplier=supplier, default_price=50,
        shipping_mode=ShippingMode.SHIPPED
    )
    unshipped_product = create_product(
        printable_gibberish(), shop=shop, supplier=supplier, default_price=50,
        shipping_mode=ShippingMode.NOT_SHIPPED
    )

    request = rf.get("/")
    request.session = {}
    request.shop = shop
    apply_request_middleware(request)
    basket = get_basket(request)

    # With a shipped product but no shipping methods, we oughta get an error
    basket.add_product(supplier=supplier, shop=shop, product=shipped_product, quantity=1)
    assert any(ve.code == "no_common_shipping" for ve in basket.get_validation_errors())
    basket.clear_all()

    # But with an unshipped product, we should not
    basket.add_product(supplier=supplier, shop=shop, product=unshipped_product, quantity=1)
    assert not any(ve.code == "no_common_shipping" for ve in basket.get_validation_errors())
Ejemplo n.º 6
0
def test_user_detail_contact_seed(rf):
    get_default_shop()
    contact = create_random_person()

    # Using random data for name and email would need escaping when
    # checking if it is rendered, therefore use something very basic instead
    contact.name = "Matti Perustyyppi"
    contact.email = "*****@*****.**"
    contact.save()

    view_func = UserDetailView.as_view()
    # Check that fields populate . . .
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}))
    response = view_func(request)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
    # POST the password too to create the user . . .
    post = extract_form_fields(BeautifulSoup(content))
    post["password"] = "******"
    request.method = "POST"
    request.POST = post
    response = view_func(request)
    assert response.status_code < 500
    # Check this new user is visible in the details now
    user = Contact.objects.get(pk=contact.pk).user
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}))
    response = view_func(request, pk=user.pk)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
def init_test(request, shop, prices):
    apply_request_middleware(request)
    parent = create_product("parent_product", shop=shop)
    children = [create_product("child-%d" % price, shop=shop, default_price=price) for price in prices]
    for child in children:
        child.link_to_parent(parent)
    return parent
Ejemplo n.º 8
0
def initialize_test(rf):
    shop = get_default_shop()
    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    product1 = create_product("test-product1", shop=shop, default_price=120)
    product2 = create_product("test-product2", shop=shop, default_price=180)
    return (request, [product1, product2], shop.create_price)
def initialize_test(rf):
    shop = get_default_shop()
    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    product1 = create_product("test-product1", shop=shop, default_price=120)
    product2 = create_product("test-product2", shop=shop, default_price=180)
    return (request, [product1, product2], shop.create_price)
Ejemplo n.º 10
0
def test_modules_in_core_admin_work(rf, admin_user):
    get_default_shop()
    request = rf.get("/")
    apply_request_middleware(request, user=admin_user)
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    with replace_modules(ShoopAdminAppConfig.provides["admin_module"]):
        assert all(get_module_urls())
        assert get_menu_entry_categories(request)
Ejemplo n.º 11
0
def get_context(rf, customer=None):
    request = rf.get("/")
    request.shop = get_default_shop()
    apply_request_middleware(request)
    if customer:
        request.customer = customer
    vars = {"request": request}
    return get_jinja_context(**vars)
Ejemplo n.º 12
0
def test_modules_in_core_admin_work(rf, admin_user):
    get_default_shop()
    request = rf.get("/")
    apply_request_middleware(request, user=admin_user)
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    with replace_modules(ShoopAdminAppConfig.provides["admin_module"]):
        assert all(get_module_urls())
        assert get_menu_entry_categories(request)
Ejemplo n.º 13
0
def test_simple_search_no_results(rf):
    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 not in resp.rendered_content
Ejemplo n.º 14
0
def test_basket(rf, storage):
    StoredBasket.objects.all().delete()
    quantities = [3, 12, 44, 23, 65]
    shop = get_default_shop()
    get_default_payment_method(
    )  # Can't create baskets without payment methods
    supplier = get_default_supplier()
    products_and_quantities = []
    for quantity in quantities:
        product = create_product(printable_gibberish(),
                                 shop=shop,
                                 supplier=supplier,
                                 default_price=50)
        products_and_quantities.append((product, quantity))

    is_database = (
        storage == "shoop.front.basket.storage:DatabaseBasketStorage")
    with override_settings(SHOOP_BASKET_STORAGE_CLASS_SPEC=storage):
        for product, q in products_and_quantities:
            request = rf.get("/")
            request.session = {}
            request.shop = shop
            apply_request_middleware(request)
            basket = get_basket(request)
            assert basket == request.basket
            assert basket.product_count == 0
            line = basket.add_product(supplier=supplier,
                                      shop=shop,
                                      product=product,
                                      quantity=q)
            assert line.quantity == q
            assert basket.get_lines()
            assert basket.get_product_ids_and_quantities().get(product.pk) == q
            assert basket.product_count == q
            basket.save()
            delattr(request, "basket")
            basket = get_basket(request)
            assert basket.get_product_ids_and_quantities().get(product.pk) == q
            if is_database:
                product_ids = set(
                    StoredBasket.objects.last().products.values_list(
                        "id", flat=True))
                assert product_ids == set([product.pk])

        if is_database:
            stats = StoredBasket.objects.all().aggregate(
                n=Sum("product_count"),
                tfs=Sum("taxful_total_price_value"),
                tls=Sum("taxless_total_price_value"),
            )
            assert stats["n"] == sum(quantities)
            if shop.prices_include_tax:
                assert stats["tfs"] == sum(quantities) * 50
            else:
                assert stats["tls"] == sum(quantities) * 50

        basket.finalize()
Ejemplo n.º 15
0
def test_simple_search_no_results(rf):
    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 not in resp.rendered_content
Ejemplo n.º 16
0
def test_simple_search_view_works(rf):
    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
Ejemplo n.º 17
0
def test_simple_search_view_works(rf):
    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
Ejemplo n.º 18
0
def test_basic_order(rf, admin_user, mode):
    prices_include_tax = (mode == "taxful")
    shop = get_shop(prices_include_tax=prices_include_tax)

    request = rf.get('/')
    request.shop = shop
    apply_request_middleware(request)
    product = get_default_product()
    customer = get_person_contact(admin_user)
    for x in range(10):
        create_order(request, creator=admin_user, customer=customer, product=product)
    assert Order.objects.filter(customer=customer).count() == 10
Ejemplo n.º 19
0
def test_basic_order(rf, admin_user, mode):
    prices_include_tax = (mode == "taxful")
    shop = get_shop(prices_include_tax=prices_include_tax)

    request = rf.get('/')
    request.shop = shop
    apply_request_middleware(request)
    product = get_default_product()
    customer = get_person_contact(admin_user)
    for x in range(10):
        create_order(request, creator=admin_user, customer=customer, product=product)
    assert Order.objects.filter(customer=customer).count() == 10
Ejemplo n.º 20
0
def initialize_test(rf, include_tax=False):
    shop = get_shop_with_tax(include_tax=include_tax)

    group = get_default_customer_group()
    customer = create_random_person()
    customer.groups.add(group)
    customer.save()

    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    request.customer = customer
    return request, shop, group
def initialize_test(rf, include_tax=False):
    shop = get_shop_with_tax(include_tax=include_tax)

    group = get_default_customer_group()
    customer = create_random_person()
    customer.groups.add(group)
    customer.save()

    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    request.customer = customer
    return request, shop, group
Ejemplo n.º 22
0
def test_contact_set_is_active(rf, admin_user):
    get_default_shop()
    contact = create_random_person(locale="en_US", minimum_name_comp_len=5)
    assert contact.is_active

    request = apply_request_middleware(rf.post("/", {"set_is_active": "0"}), user=admin_user)
    view_func = ContactDetailView.as_view()
    response = view_func(request, pk=contact.pk)
    assert response.status_code < 500 and not Contact.objects.get(pk=contact.pk).is_active

    request = apply_request_middleware(rf.post("/", {"set_is_active": "1"}), user=admin_user)
    view_func = ContactDetailView.as_view()
    response = view_func(request, pk=contact.pk)
    assert response.status_code < 500 and Contact.objects.get(pk=contact.pk).is_active
Ejemplo n.º 23
0
def initialize_test(rf, include_tax=False):
    activate("en")
    shop = get_shop(prices_include_tax=include_tax)
    get_default_payment_method()  # Valid baskets needs some payment methods to be available

    group = get_default_customer_group()
    customer = create_random_person()
    customer.groups.add(group)
    customer.save()

    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    request.customer = customer
    return request, shop, group
Ejemplo n.º 24
0
def test_order_source_parentage(rf, admin_user):
    source = seed_source(admin_user)
    product = get_default_product()
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=product,
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
        line_id="parent"
    )
    source.add_line(
        type=OrderLineType.OTHER,
        text="Child Line",
        sku="KIDKIDKID",
        quantity=1,
        base_unit_price=source.create_price(5),
        parent_line_id="parent"
    )
    request = apply_request_middleware(rf.get("/"))

    creator = OrderCreator(request)
    order = Order.objects.get(pk=creator.create_order(source).pk)
    kid_line = order.lines.filter(sku="KIDKIDKID").first()
    assert kid_line
    assert kid_line.parent_line.product_id == product.pk
Ejemplo n.º 25
0
def test_order_creator_view_invalid_command(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get(
        "/", {"command": printable_gibberish()}),
                                       user=admin_user)
    response = OrderCreateView.as_view()(request)
    assert_contains(response, "unknown command", status_code=400)
Ejemplo n.º 26
0
def test_campaign_end_date(rf, admin_user):
    """
    To make things little bit more simple let's use only english as
    a language.
    """
    with override_settings(LANGUAGES=[("en", "en")]):
        shop = get_default_shop()
        old_name = "test_campaign"
        object = CatalogCampaign.objects.create(name=old_name, active=True, shop=shop)
        object.save()
        view = CatalogCampaignEditView.as_view()
        new_name = "Test Campaign"
        assert object.name != new_name
        data = {
            "base-name": new_name,
            "base-public_name__en": "Test Campaign",
            "base-shop": get_default_shop().id,
            "base-active": True,
            "base-basket_line_text": "Test campaign activated!",
            "base-start_datetime": datetime.datetime(year=2016, month=6, day=19),
            "base-end_datetime": datetime.datetime(year=2016, month=6, day=10)
        }
        methods_before = CatalogCampaign.objects.count()
        # Conditions, effects and effects is tested separately
        with override_provides("campaign_context_condition", []):
            with override_provides("campaign_catalog_filter", []):
                with override_provides("catalog_campaign_effect", []):
                    request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
                    response = view(request, pk=object.pk)
                    assert response.status_code in [200, 302]
                    content = response.render().content.decode("utf-8")
                    assert "Campaign end date can&#39;t be before start date." in content
        assert CatalogCampaign.objects.count() == methods_before
        assert CatalogCampaign.objects.get(pk=object.pk).name == old_name
Ejemplo n.º 27
0
def test_order_creation_adds_usage(rf, admin_user):
    request, shop, group = initialize_test(rf, False)

    source = seed_source(admin_user)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=get_default_product(),
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    source.add_line(
        type=OrderLineType.OTHER, quantity=1, base_unit_price=source.create_price(10), require_verification=True
    )

    # add coupon
    coupon = Coupon.objects.create(active=True, code="asdf")

    campaign = BasketCampaign.objects.create(
        active=True, shop=shop, name="test", public_name="test", discount_percentage="0.1", coupon=coupon
    )

    source.add_code(coupon.code)

    request = apply_request_middleware(rf.get("/"))
    creator = OrderCreator(request)
    order = creator.create_order(source)

    assert CouponUsage.objects.count() == 1
Ejemplo n.º 28
0
def test_method_edit_save(rf, admin_user, view, model, get_object,
                          service_provider_attr):
    """
    To make things little bit more simple let's use only english as
    an language.
    """
    with override_settings(LANGUAGES=[("en", "en")]):
        object = get_object()
        object.choice_identifier = ""
        object.save()
        assert object.choice_identifier == ""
        view = view.as_view()
        service_provider_attr_field = "base-%s" % service_provider_attr
        data = {
            "base-name__en": object.name,
            "base-shop": object.shop.id,
            "base-tax_class": object.tax_class.id,
            "base-enabled": True,
            service_provider_attr_field: getattr(object,
                                                 service_provider_attr).pk,
            "base-choice_identifier": "manual"
        }
        methods_before = model.objects.count()
        # Behavior components is tested at shoop.tests.admin.test_service_behavior_components
        with override_provides("service_behavior_component_form", []):
            request = apply_request_middleware(rf.post("/", data=data),
                                               user=admin_user)
            response = view(request, pk=object.pk)
            if hasattr(response, "render"):
                response.render()
            assert response.status_code in [200, 302]

        assert model.objects.count() == methods_before
        assert model.objects.get(pk=object.pk).choice_identifier == "manual"
Ejemplo n.º 29
0
def test_form_populate_initial_data(rf, admin_user):
    shop = get_default_shop()
    supplier = get_default_supplier()

    campaign = BasketCampaign(discount_percentage=0.1, shop=shop)
    campaign.save()

    # Test that correct initial value is returned for non-many-to-many field
    product_amount_initial = 10
    product_amount_condition = BasketTotalProductAmountCondition(product_count=product_amount_initial)
    product_amount_condition.save()
    campaign.conditions.add(product_amount_condition)

    products_count_initial = 5
    for i in range(products_count_initial):
        create_product(printable_gibberish(), shop=shop, supplier=supplier, default_price="20")
    products_initial = Product.objects.all()[:products_count_initial]
    assert len(products_initial) == products_count_initial

    # Test that correct initial value is returned for many-to-many field
    products_in_basket_condition = ProductsInBasketCondition.objects.create()
    products_in_basket_condition.values = products_initial
    products_in_basket_condition.save()
    campaign.conditions.add(products_in_basket_condition)

    assert len(campaign.conditions.all()) == 2

    request=apply_request_middleware(rf.get("/"), user=admin_user)
    form = BasketCampaignForm(request=request, instance=campaign)
    assert form.fields["basket_product_condition"].initial == product_amount_initial
    assert set(form.fields["basket_products_condition"].initial) == set([p.pk for p in products_initial])
def test_behavior_delete_save(rf, admin_user, view, model, get_object, service_provider_attr):
    """
    Only testing one initial behavior component
    """
    get_default_shop()
    with override_settings(LANGUAGES=[("en", "en")]):
        object = get_object()
        view = view.as_view()
        service_provider_attr_field = "base-%s" % service_provider_attr

        component = WeightLimitsBehaviorComponent.objects.create(min_weight=0, max_weight=1)
        object.behavior_components.add(component)
        components_before = object.behavior_components.count()
        assert components_before == 1

        data = get_default_data(object, service_provider_attr, service_provider_attr_field, delete=True)
        data["weightlimitsbehaviorcomponent-0-id"] = component.id
        data["weightlimitsbehaviorcomponent-INITIAL_FORMS"] = 1
        data["weightlimitsbehaviorcomponent-TOTAL_FORMS"] = 2

        request = apply_request_middleware(rf.post("/", data=data, user=admin_user))
        response = view(request, pk=object.pk)
        if hasattr(response, "render"):
            response.render()
        components_after = object.behavior_components.count()
        assert not components_after

        assert not WaivingCostBehaviorComponent.objects.first()
Ejemplo n.º 31
0
def test_method_edit_save(rf, admin_user, view, model, get_object, service_provider_attr):
    """
    To make things little bit more simple let's use only english as
    an language.
    """
    with override_settings(LANGUAGES=[("en", "en")]):
        object = get_object()
        object.choice_identifier = ""
        object.save()
        assert object.choice_identifier == ""
        view = view.as_view()
        service_provider_attr_field = "base-%s" % service_provider_attr
        data = {
            "base-name__en": object.name,
            "base-shop": object.shop.id,
            "base-tax_class": object.tax_class.id,
            "base-enabled": True,
            service_provider_attr_field: getattr(object, service_provider_attr).pk,
            "base-choice_identifier": "manual"
        }
        methods_before = model.objects.count()
        # Behavior components is tested at shoop.tests.admin.test_service_behavior_components
        with override_provides("service_behavior_component_form", []):
            request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
            response = view(request, pk=object.pk)
            if hasattr(response, "render"):
                response.render()
            assert response.status_code in [200, 302]

        assert model.objects.count() == methods_before
        assert model.objects.get(pk=object.pk).choice_identifier == "manual"
Ejemplo n.º 32
0
def test_order_creation_adds_usage(rf, admin_user):
    request, shop, group = initialize_test(rf, False)

    source = seed_source(admin_user)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=get_default_product(),
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    source.add_line(
        type=OrderLineType.OTHER,
        quantity=1,
        base_unit_price=source.create_price(10),
        require_verification=True,
    )

    # add coupon
    coupon = Coupon.objects.create(active=True, code="asdf")

    BasketCampaign.objects.create(active=True,
                                  shop=shop,
                                  name="test",
                                  public_name="test",
                                  discount_percentage="0.1",
                                  coupon=coupon)

    source.add_code(coupon.code)

    request = apply_request_middleware(rf.get("/"))
    creator = OrderCreator(request)
    creator.create_order(source)

    assert CouponUsage.objects.count() == 1
Ejemplo n.º 33
0
def test_contact_details_view_with_many_groups(rf, admin_user):
    get_default_shop()
    person = create_random_person()
    person.groups.add(
        ContactGroup.objects.create(name="Czz Group"),
        ContactGroup.objects.create(name="Azz Group"),
        ContactGroup.objects.create(name="Bzz Group"),
        ContactGroup.objects.language('fi').create(name="Dzz ryhmä"),
    )

    # Group with name in two languages
    grp_e = ContactGroup.objects.language('en').create(name="Ezz Group")
    grp_e.set_current_language('fi')
    grp_e.name = "Ezz ryhmä"
    grp_e.save()
    person.groups.add(grp_e)

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    with translation.override('en'):
        view_func = ContactDetailView.as_view()
        response = view_func(request, pk=person.pk)
    content = response.render().content.decode('utf-8')
    assert "Azz Group" in content
    assert "Bzz Group" in content
    assert "Czz Group" in content
    assert "Dzz ryhmä" in content, "no name in active language, still present"
    assert "Ezz Group" in content, "rendered with active language"
    positions = [content.index(x + "zz ") for x in 'ABCDE']
    assert positions == sorted(positions), "Groups are sorted"
    assert response.status_code == 200
Ejemplo n.º 34
0
def test_behavior_delete_save(rf, admin_user, view, model, get_object,
                              service_provider_attr):
    """
    Only testing one initial behavior component
    """
    get_default_shop()
    with override_settings(LANGUAGES=[("en", "en")]):
        object = get_object()
        view = view.as_view()
        service_provider_attr_field = "base-%s" % service_provider_attr

        component = WeightLimitsBehaviorComponent.objects.create(min_weight=0,
                                                                 max_weight=1)
        object.behavior_components.add(component)
        components_before = object.behavior_components.count()
        assert components_before == 1

        data = get_default_data(object,
                                service_provider_attr,
                                service_provider_attr_field,
                                delete=True)
        data["weightlimitsbehaviorcomponent-0-id"] = component.id
        data["weightlimitsbehaviorcomponent-INITIAL_FORMS"] = 1
        data["weightlimitsbehaviorcomponent-TOTAL_FORMS"] = 2

        request = apply_request_middleware(
            rf.post("/", data=data, user=admin_user))
        response = view(request, pk=object.pk)
        if hasattr(response, "render"):
            response.render()
        components_after = object.behavior_components.count()
        assert not components_after

        assert not WaivingCostBehaviorComponent.objects.first()
Ejemplo n.º 35
0
def test_editing_sales_ranges_multi_shop(rf, admin_user):
    get_default_shop()
    another_shop = get_shop(prices_include_tax=True)
    another_shop.status = ShopStatus.ENABLED
    another_shop.save()
    group = get_default_customer_group()
    data = {}
    for shop in Shop.objects.all():
        data.update(get_edit_view_data(shop, group, 0, 50))

    assert ContactGroupSalesRange.objects.count() == 0
    # To make this test work we need to mock members form_part since the extra
    # forms does not render correctly
    with patch.object(ContactGroupEditView, "base_form_part_classes",
                      [ContactGroupBaseFormPart]):
        request = apply_request_middleware(rf.post("/", data=data),
                                           user=admin_user)
        view = ContactGroupEditView.as_view()
        response = view(request=request, pk=group.pk)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code in [200, 302]

    assert ContactGroupSalesRange.objects.count() == 2
    for shop in Shop.objects.all():
        sales_range = ContactGroupSalesRange.objects.filter(group=group,
                                                            shop=shop).first()
        assert sales_range.min_value == 0
        assert sales_range.max_value == 50
Ejemplo n.º 36
0
def test_campaign_edit_save(rf, admin_user):
    """
    To make things little bit more simple let's use only english as
    a language.
    """
    with override_settings(LANGUAGES=[("en", "en")]):
        shop = get_default_shop()
        object = BasketCampaign.objects.create(name="test campaign", active=True, shop=shop)
        object.save()
        view = BasketCampaignEditView.as_view()
        new_name = "Test Campaign"
        assert object.name != new_name
        data = {
            "base-name": new_name,
            "base-public_name__en": "Test Campaign",
            "base-shop": get_default_shop().id,
            "base-active": True,
            "base-basket_line_text": "Test campaign activated!"
        }
        methods_before = BasketCampaign.objects.count()
        # Conditions and effects is tested separately
        with override_provides("campaign_basket_condition", []):
            with override_provides("basket_campaign_effect", []):
                request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
                response = view(request, pk=object.pk)
                assert response.status_code in [200, 302]

        assert BasketCampaign.objects.count() == methods_before
        assert BasketCampaign.objects.get(pk=object.pk).name == new_name
Ejemplo n.º 37
0
def test_order_creator(rf, admin_user):
    source = seed_source(admin_user)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=get_default_product(),
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    source.add_line(
        type=OrderLineType.OTHER,
        quantity=1,
        base_unit_price=source.create_price(10),
        require_verification=True,
    )

    request = apply_request_middleware(rf.get("/"))

    creator = OrderCreator(request)
    order = creator.create_order(source)
    assert get_data_dict(source.billing_address) == get_data_dict(order.billing_address)
    assert get_data_dict(source.shipping_address) == get_data_dict(order.shipping_address)
    assert source.customer == order.customer
    assert source.payment_method == order.payment_method
    assert source.shipping_method == order.shipping_method
    assert order.pk
Ejemplo n.º 38
0
def test_method_creation(rf, admin_user, view, model, service_provider_attr, get_provider):
    """
    To make things little bit more simple let's use only english as
    an language.
    """
    with override_settings(LANGUAGES=[("en", "en")]):
        view = view.as_view()
        service_provider_field = "base-%s" % service_provider_attr
        data = {
            service_provider_field: get_provider().id,
            "base-choice_identifier": "manual",
            "base-name__en": "Custom method",
            "base-shop": get_default_shop().id,
            "base-tax_class": get_default_tax_class().id,
            "base-enabled": True,
        }
        # Default provider CustomCarrier/CustomPaymentProcessor should be set in form init
        methods_before = model.objects.count()
        url = "/?provider=%s" % get_provider().id
        request = apply_request_middleware(rf.post(url, data=data), user=admin_user)
        response = view(request, pk=None)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code in [200, 302]
        assert model.objects.count() == (methods_before + 1)
Ejemplo n.º 39
0
def test_order_source_parentage(rf, admin_user):
    source = seed_source(admin_user)
    product = get_default_product()
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=product,
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
        line_id="parent"
    )
    source.add_line(
        type=OrderLineType.OTHER,
        text="Child Line",
        sku="KIDKIDKID",
        quantity=1,
        base_unit_price=source.create_price(5),
        parent_line_id="parent"
    )
    request = apply_request_middleware(rf.get("/"))

    creator = OrderCreator(request)
    order = Order.objects.get(pk=creator.create_order(source).pk)
    kid_line = order.lines.filter(sku="KIDKIDKID").first()
    assert kid_line
    assert kid_line.parent_line.product_id == product.pk
Ejemplo n.º 40
0
def test_order_creator_view_for_customer(rf, admin_user):
    get_default_shop()
    contact = create_random_person(locale="en_US", minimum_name_comp_len=5)
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.id}), user=admin_user)
    response = OrderEditView.as_view()(request)
    assert_contains(response, "customerData")  # in the config
    assert_contains(response, "isCompany")  # in the config
Ejemplo n.º 41
0
def test_services_edit_view_formsets(rf, admin_user, view, get_object):
    get_default_shop()
    object = get_object()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    form_parts = get_form_parts(request, view, object)
    # form parts should include forms, form parts and plus one for the base form
    assert len(form_parts) == (len(DEFAULT_BEHAVIOR_FORMS) + len(DEFAULT_BEHAVIOR_FORM_PARTS) + 1)
Ejemplo n.º 42
0
def test_contact_details_view_with_many_groups(rf, admin_user):
    get_default_shop()
    person = create_random_person()
    person.groups.add(
        ContactGroup.objects.create(name="Czz Group"),
        ContactGroup.objects.create(name="Azz Group"),
        ContactGroup.objects.create(name="Bzz Group"),
        ContactGroup.objects.language('fi').create(name="Dzz ryhmä"),
    )

    # Group with name in two languages
    grp_e = ContactGroup.objects.language('en').create(name="Ezz Group")
    grp_e.set_current_language('fi')
    grp_e.name = "Ezz ryhmä"
    grp_e.save()
    person.groups.add(grp_e)

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    with translation.override('en'):
        view_func = ContactDetailView.as_view()
        response = view_func(request, pk=person.pk)
    content = response.render().content.decode('utf-8')
    assert "Azz Group" in content
    assert "Bzz Group" in content
    assert "Czz Group" in content
    assert "Dzz ryhmä" in content, "no name in active language, still present"
    assert "Ezz Group" in content, "rendered with active language"
    positions = [content.index(x + "zz ") for x in 'ABCDE']
    assert positions == sorted(positions), "Groups are sorted"
    assert response.status_code == 200
Ejemplo n.º 43
0
def test_method_creation(rf, admin_user, view, model, service_provider_attr,
                         get_provider):
    """
    To make things little bit more simple let's use only english as
    an language.
    """
    with override_settings(LANGUAGES=[("en", "en")]):
        view = view.as_view()
        service_provider_field = "base-%s" % service_provider_attr
        data = {
            service_provider_field: get_provider().id,
            "base-choice_identifier": "manual",
            "base-name__en": "Custom method",
            "base-shop": get_default_shop().id,
            "base-tax_class": get_default_tax_class().id,
            "base-enabled": True,
        }
        # Default provider CustomCarrier/CustomPaymentProcessor should be set in form init
        methods_before = model.objects.count()
        url = "/?provider=%s" % get_provider().id
        request = apply_request_middleware(rf.post(url, data=data),
                                           user=admin_user)
        response = view(request, pk=None)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code in [200, 302]
        assert model.objects.count() == (methods_before + 1)
Ejemplo n.º 44
0
def test_editing_sales_ranges_multi_shop(rf, admin_user):
    get_default_shop()
    another_shop = get_shop(prices_include_tax=True)
    another_shop.status = ShopStatus.ENABLED
    another_shop.save()
    group = get_default_customer_group()
    data = {}
    for shop in Shop.objects.all():
        data.update(get_edit_view_data(shop, group, 0, 50))

    assert ContactGroupSalesRange.objects.count() == 0
    # To make this test work we need to mock members form_part since the extra
    # forms does not render correctly
    with patch.object(ContactGroupEditView, "base_form_part_classes", [ContactGroupBaseFormPart]):
        request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
        view = ContactGroupEditView.as_view()
        response = view(request=request, pk=group.pk)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code in [200, 302]

    assert ContactGroupSalesRange.objects.count() == 2
    for shop in Shop.objects.all():
        sales_range = ContactGroupSalesRange.objects.filter(group=group, shop=shop).first()
        assert sales_range.min_value == 0
        assert sales_range.max_value == 50
Ejemplo n.º 45
0
def test_services_edit_view_formsets(rf, admin_user, view, get_object):
    get_default_shop()
    object = get_object()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    form_parts = get_form_parts(request, view, object)
    assert len(form_parts) == (len(DEFAULT_BEHAVIOR_FORMS) + 1
                               )  # plus one since the base form
Ejemplo n.º 46
0
def test_address_phase_authorized_user(rf, admin_user):
    request = apply_request_middleware(rf.get("/"),
                                       shop=get_default_shop(),
                                       customer=get_person_contact(admin_user))
    view_func = AddressesPhase.as_view()
    resp = view_func(request)
    assert 'company' not in resp.context_data['form'].form_defs
Ejemplo n.º 47
0
def test_extending_shipment_form_valid_hook(rf, admin_user):
    shop = get_default_shop()
    supplier = get_default_supplier()
    product = create_product(sku="test-sku", shop=shop, supplier=supplier, default_price=3.33)
    quantity = 1
    order = create_order_with_product(product, supplier, quantity=quantity, taxless_base_unit_price=1, shop=shop)

    extend_form_class = "shoop_tests.admin.test_shipment_creator.ShipmentFormModifierTest"
    with override_provides(FORM_MODIFIER_PROVIDER_KEY, [extend_form_class]):
        phone_number = "+358911"
        data = {"q_%s" % product.pk: 1, "supplier": supplier.pk, "phone": phone_number}
        request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
        view = OrderCreateShipmentView.as_view()
        response = view(request, pk=order.pk)
        assert response.status_code == 302

        # Order should now have shipment, but let's re fetch it first
        order = Order.objects.get(pk=order.pk)
        assert order.shipments.count() == 1

        shipment = order.shipments.first()
        assert order.shipping_data.get(shipment.identifier).get("phone") == phone_number
        assert shipment.supplier_id == supplier.id
        assert shipment.products.count() == 1
        assert shipment.products.first().product_id == product.id
Ejemplo n.º 48
0
def test_order_creator(rf, admin_user):
    source = seed_source(admin_user)
    source.add_line(
        type=OrderLineType.PRODUCT,
        product=get_default_product(),
        supplier=get_default_supplier(),
        quantity=1,
        base_unit_price=source.create_price(10),
    )
    source.add_line(
        type=OrderLineType.OTHER,
        quantity=1,
        base_unit_price=source.create_price(10),
        require_verification=True,
    )

    request = apply_request_middleware(rf.get("/"))

    creator = OrderCreator(request)
    order = creator.create_order(source)
    assert get_data_dict(source.billing_address) == get_data_dict(order.billing_address)
    assert get_data_dict(source.shipping_address) == get_data_dict(order.shipping_address)
    assert source.customer == order.customer
    assert source.payment_method == order.payment_method
    assert source.shipping_method == order.shipping_method
    assert order.pk
Ejemplo n.º 49
0
def test_campaign_new_mode_view_formsets(rf, admin_user):
    view = CatalogCampaignEditView
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    form_parts = get_form_parts(request, view, view.model())
    assert len(form_parts) == 1
    assert issubclass(form_parts[0].__class__, CatalogBaseFormPart)
Ejemplo n.º 50
0
def test_rules_and_effects(rf, admin_user):
    """
    To make things little bit more simple let's use only english as
    a language.
    """
    get_default_shop()
    with override_settings(LANGUAGES=[("en", "en")]):
        shop = get_default_shop()
        object = BasketCampaign.objects.create(name="test campaign", active=True, shop=shop)
        assert object.conditions.count() == 0
        assert object.effects.count() == 0
        view = BasketCampaignEditView.as_view()
        data = {
            "base-name": "test campaign",
            "base-public_name__en": "Test Campaign",
            "base-shop": get_default_shop().id,
            "base-active": True,
            "base-basket_line_text": "Test campaign activated!"
        }
        with override_provides(
                "campaign_basket_condition", ["shoop.campaigns.admin_module.forms:BasketTotalProductAmountConditionForm"]):
            with override_provides(
                    "basket_campaign_effect", ["shoop.campaigns.admin_module.forms:BasketDiscountAmountForm"]):
                data.update(get_products_in_basket_data())
                data.update(get_free_product_data(object))
                request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
                view(request, pk=object.pk)

        object.refresh_from_db()
        assert object.conditions.count() == 1
        assert object.effects.count() == 1
Ejemplo n.º 51
0
def test_form_populate_initial_data(rf, admin_user):
    shop = get_default_shop()
    supplier = get_default_supplier()
    initial_discount_amount = 20
    campaign = BasketCampaign.objects.create(shop=shop)
    BasketDiscountAmount.objects.create(campaign=campaign, discount_amount=initial_discount_amount)

    # Test that correct initial value is returned for non-many-to-many field
    product_amount_initial = 10
    product_amount_condition = BasketTotalProductAmountCondition(product_count=product_amount_initial)
    product_amount_condition.save()
    campaign.conditions.add(product_amount_condition)

    products_count_initial = 5
    for i in range(products_count_initial):
        create_product(printable_gibberish(), shop=shop, supplier=supplier, default_price="20")
    products_initial = Product.objects.all()[:products_count_initial]
    assert len(products_initial) == products_count_initial

    # Test that correct initial value is returned for many-to-many field
    products_in_basket_condition = ProductsInBasketCondition.objects.create()
    products_in_basket_condition.values = products_initial
    products_in_basket_condition.save()
    campaign.conditions.add(products_in_basket_condition)

    assert len(campaign.conditions.all()) == 2
    assert campaign.effects.count() == 1

    request=apply_request_middleware(rf.get("/"), user=admin_user)
    form = BasketCampaignForm(request=request, instance=campaign)
    assert form.fields["basket_product_condition"].initial == product_amount_initial
    assert set(form.fields["basket_products_condition"].initial) == set([p.pk for p in products_initial])
    assert form.fields["discount_amount_effect"].initial == initial_discount_amount
Ejemplo n.º 52
0
def test_admin_catalog_campaign_edit_view(rf, admin_user):
    shop = get_default_shop()
    view = CatalogCampaignEditView(request=apply_request_middleware(rf.get("/"), user=admin_user))
    form_class = view.get_form_class()
    form_kwargs = view.get_form_kwargs()
    form = form_class(**form_kwargs)

    assert not form.is_bound

    data = get_form_data(form)
    data.update({
        "shop": shop.pk,
        "name": "test",
    })
    form = form_class(**dict(form_kwargs, data=data))
    form.full_clean()
    assert "You must define discount percentage or amount" in form.errors["__all__"][0]

    data.update({"discount_amount_value": "20"})
    form = form_class(**dict(form_kwargs, data=data))
    form.full_clean()

    # atleast 1 rule is required
    assert "You must set at least one rule for this campaign" in form.errors["__all__"][0]

    supplier = get_default_supplier()
    product = create_product(printable_gibberish(), shop=shop, supplier=supplier, default_price="20")
    data.update({"product_filter": [1]})

    form = form_class(**dict(form_kwargs, data=data))
    form.full_clean()
    assert not form.errors

    campaign = form.save()
    assert campaign.filters.count() == 1
Ejemplo n.º 53
0
def test_superuser_can_see_invisible_page(rf, admin_user):
    page = create_page()
    get_default_shop()
    view_func = PageView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view_func(request, url=page.url)
    response.render()
    assert "<h1>Bacon ipsum" in response.rendered_content
Ejemplo n.º 54
0
def get_frontend_request_for_command(state, command, user):
    json_data = json.dumps({"state": state})
    return apply_request_middleware(RequestFactory().post(
        "/",
        data=json_data,
        content_type="application/json; charset=UTF-8",
        QUERY_STRING="command=%s" % command),
                                    user=user)
Ejemplo n.º 55
0
def test_user_detail_works_at_all(rf, admin_user):
    get_default_shop()
    user = get_user_model().objects.create(
        username=printable_gibberish(20),
        first_name=printable_gibberish(10),
        last_name=printable_gibberish(10),
        password="******"
    )
    view_func = UserDetailView.as_view()
    response = view_func(apply_request_middleware(rf.get("/"), user=admin_user), pk=user.pk)
    assert response.status_code == 200
    response.render()
    assert force_text(user) in force_text(response.content)
    response = view_func(apply_request_middleware(rf.post("/", {"set_is_active": "0"}), user=admin_user), pk=user.pk)
    assert response.status_code < 500 and not get_user_model().objects.get(pk=user.pk).is_active
    with pytest.raises(Problem):
        view_func(apply_request_middleware(rf.post("/", {"set_is_active": "0"}), user=admin_user), pk=admin_user.pk)
Ejemplo n.º 56
0
def test_services_edit_view_formsets(rf, admin_user, view, get_object):
    get_default_shop()
    object = get_object()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    form_parts = get_form_parts(request, view, object)
    # form parts should include forms, form parts and plus one for the base form
    assert len(form_parts) == (len(DEFAULT_BEHAVIOR_FORMS) +
                               len(DEFAULT_BEHAVIOR_FORM_PARTS) + 1)