Exemplo n.º 1
0
def test_multishops_middleware(rf, host):
    with override_provides("xtheme", [
        "shuup_tests.xtheme.utils:FauxTheme",
        "shuup_tests.xtheme.utils:FauxTheme2"
    ]):
        shop1 = Shop.objects.create(identifier="shop1", domain="shop-1")
        shop2 = Shop.objects.create(identifier="shop2", domain="shop-test-2")

        theme_settings_shop1 = ThemeSettings.objects.create(theme_identifier=FauxTheme.identifier, shop=shop1)
        theme_settings_shop2 = ThemeSettings.objects.create(theme_identifier=FauxTheme2.identifier, shop=shop2)

        request = rf.get("/")
        request.META["HTTP_HOST"] = host

        # should apply the correct shop and the template
        apply_request_middleware(request)

        if host == "shop-1.somedomain.com":
            assert request.shop.id == shop1.id
            assert get_middleware_current_theme().identifier == FauxTheme.identifier
            assert get_middleware_current_theme().settings_obj.id == theme_settings_shop1.id
        else:
            assert request.shop.id == shop2.id
            assert get_middleware_current_theme().identifier == FauxTheme2.identifier
            assert get_middleware_current_theme().settings_obj.id == theme_settings_shop2.id
Exemplo n.º 2
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())
Exemplo n.º 3
0
def test_basket_orderability_change_shop_product(rf):
    StoredBasket.objects.all().delete()
    shop = get_default_shop()
    supplier = get_default_supplier()
    product = create_product(printable_gibberish(), shop=shop, supplier=supplier, default_price=50)
    request = rf.get("/")
    request.session = {}
    request.shop = shop
    apply_request_middleware(request)
    basket = get_basket(request)
    line = basket.add_product(
        supplier=supplier,
        shop=shop,
        product=product,
        quantity=1,
        force_new_line=True,
        extra={"foo": "foo"}
    )
    assert len(basket.get_lines()) == 1
    assert len(basket.get_unorderable_lines()) == 0
    product.get_shop_instance(shop).delete()
    basket.uncache()
    assert basket.dirty
    assert len(basket.get_lines()) == 0
    assert len(basket.get_unorderable_lines()) == 1
Exemplo n.º 4
0
def assert_config_value(rf, admin_user, form_id, key, value, expected_value, shop=None):
    if not shop:
        shop = get_default_shop()

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    view_func = SystemSettingsView.as_view()
    response = view_func(request)
    assert response.status_code == 200

    form_field = "%s-%s" % (form_id, key)
    data = {form_field: value}
    request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
    response = view_func(request)
    assert response.status_code == 302
    if expected_value == "unset":
        expected_value = value
    assert configuration.get(None, key) == expected_value

    assert len(messages.get_messages(request)) == 1

    # Double save the form and the configuration should still be unchanged
    response = view_func(request)
    assert response.status_code == 302
    assert configuration.get(None, key) == expected_value

    assert len(messages.get_messages(request)) == 2

    return shop
Exemplo n.º 5
0
def test_shop_form_part(rf):
    cache.clear()
    shop = factories.get_default_shop()
    request = apply_request_middleware(rf.get("/"))

    # nothing changed
    form_part = StripeConfigurationFormPart(request, shop)
    form = list(form_part.get_form_defs())[0].instantiate(prefix="stripe")
    assert form.has_changed() is False
    assert not get_checkout_payment_details_message(shop)
    assert not get_checkout_payment_phase_message(shop)
    assert not get_checkout_saved_card_message(shop)
    assert not get_saved_card_message(shop)

    request = apply_request_middleware(rf.post("/"))
    data = {
        "stripe-checkout_payment_details_message": "A",
        "stripe-checkout_payment_phase_message": "B",
        "stripe-checkout_saved_card_message": "C",
        "stripe-saved_card_message": "D"
    }
    form_part = StripeConfigurationFormPart(request, shop)
    form = list(form_part.get_form_defs())[0].instantiate(prefix="stripe", data=data)
    assert form.is_valid()
    form_part.form_valid({StripeConfigurationFormPart.name: form})
    assert get_checkout_payment_details_message(shop) == "A"
    assert get_checkout_payment_phase_message(shop) == "B"
    assert get_checkout_saved_card_message(shop) == "C"
    assert get_saved_card_message(shop) == "D"
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
Exemplo n.º 7
0
def test_discounted_price(rf):
    shop = factories.get_default_shop()
    supplier = factories.get_default_supplier()
    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    assert request.shop == shop

    original_price = 10
    product = factories.create_product("test1", shop=shop, supplier=supplier, default_price=original_price)
    shop_product = product.get_shop_instance(shop)

    # Set discount with discount amount for $2
    discount_amount = 2
    discount = Discount.objects.create(
        active=True, product=product, supplier=supplier, discount_amount_value=discount_amount)
    discount.shops = [shop]

    # Even though the supplier is matching with the product there is no discount
    # since the supplier is not in pricing context.
    assert not hasattr(request, "supplier")
    assert supplier in shop_product.suppliers.all()
    assert product.get_price_info(request).price == request.shop.create_price(10)

    setattr(request, "supplier", supplier)
    assert product.get_price_info(request).price == request.shop.create_price(8)

    # No discount once we change the discount supplier
    new_supplier = Supplier.objects.create(identifier="*")
    discount.supplier = new_supplier
    discount.save()
    assert product.get_price_info(request).price == request.shop.create_price(10)
Exemplo n.º 8
0
def get_context(rf, customer=None):
    request = rf.get("/")
    request.shop = factories.get_default_shop()
    apply_request_middleware(request)
    if customer:
        request.customer = customer
    return get_jinja_context(**{"request": request})
Exemplo n.º 9
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"]
Exemplo n.º 10
0
def test_shop_wizard_pane(rf, admin_user, settings):
    settings.SHUUP_SETUP_WIZARD_PANE_SPEC = [
        "shuup.admin.modules.shops.views:ShopWizardPane"
    ]
    shop = Shop.objects.create()
    get_currency("USD")
    assert not shop.contact_address
    assert not TaxClass.objects.exists()
    fields = _extract_fields(rf, admin_user)
    fields["shop-logo"] = ""  # Correct init value for this is not None, but empty string
    request = apply_request_middleware(rf.post("/", data=fields), user=admin_user)
    response = WizardView.as_view()(request)
    # fields are missing
    assert response.status_code == 400
    fields["shop-public_name__fi"] = "test shop"
    fields["shop-currency"] = "USD"
    fields["address-name"] = "TEST"
    fields["address-city"] = "TEST"
    fields["address-region_code"] = "CA"
    fields["address-street"] = "test"
    fields["address-country"] = "US"

    request = apply_request_middleware(rf.post("/", data=fields), user=admin_user)
    response = WizardView.as_view()(request)
    assert response.status_code == 200
    shop.refresh_from_db()
    shop.set_current_language("fi")
    assert shop.name == "test shop"
    assert shop.public_name == "test shop"
    assert shop.logo is None
    assert shop.contact_address
    assert shop.currency == "USD"
    assert TaxClass.objects.exists()
    assert_redirect_to_dashboard(rf)
Exemplo n.º 11
0
def test_edit_view_adding_messages_to_form_group(rf, admin_user):
    get_default_shop()  # obvious prerequisite
    product = get_default_product()
    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=product.pk)
    response.render()
    assert 200 <= response.status_code < 300

    assert ProductEditView.add_form_errors_as_messages

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content))
    post_data = {
        # Error in the base form part
        "base-name__en": "",
    }
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=product.pk)

    errors = response.context_data["form"].errors

    assert "base" in errors
    assert "name__en" in errors["base"]
Exemplo n.º 12
0
def test_parallel_baskets(rf):
    request = get_request_with_basket()
    shop = get_default_shop()
    customer = create_random_person()

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

    basket_one = get_basket(request, basket_name="basket_one")
    basket_two = get_basket(request, basket_name="basket_two")

    product_one = get_default_product()
    product_two = get_default_product()
    product_two.sku = "derpy-hooves"
    sales_unit = SalesUnit.objects.create(identifier="test-sales-partial", decimals=2, name="Partial unit")
    product_two.sales_unit = sales_unit  # Set the sales unit for the product
    product_two.save()

    basket_commands.handle_add(request, basket_one, product_id=product_one.pk, quantity=1)
    basket_commands.handle_add(request, basket_two, product_id=product_two.pk, quantity=3.5)

    assert basket_one.product_count == 1
    assert basket_two.product_count == 3.5
Exemplo n.º 13
0
def test_save_cart_errors(rf, regular_user):
    get_default_shop()
    request = apply_request_middleware(rf.post("/", {
        "title": "test"
    }))
    response = CartSaveView.as_view()(request)
    data = json.loads(response.content.decode("utf8"))
    assert response.status_code == 403, "can't save cart as anonymous user"
    assert not data["ok"], "can't save cart without title"

    customer = get_person_contact(regular_user)
    request = apply_request_middleware(rf.post("/", {
        "title": ""
    }), customer=customer, user=regular_user)
    response = CartSaveView.as_view()(request)
    data = json.loads(response.content.decode("utf8"))
    assert response.status_code == 400
    assert not data["ok"], "can't save cart without title"

    request = apply_request_middleware(rf.post("/", {
        "title": "test"
    }), customer=customer, user=regular_user)
    response = CartSaveView.as_view()(request)
    data = json.loads(response.content.decode("utf8"))
    assert response.status_code == 400
    assert not data["ok"], "can't save an empty cart"
Exemplo n.º 14
0
def test_force_views_only_for_staff(rf):
    shop = factories.get_default_shop()
    user = factories.create_random_user(is_staff=True)
    person_contact = get_person_contact(user)

    # Start forcing. There shouldn't be any changes to
    # request customer due calling the force functions since
    # those just do the redirect in case the current is user
    # is not shop staff.
    request = apply_request_middleware(rf.get("/"), user=user)
    assert request.customer == person_contact

    _call_force_view(request, force_anonymous_contact)

    request = apply_request_middleware(rf.get("/"), user=user)
    assert request.customer == person_contact

    _call_force_view(request, force_person_contact)

    request = apply_request_middleware(rf.get("/"), user=user)
    assert request.customer == person_contact

    _call_force_view(request, force_company_contact)

    request = apply_request_middleware(rf.get("/"), user=user)
    assert request.customer == person_contact

    assert get_company_contact(user) is None
Exemplo n.º 15
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.º 16
0
def test_user_list(rf, admin_user):
    shop = get_default_shop()
    user = get_user_model().objects.create(
        username=printable_gibberish(20),
        first_name=printable_gibberish(10),
        last_name=printable_gibberish(10),
        password="******",
        is_staff=True,
        is_superuser=False
    )
    shop.staff_members.add(user)
    view_func = UserListView.as_view()
    request = rf.get("/", {"jq": json.dumps({"perPage": 100, "page": 1})})

    # check with superuser
    response = view_func(apply_request_middleware(request, user=admin_user))
    assert response.status_code == 200
    data = json.loads(response.content.decode("utf-8"))
    assert len(data["items"]) == 2

    # check with staff user
    response = view_func(apply_request_middleware(request, user=user))
    assert response.status_code == 200
    data = json.loads(response.content.decode("utf-8"))
    assert len(data["items"]) == 1
Exemplo n.º 17
0
def _test_happy_hours_delete_view(rf, index):
    shop = factories.get_shop(identifier="shop%s" % index, enabled=True)
    staff_user = factories.create_random_user(is_staff=True)
    shop.staff_members.add(staff_user)
    happy_hour_name = "The Hour %s" % index
    happy_hour = HappyHour.objects.create(name=happy_hour_name)
    happy_hour.shops = [shop]
    extra_happy_hour= HappyHour.objects.create(name="Extra Hour %s" % index)
    extra_happy_hour.shops = [shop]

    assert HappyHour.objects.filter(name=happy_hour_name).exists()
    view_func = HappyHourDeleteView.as_view()
    request = apply_request_middleware(rf.post("/"), user=staff_user, shop=shop)
    set_shop(request, shop)
    response = view_func(request, pk=happy_hour.pk)
    if hasattr(response, "render"):
        response.render()
    assert response.status_code == 302
    assert not HappyHour.objects.filter(name=happy_hour_name).exists()

    # Make sure that this staff can't remove other people discounts
    other_exceptions = HappyHour.objects.exclude(shops=shop)
    exception_count = other_exceptions.count()
    for coupon in other_exceptions:
        view_func = HappyHourDeleteView.as_view()
        request = apply_request_middleware(rf.post("/"), user=staff_user, shop=shop)
        set_shop(request, shop)
        with pytest.raises(Http404):
            response = view_func(request, pk=coupon.pk)
            if hasattr(response, "render"):
                response.render()

    assert exception_count == HappyHour.objects.exclude(shops=shop).count()
Exemplo n.º 18
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
Exemplo n.º 19
0
def test_get_shop(rf, get_shop_fn):
    with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True):
        activate("en")
        shop1 = Shop.objects.create(identifier="shop1", status=ShopStatus.ENABLED)
        shop2 = Shop.objects.create(identifier="shop2", status=ShopStatus.ENABLED)

        normal_user = factories.create_random_user()
        staff_user = factories.create_random_user(is_staff=True)

        request = apply_request_middleware(rf.post("/"), user=normal_user, skip_session=True)
        # user not staff
        assert get_shop_fn(request) is None

        # staff user now
        with pytest.raises(PermissionDenied) as exc:
            request = apply_request_middleware(rf.post("/"), user=staff_user)
            assert exc.value == "You are not a staff member of this shop"

        # no shop set
        assert get_shop_fn(request) is None

        # adds the user to a shop
        shop1.staff_members.add(staff_user)
        request = apply_request_middleware(rf.post("/"), user=staff_user, skip_session=True)
        assert get_shop_fn(request) == shop1

        # adds the user to another shop
        shop2.staff_members.add(staff_user)

        # still the first shop as we do not set any
        assert get_shop_fn(request) == shop1

        for shop in [shop1, shop2]:
            request = apply_request_middleware(rf.post("/"), user=staff_user, shop=shop)
            assert get_shop_fn(request) == shop
def test_region_views(rf, admin_user):
    get_default_shop()

    view = load("shuup_shipping_table.admin.views.region.RegionListView").as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request)
    assert response.status_code == 200

    view = load("shuup_shipping_table.admin.views.region.RegionEditView").as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request)
    assert response.status_code == 200
    
    view = load("shuup_shipping_table.admin.views.region.RegionDeleteView").as_view()
    request = apply_request_middleware(rf.post("/"), user=admin_user)
    with pytest.raises(Http404):
        response = view(request, pk=1)


    view = load("shuup_shipping_table.admin.views.region.RegionImportView").as_view()
    request = apply_request_middleware(rf.post("/"), user=admin_user)
    response = view(request)
    assert response.status_code == 302

    view = load("shuup_shipping_table.admin.views.region.RegionExportView").as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request)
    assert response.status_code == 200
Exemplo n.º 21
0
def test_user_detail_works_at_all(rf, admin_user):
    shop = 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)

    user = get_user_model().objects.create(
        username=printable_gibberish(20),
        first_name=printable_gibberish(10),
        last_name=printable_gibberish(10),
        password="******",
        is_staff=True,
        is_superuser=False
    )
    shop.staff_members.add(user)
    # non superusers can't see superusers
    with pytest.raises(Http404):
        view_func(apply_request_middleware(rf.get("/"), user=user), pk=admin_user.pk)
Exemplo n.º 22
0
def test_login_as_user_errors(rf, admin_user, regular_user):
    get_default_shop()
    view_func = LoginAsUserView.as_view()
    request = apply_request_middleware(rf.post("/"), user=regular_user, skip_session=True)

    # log in as self
    with pytest.raises(Problem):
        view_func(request, pk=regular_user.pk)

    user = UserFactory()
    get_person_contact(user)
    # non superuser trying to login as someone else
    with pytest.raises(PermissionDenied):
        view_func(request, pk=user.pk)

    request = apply_request_middleware(rf.post("/"), user=admin_user)
    user.is_superuser = True
    user.save()
    # user is trying to login as another superuser
    with pytest.raises(PermissionDenied):
        view_func(request, pk=user.pk)

    user.is_superuser = False
    user.is_staff = True
    user.save()
    # user is trying to login as a staff user
    with pytest.raises(PermissionDenied):
        view_func(request, pk=user.pk)

    user.is_staff = False
    user.is_active = False
    user.save()
    # user is trying to login as an inactive user
    with pytest.raises(Problem):
        view_func(request, pk=user.pk)
def test_coupon_creation_for_supplier(rf, admin_user):
    """
    To make things little bit more simple let's use only english as
    a language.
    """
    shop = get_default_shop()
    supplier = Supplier.objects.create(identifier=admin_user.username)
    
    another_superuser = create_random_user(is_superuser=True, is_staff=True)
    supplier2 = Supplier.objects.create(identifier=another_superuser.username)

    supplier_provider = "shuup.testing.supplier_provider.UsernameSupplierProvider"
    with override_settings(LANGUAGES=[("en", "en")]):
        with override_settings(SHUUP_ADMIN_SUPPLIER_PROVIDER_SPEC=supplier_provider):
            view = CouponEditView.as_view()
            data = {
                "code": "OK",
                "active": True,
                "shop": shop.pk
            }
            coupons_before = Coupon.objects.count()
            request = apply_request_middleware(rf.post("/", data=data), user=admin_user)
            assert get_supplier(request) == supplier
            response = view(request, pk=None)
            assert response.status_code in [200, 302]
            assert Coupon.objects.count() == (coupons_before + 1)

            new_coupon = Coupon.objects.filter(supplier=supplier).first()
            assert new_coupon

            # Another superuser shouldn't see this campaign
            request = apply_request_middleware(rf.post("/", data=data), user=another_superuser)
            assert get_supplier(request) == supplier2
            with pytest.raises(Http404):
                response = view(request, pk=new_coupon.pk)
Exemplo n.º 24
0
def test_category_create_with_parent(rf, admin_user):
    shop = get_default_shop()
    default_category = get_default_category()

    default_category.shops.clear()
    assert shop not in default_category.shops.all()
    with override_settings(LANGUAGES=[("en", "en")]):
        view = CategoryEditView.as_view()
        cat_name = "Random name"
        data = {
            "base-name__en": cat_name,
            "base-status": CategoryStatus.VISIBLE.value,
            "base-visibility": CategoryVisibility.VISIBLE_TO_ALL.value,
            "base-ordering": 1,
            "base-parent": default_category.pk
        }
        assert Category.objects.count() == 1
        request = apply_request_middleware(rf.post("/", data=data), user=admin_user, shop=shop)
        response = view(request, pk=None)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code in [200, 302]
        assert Category.objects.count() == 1

        default_category.shops.add(shop)
        request = apply_request_middleware(rf.post("/", data=data), user=admin_user, shop=shop)
        response = view(request, pk=None)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code in [200, 302]
        assert Category.objects.count() == 2
Exemplo n.º 25
0
def test_product_edit_view_multipleshops(rf):
    """
    Check whether a staff user from Shop A can see the product from Shop B
    when the staff user is only attached to Shop A
    """
    with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True):
        shop1 = get_default_shop()
        shop2 = get_new_shop(identifier="shop2", domain="shop2", name="Shop 2")
        shop2_staff = create_random_user(is_staff=True)
        shop2.staff_members.add(shop2_staff)

        product = create_product("shop1-product", shop=shop1)
        shop_product = product.get_shop_instance(shop1)
        request = apply_request_middleware(rf.get("/", HTTP_HOST=shop2.domain), user=shop2_staff)

        view_func = ProductEditView.as_view()
        with pytest.raises(Http404):
            view_func(request, pk=shop_product.pk)

        view_func = ProductListView.as_view()
        payload = {"jq": json.dumps({"perPage": 100, "page": 1}), "shop": shop2.pk}
        request = apply_request_middleware(rf.get("/", payload, HTTP_HOST=shop2.domain), user=shop2_staff)
        response = view_func(request)
        assert response.status_code == 200
        data = json.loads(response.content.decode("utf-8"))
        assert len(data["items"]) == 0
Exemplo n.º 26
0
def _test_exception_delete_view(rf, index):
    shop = factories.get_shop(identifier="shop%s" % index, enabled=True)
    staff_user = factories.create_random_user(is_staff=True)
    shop.staff_members.add(staff_user)
    exception_name = "Exception %s" % index
    exception = AvailabilityException.objects.create(
        name=exception_name, start_datetime=now(), end_datetime=now())
    exception.shops = [shop]
    extra_exception = AvailabilityException.objects.create(
        name="Extra Exception %s" % index, start_datetime=now(), end_datetime=now())
    extra_exception.shops = [shop]

    assert AvailabilityException.objects.filter(name=exception_name).exists()
    view_func = AvailabilityExceptionDeleteView.as_view()
    request = apply_request_middleware(rf.post("/"), user=staff_user, shop=shop)
    set_shop(request, shop)
    response = view_func(request, pk=exception.pk)
    if hasattr(response, "render"):
        response.render()
    assert response.status_code == 302
    assert not AvailabilityException.objects.filter(name=exception_name).exists()

    # Make sure that this staff can't remove other people discounts
    other_exceptions = AvailabilityException.objects.exclude(shops=shop)
    exception_count = other_exceptions.count()
    for coupon in other_exceptions:
        view_func = AvailabilityExceptionDeleteView.as_view()
        request = apply_request_middleware(rf.post("/"), user=staff_user, shop=shop)
        set_shop(request, shop)
        with pytest.raises(Http404):
            response = view_func(request, pk=coupon.pk)
            if hasattr(response, "render"):
                response.render()

    assert exception_count == AvailabilityException.objects.exclude(shops=shop).count()
Exemplo n.º 27
0
def test_iframe_mode(rf, admin_user, extra_query_param, extra_query_value, expected_script):
    get_default_shop()
    view = load("shuup.admin.modules.categories.views:CategoryEditView").as_view()

    request = apply_request_middleware(rf.get("/", {"mode": "iframe"}), user=admin_user)
    response = view(request)
    if hasattr(response, "render"):
        response.render()
    assert 200 <= response.status_code < 300

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content, "lxml"))
    post.update({
        "base-name__en": "Name"
    })
    post.pop("base-image")

    # save iframe mode
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    request.GET = request.GET.copy()
    request.GET["mode"] = "iframe"

    if extra_query_param:
        request.GET[extra_query_param] = extra_query_value

    response = view(request)
    assert response.status_code == 302

    client = Client()
    client.login(username="******", password="******")

    response = client.get(response.url)
    assert response.status_code == 200
    assert expected_script in force_text(response.content)
Exemplo n.º 28
0
def test_lcfg(rf):
    two_thirds = int(LayoutCellGeneralInfoForm.CELL_FULL_WIDTH * 2 / 3)
    with plugin_override():
        with override_current_theme_class(None):
            theme = get_current_theme(get_default_shop())

            cell = LayoutCell(theme, "text", sizes={"md": two_thirds, "sm": two_thirds})
            lcfg = LayoutCellFormGroup(layout_cell=cell, theme=theme, request=apply_request_middleware(rf.get("/")))
            assert "general" in lcfg.forms
            assert "plugin" in lcfg.forms
            assert not lcfg.is_valid()  # Oh, we must've forgotten the text...
            lcfg = LayoutCellFormGroup(
                data={
                    "general-cell_width": "%d" % two_thirds,
                    "general-cell_align": " ",
                    "general-cell_extra_classes" : "newClass",
                    "plugin-text_*": "Hello, world!"
                },
                layout_cell=cell,
                theme=theme,
                request=apply_request_middleware(rf.get("/"))
            )
            assert lcfg.is_valid()  # Let's see now!
            lcfg.save()
            assert cell.sizes["md"] == two_thirds
            assert cell.extra_classes == "newClass"
            assert cell.config["text"] == {FALLBACK_LANGUAGE_CODE: "Hello, world!"}
Exemplo n.º 29
0
def test_user_detail_contact_seed(rf, admin_user):
    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}), user=admin_user)
    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}), user=admin_user)
    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
Exemplo n.º 30
0
def test_delete_payment(admin_user, rf):
    product = get_default_product()
    shop_product = product.get_shop_instance(get_default_shop())
    shop_product.default_price_value = 20
    shop_product.save()

    order = create_random_order(customer=create_random_person(), products=(product,), completion_probability=0)
    payment_amount = order.taxful_total_price_value

    # create a payment
    view = OrderCreatePaymentView.as_view()
    request = apply_request_middleware(rf.post("/", {"amount": payment_amount}), user=admin_user)
    response = view(request, pk=order.pk)
    assert response.status_code == 302

    order.refresh_from_db()
    assert order.is_paid()

    # delete the payment
    payment = order.payments.last()
    view = OrderDeletePaymentView.as_view()
    request = apply_request_middleware(rf.post("/", {"payment": payment.pk}), user=admin_user)
    response = view(request, pk=order.pk)
    assert response.status_code == 302

    order.refresh_from_db()
    assert order.is_not_paid()
Exemplo n.º 31
0
def test_provider_provides_definitions(rf, admin_user):
    if "shuup.front.apps.registration" not in settings.INSTALLED_APPS:
        pytest.skip("shuup.front.apps.registration required in installed apps")

    shop = get_default_shop()

    with override_provides("front_company_registration_form_provider",
                           ["shuup_tests.front.utils.FormDefTestProvider"]):
        with override_provides("front_registration_field_provider",
                               ["shuup_tests.front.utils.FieldTestProvider"]):
            request = apply_request_middleware(rf.post("/"), shop=shop)
            current_username = "******"
            current_name = "123"
            payload = {
                'company-tax_number': "123",
                'company-name': current_name,
                'billing-country': "US",
                'billing-city': "city",
                'billing-street': "street",
                'contact_person-last_name': "last",
                'contact_person-first_name': "first",
                'contact_person-email': "*****@*****.**",
                'user_account-password1': "asdf123",
                'user_account-password2': "asdf123",
                'user_account-username': current_username
            }
            form_group = CompanyRegistrationForm(request=request, data=payload)

            assert FormDefTestProvider.test_name in form_group.form_defs

            # test CompanyRegistrationForm itself
            assert "company" in form_group.form_defs
            assert "billing" in form_group.form_defs
            assert "contact_person" in form_group.form_defs
            assert "user_account" in form_group.form_defs

            assert form_group.form_defs["billing"].form_class == cached_load(
                'SHUUP_ADDRESS_MODEL_FORM')

            assert not form_group.is_valid()
            assert FormDefTestProvider.test_name in form_group.errors
            assert FieldTestProvider.key in form_group.errors[
                FormDefTestProvider.test_name]
            assert len(form_group.errors) == 1  # no other errors

            key = "%s-%s" % (FormDefTestProvider.test_name,
                             FieldTestProvider.key)
            payload.update({key: 1})

            form_group = CompanyRegistrationForm(request=request, data=payload)

            assert FormDefTestProvider.test_name in form_group.form_defs
            assert form_group.is_valid()
            assert FormDefTestProvider.test_name not in form_group.errors
            assert not len(form_group.errors)  # no errors

            # test signal fires
            company_registration_save.connect(
                change_company_signal,
                dispatch_uid="test_registration_change_company_signal")
            form_group.save(commit=True)
            assert not User.objects.filter(username=username).exists()
            assert not CompanyContact.objects.filter(
                name=current_name).exists()

            assert User.objects.filter(username="******").exists()
            assert CompanyContact.objects.filter(name="changed_name").exists()
            company_registration_save.disconnect(
                dispatch_uid="test_registration_change_company_signal")
def test_admin_edit(rf, admin_user):
    shop = get_default_shop()

    group = get_default_customer_group(shop)
    cgpd = ContactGroupPriceDisplay.objects.for_group_and_shop(group, shop)
    view = ContactGroupPriceDisplayEditView.as_view()

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=cgpd.pk)
    response.render()
    content = force_text(response.content)

    data = extract_form_fields(BeautifulSoup(content))

    data.update({
        "price_display_mode": [PriceDisplayChoices.HIDE.value],
        "group": group.id,
    })

    request = apply_request_middleware(rf.post("/", data),
                                       user=admin_user,
                                       shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful

    group = get_default_customer_group(shop)

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is False
    assert options.include_taxes is None

    # none, with_taxes, without_taxes, hide
    k = "price_display_mode"
    data.update({k: [PriceDisplayChoices.NONE.value]})
    request = apply_request_middleware(rf.post("/", data),
                                       user=admin_user,
                                       shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is True  # default
    assert options.include_taxes is None

    data.update({k: [PriceDisplayChoices.WITH_TAXES.value]})
    request = apply_request_middleware(rf.post("/", data),
                                       user=admin_user,
                                       shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful
    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is True  # default
    assert options.include_taxes is True

    data.update({k: [PriceDisplayChoices.WITHOUT_TAXES.value]})
    request = apply_request_middleware(rf.post("/", data),
                                       user=admin_user,
                                       shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is True
    assert options.include_taxes is False
Exemplo n.º 33
0
def test_protected_contact_groups(rf, admin_user, contact):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    check_for_delete(request, contact().get_default_group(), False)
Exemplo n.º 34
0
def get_request_for_contact_tests(rf):
    request = rf.get("/")
    request.shop = get_shop(prices_include_tax=True)
    apply_request_middleware(request)
    return request
def test_menu_save_arrange_view(rf):
    with override_settings(
            SHUUP_ADMIN_SHOP_PROVIDER_SPEC=
            "shuup.testing.shop_provider.TestingAdminShopProvider",
            SHUUP_ADMIN_SUPPLIER_PROVIDER_SPEC=
            "shuup.testing.supplier_provider.FirstSupplierProvider",
    ):
        supplier_user = get_supplier_user()
        url = reverse("shuup_admin:menu.arrange_supplier")

        menu_request = apply_request_middleware(rf.get(url),
                                                user=supplier_user)
        admin_menu_before_save = [
            m.to_dict() for m in get_menu_entry_categories(menu_request)
        ]
        new_data = admin_menu_before_save[::-1]
        new_data[0]["entries"][0]["name"] = "Menu Arrange"
        data = {"menus": json.dumps(new_data)}

        request = apply_request_middleware(rf.post(url, data=data),
                                           user=supplier_user)
        response = SupplierMenuArrangeView.as_view()(request)
        assert response.status_code == 302

        menu_request = apply_request_middleware(rf.get(url),
                                                user=supplier_user)
        admin_menu_after_save = [
            m.to_dict() for m in get_menu_entry_categories(menu_request)
        ]
        assert admin_menu_after_save == new_data

        # Make sure other staff has same menu after save
        another_supplier_user = get_supplier_user()
        menu_request = apply_request_middleware(rf.get(url),
                                                user=supplier_user)
        admin_menu_after_save = [
            m.to_dict() for m in get_menu_entry_categories(menu_request)
        ]
        assert admin_menu_after_save == new_data

        # Test that different languages are also customizable
        activate("fi")
        new_data[0]["entries"][0]["name"] = "Listan jarjestaminen"
        data = {"menus": json.dumps(new_data)}
        request = apply_request_middleware(rf.post(url, data=data),
                                           user=supplier_user)
        response = SupplierMenuArrangeView.as_view()(request)
        assert response.status_code == 302

        menu_request = apply_request_middleware(rf.get(url),
                                                user=supplier_user)
        admin_menu_after_save = [
            m.to_dict() for m in get_menu_entry_categories(menu_request)
        ]
        assert admin_menu_after_save == new_data

        # Back in english menu title should still be "Menu Arrange"
        activate("en")
        menu_request = apply_request_middleware(rf.get(url),
                                                user=supplier_user)
        admin_menu_after_save = [
            m.to_dict() for m in get_menu_entry_categories(menu_request)
        ]
        assert admin_menu_after_save[0]["entries"][0]["name"] == "Menu Arrange"

    # Make sure staff does not receive this menu as long as the get_supplier provider
    # returns None which is the default
    staff = get_staff_user()
    menu_request = apply_request_middleware(rf.get(url), user=staff)
    staff_menu = [m.to_dict() for m in get_menu_entry_categories(menu_request)]
    assert staff_menu != admin_menu_after_save
Exemplo n.º 36
0
def test_new_customers_report(rf, admin_user, group_by):
    with override_provides(
            "reports",
        ["shuup.default_reports.reports.new_customers:NewCustomersReport"]):
        shop = get_default_shop()

        person_creation_dates = [
            datetime(2015, 1, 2),
            datetime(2015, 1, 1),
            datetime(2016, 2, 2),
        ]
        # create person with NO user
        for creation_date in person_creation_dates:
            person = create_random_person()
            person.created_on = creation_date
            person.save()

        user_person_creation_dates = [
            datetime(2015, 3, 3),
            datetime(2015, 3, 3),
            datetime(2015, 4, 4),
            datetime(2016, 5, 5),
            datetime(2016, 6, 6),
            datetime(2016, 7, 7),
        ]
        # create person with users
        for creation_date in user_person_creation_dates:
            person = create_random_person()
            person.user = UserFactory()
            person.created_on = creation_date
            person.save()

        company_creation_dates = [
            datetime(2015, 1, 1),
            datetime(2015, 8, 8),
            datetime(2015, 9, 9),
        ]
        # create company contacts
        for creation_date in company_creation_dates:
            company = CompanyFactory()
            company.created_on = creation_date
            company.save()

        data = {
            "report": NewCustomersReport.get_name(),
            "shop": shop.pk,
            "date_range": DateRangeChoices.ALL_TIME.value,
            "writer": "json",
            "force_download": 1,
            "group_by": group_by,
        }

        view = ReportView.as_view()
        request = apply_request_middleware(rf.post("/", data=data),
                                           user=admin_user)
        response = view(request)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code == 200
        json_data = json.loads(response.content.decode("utf-8"))
        assert force_text(NewCustomersReport.title) in json_data.get("heading")

        data = json_data["tables"][0]["data"]

        if group_by == "%Y":
            assert len(data) == 3

            assert data[0]["date"] == "2015"
            assert int(data[0]["personcontact"]) == 5
            assert int(data[0]["companycontact"]) == 3
            assert int(data[0]["users"]) == 3

            assert data[1]["date"] == "2016"
            assert int(data[1]["personcontact"]) == 4
            assert int(data[1]["companycontact"]) == 0
            assert int(data[1]["users"]) == 3

        elif group_by == "%Y-%m":
            assert len(data) == 10

            assert data[0]["date"] == "2015-01"
            assert int(data[0]["personcontact"]) == 2
            assert int(data[0]["companycontact"]) == 1
            assert int(data[0]["users"]) == 0

            assert data[1]["date"] == "2015-03"
            assert int(data[1]["personcontact"]) == 2
            assert int(data[1]["companycontact"]) == 0
            assert int(data[1]["users"]) == 2

            assert data[2]["date"] == "2015-04"
            assert int(data[2]["personcontact"]) == 1
            assert int(data[2]["companycontact"]) == 0
            assert int(data[2]["users"]) == 1

            assert data[3]["date"] == "2015-08"
            assert int(data[3]["personcontact"]) == 0
            assert int(data[3]["companycontact"]) == 1
            assert int(data[3]["users"]) == 0

            assert data[4]["date"] == "2015-09"
            assert int(data[4]["personcontact"]) == 0
            assert int(data[4]["companycontact"]) == 1
            assert int(data[4]["users"]) == 0

            assert data[5]["date"] == "2016-02"
            assert int(data[5]["personcontact"]) == 1
            assert int(data[5]["companycontact"]) == 0
            assert int(data[5]["users"]) == 0

            assert data[6]["date"] == "2016-05"
            assert int(data[6]["personcontact"]) == 1
            assert int(data[6]["companycontact"]) == 0
            assert int(data[6]["users"]) == 1

            assert data[7]["date"] == "2016-06"
            assert int(data[7]["personcontact"]) == 1
            assert int(data[7]["companycontact"]) == 0
            assert int(data[7]["users"]) == 1

            assert data[8]["date"] == "2016-07"
            assert int(data[8]["personcontact"]) == 1
            assert int(data[8]["companycontact"]) == 0
            assert int(data[8]["users"]) == 1

        elif group_by == "%Y-%m-%d":
            assert len(data) == 11

            assert data[0]["date"] == "2015-01-01"
            assert int(data[0]["personcontact"]) == 1
            assert int(data[0]["companycontact"]) == 1
            assert int(data[0]["users"]) == 0

            assert data[1]["date"] == "2015-01-02"
            assert int(data[1]["personcontact"]) == 1
            assert int(data[1]["companycontact"]) == 0
            assert int(data[1]["users"]) == 0

            assert data[2]["date"] == "2015-03-03"
            assert int(data[2]["personcontact"]) == 2
            assert int(data[2]["companycontact"]) == 0
            assert int(data[2]["users"]) == 2

            assert data[3]["date"] == "2015-04-04"
            assert int(data[3]["personcontact"]) == 1
            assert int(data[3]["companycontact"]) == 0
            assert int(data[3]["users"]) == 1

            assert data[4]["date"] == "2015-08-08"
            assert int(data[4]["personcontact"]) == 0
            assert int(data[4]["companycontact"]) == 1
            assert int(data[4]["users"]) == 0

            assert data[5]["date"] == "2015-09-09"
            assert int(data[5]["personcontact"]) == 0
            assert int(data[5]["companycontact"]) == 1
            assert int(data[5]["users"]) == 0

            assert data[6]["date"] == "2016-02-02"
            assert int(data[6]["personcontact"]) == 1
            assert int(data[6]["companycontact"]) == 0
            assert int(data[6]["users"]) == 0

            assert data[7]["date"] == "2016-05-05"
            assert int(data[7]["personcontact"]) == 1
            assert int(data[7]["companycontact"]) == 0
            assert int(data[7]["users"]) == 1

            assert data[8]["date"] == "2016-06-06"
            assert int(data[8]["personcontact"]) == 1
            assert int(data[8]["companycontact"]) == 0
            assert int(data[8]["users"]) == 1

            assert data[9]["date"] == "2016-07-07"
            assert int(data[9]["personcontact"]) == 1
            assert int(data[9]["companycontact"]) == 0
            assert int(data[9]["users"]) == 1
Exemplo n.º 37
0
def test_product_total_sales_report(rf, admin_user, order_by):
    with override_provides("reports", [
            "shuup.default_reports.reports.product_total_sales:ProductSalesReport"
    ]):
        shop = get_default_shop()
        supplier = get_default_supplier(shop)
        product1 = create_product("product1", supplier=supplier, shop=shop)
        product2 = create_product("product2", supplier=supplier, shop=shop)

        p1_qtd, p1_price, p1_tr, p1_lines = Decimal(3), Decimal(5), Decimal(
            0), 5
        p2_qtd, p2_price, p2_tr, p2_lines = Decimal(4), Decimal(5), Decimal(
            0.95), 3

        order = create_order_with_product(
            product=product1,
            supplier=supplier,
            quantity=p1_qtd,
            taxless_base_unit_price=p1_price,
            tax_rate=p1_tr,
            n_lines=p1_lines,
            shop=shop,
        )
        order.create_payment(order.taxful_total_price.amount)

        order2 = create_order_with_product(
            product=product2,
            supplier=supplier,
            quantity=p2_qtd,
            taxless_base_unit_price=p2_price,
            tax_rate=p2_tr,
            n_lines=p2_lines,
            shop=shop,
        )
        order2.create_payment(order2.taxful_total_price.amount)

        data = {
            "report": ProductSalesReport.get_name(),
            "shop": shop.pk,
            "date_range": DateRangeChoices.ALL_TIME.value,
            "writer": "json",
            "force_download": 1,
            "order_by": order_by,
        }

        view = ReportView.as_view()
        request = apply_request_middleware(rf.post("/", data=data),
                                           user=admin_user)
        response = view(request)
        if hasattr(response, "render"):
            response.render()
        assert response.status_code == 200
        json_data = json.loads(response.content.decode("utf-8"))
        assert force_text(ProductSalesReport.title) in json_data.get("heading")

        data = json_data["tables"][0]["data"]
        assert len(data) == 2

        p1_total_qtd = p1_qtd * p1_lines
        p1_taxless_total = p1_total_qtd * p1_price
        p1_taxful_total = p1_taxless_total * (1 + p1_tr)

        p2_total_qtd = p2_qtd * p2_lines
        p2_taxless_total = p2_total_qtd * p2_price
        p2_taxful_total = p2_taxless_total * (1 + p2_tr)

        if order_by == "quantity":
            p1 = data[0]
            p2 = data[1]

        elif order_by == "taxless_total":
            p1 = data[0]
            p2 = data[1]

        else:  # order_by == "taxful_total":
            p1 = data[1]
            p2 = data[0]

        precision = Decimal("0.1")**2

        assert p1["product"] == product1.name
        assert Decimal(p1["quantity"]) == p1_total_qtd
        assert Decimal(
            p1["taxless_total"]) == p1_taxless_total.quantize(precision)
        assert Decimal(
            p1["taxful_total"]) == p1_taxful_total.quantize(precision)

        assert p2["product"] == product2.name
        assert Decimal(p2["quantity"]) == p2_total_qtd
        assert Decimal(
            p2["taxless_total"]) == p2_taxless_total.quantize(precision)
        assert Decimal(
            p2["taxful_total"]) == p2_taxful_total.quantize(precision)
Exemplo n.º 38
0
def test_contact_filters(rf, admin_user):
    shop = get_default_shop()
    products_per_order = 5

    request = rf.get("/")
    request.shop = shop
    apply_request_middleware(request)
    product = get_default_product()

    customer = get_person_contact(admin_user)
    create_order(request,
                 creator=admin_user,
                 customer=customer,
                 product=product)
    order_one = Order.objects.first()

    user = UserFactory()
    second_customer = get_person_contact(user)
    create_order(request,
                 creator=admin_user,
                 customer=second_customer,
                 product=product)
    order_two = Order.objects.first()

    user = UserFactory()
    user.is_staff = True
    user.save()

    create_order(request,
                 creator=user,
                 customer=second_customer,
                 product=product)
    order_three = Order.objects.first()
    order_three.orderer = customer
    order_three.save()

    # test that admin user gets two orders as he created two
    expected_taxful_total_price = order_one.taxful_total_price + order_two.taxful_total_price
    expected_taxless_total_price = order_one.taxless_total_price + order_two.taxless_total_price
    expected_order_count = 2
    test_info = initialize_simple_report(
        SalesReport, data_overrides={"creator": [admin_user.pk]})
    return_data = test_info.json_data.get("tables")[0].get("data")
    _assert_expected_values(expected_order_count, expected_taxful_total_price,
                            expected_taxless_total_price, products_per_order,
                            return_data)

    # test that new admin user gets one order
    expected_taxful_total_price = order_three.taxful_total_price
    expected_taxless_total_price = order_three.taxless_total_price
    expected_order_count = 1
    test_info = initialize_simple_report(SalesReport,
                                         data_overrides={"creator": [user.pk]})
    return_data = test_info.json_data.get("tables")[0].get("data")
    _assert_expected_values(expected_order_count, expected_taxful_total_price,
                            expected_taxless_total_price, products_per_order,
                            return_data)

    # test that new admin user and second_customer gets one order
    expected_taxful_total_price = order_three.taxful_total_price
    expected_taxless_total_price = order_three.taxless_total_price
    expected_order_count = 1
    test_info = initialize_simple_report(SalesReport,
                                         data_overrides={
                                             "creator": [user.pk],
                                             "customer": [second_customer.pk]
                                         })
    return_data = test_info.json_data.get("tables")[0].get("data")
    _assert_expected_values(expected_order_count, expected_taxful_total_price,
                            expected_taxless_total_price, products_per_order,
                            return_data)

    # test that second_customer gets two orders
    expected_taxful_total_price = order_three.taxful_total_price + order_two.taxful_total_price
    expected_taxless_total_price = order_three.taxless_total_price + order_two.taxless_total_price
    expected_order_count = 2
    test_info = initialize_simple_report(
        SalesReport, data_overrides={"customer": [second_customer.pk]})
    return_data = test_info.json_data.get("tables")[0].get("data")
    _assert_expected_values(expected_order_count, expected_taxful_total_price,
                            expected_taxless_total_price, products_per_order,
                            return_data)

    # test that second_customer gets two orders
    expected_taxful_total_price = order_three.taxful_total_price
    expected_taxless_total_price = order_three.taxless_total_price
    expected_order_count = 1
    test_info = initialize_simple_report(SalesReport,
                                         data_overrides={
                                             "customer": [second_customer.pk],
                                             "orderer": [customer.pk]
                                         })
    return_data = test_info.json_data.get("tables")[0].get("data")
    _assert_expected_values(expected_order_count, expected_taxful_total_price,
                            expected_taxless_total_price, products_per_order,
                            return_data)
Exemplo n.º 39
0
def test_product_from_category_plugin(rf):
    shop = get_default_shop()
    category1 = get_default_category()
    category2 = CategoryFactory(status=CategoryStatus.VISIBLE)

    category1.shops.add(shop)
    category2.shops.add(shop)

    p1 = create_product("p1", shop, get_default_supplier(), "10")
    p2 = create_product("p2", shop, get_default_supplier(), "20")
    p3 = create_product("p3", shop, get_default_supplier(), "30")

    sp1 = p1.get_shop_instance(shop)
    sp2 = p2.get_shop_instance(shop)
    sp3 = p3.get_shop_instance(shop)

    sp1.categories.add(category1)
    sp2.categories.add(category1)
    sp3.categories.add(category2)

    plugin = ProductsFromCategoryPlugin({
        "category": category1.pk,
        "cache_timeout": 120
    })
    plugin_context = plugin.get_context_data(get_context(rf, is_ajax=False))
    context_products = plugin_context["products"]

    assert len(context_products) == 0

    plugin_context = plugin.get_context_data(get_context(rf))
    context_data_url = plugin_context["data_url"]
    context_products = plugin_context["products"]
    assert p1 in context_products
    assert p2 in context_products
    assert p3 not in context_products

    check_expected_product_count(context_data_url, 2)
    check_expected_product_count(context_data_url,
                                 2)  # one for checking it is cached

    # test the plugin form
    with override_current_theme_class(None):
        theme = get_current_theme(get_default_shop())
        cell = LayoutCell(theme,
                          ProductsFromCategoryPlugin.identifier,
                          sizes={"md": 8})
        lcfg = LayoutCellFormGroup(layout_cell=cell,
                                   theme=theme,
                                   request=apply_request_middleware(
                                       rf.get("/")))
        assert not lcfg.is_valid()

        lcfg = LayoutCellFormGroup(
            data={
                "general-cell_width": "8",
                "general-cell_align": "pull-right",
                "plugin-count": 4,
                "plugin-category": category2.pk,
                "plugin-cache_timeout": 3600,
            },
            layout_cell=cell,
            theme=theme,
            request=apply_request_middleware(rf.get("/")),
        )
        assert lcfg.is_valid()
        lcfg.save()
        assert cell.config["category"] == str(category2.pk)
Exemplo n.º 40
0
def test_menu_arrange_view(rf, admin_user):
    url = reverse('shuup_admin:menu.arrange')
    request = apply_request_middleware(rf.get(url), user=admin_user)
    response = AdminMenuArrangeView.as_view()(request)
    assert response.status_code == 200
Exemplo n.º 41
0
def test_product_selection_plugin(rf):
    shop = get_default_shop()
    supplier = get_default_supplier()
    p1 = create_product("p1", shop, supplier, "10")
    p2 = create_product("p2", shop, supplier, "20")
    p3 = create_product("p3", shop, supplier, "30")
    p4 = create_product("p4", shop, supplier, "40")

    sp1 = p1.get_shop_instance(shop)
    sp2 = p2.get_shop_instance(shop)
    sp3 = p3.get_shop_instance(shop)

    plugin = ProductSelectionPlugin({
        "products": [sp1.product.pk, sp2.product.pk, sp3.product.pk],
        "cache_timeout":
        120
    })
    plugin_context = plugin.get_context_data(get_context(rf, is_ajax=False))
    context_products = plugin_context["products"]

    assert len(context_products) == 0

    plugin_context = plugin.get_context_data(get_context(rf))
    context_data_url = plugin_context["data_url"]
    context_products = plugin_context["products"]
    assert p1 in context_products
    assert p2 in context_products
    assert p3 in context_products
    assert p4 not in context_products

    check_expected_product_count(context_data_url, 3)
    check_expected_product_count(context_data_url,
                                 3)  # one for checking it is cached

    # test the plugin form
    with override_current_theme_class(None):
        theme = get_current_theme(get_default_shop())
        cell = LayoutCell(theme,
                          ProductSelectionPlugin.identifier,
                          sizes={"md": 8})
        lcfg = LayoutCellFormGroup(layout_cell=cell,
                                   theme=theme,
                                   request=apply_request_middleware(
                                       rf.get("/")))
        # not valid, products are required
        assert not lcfg.is_valid()

        lcfg = LayoutCellFormGroup(
            data={
                "general-cell_width": "8",
                "general-cell_align": "pull-right",
                "plugin-products": [p1.pk, p2.pk],
                "plugin-cache_timeout": 120,
            },
            layout_cell=cell,
            theme=theme,
            request=apply_request_middleware(rf.get("/")),
        )
        assert lcfg.is_valid()
        lcfg.save()
        assert cell.config["products"] == [str(p1.pk), str(p2.pk)]
Exemplo n.º 42
0
 def get_request():
     return apply_request_middleware(rf.get("/"))
Exemplo n.º 43
0
def test_product_media_bulk_adder(rf, admin_user):
    shop = get_default_shop()
    product = create_product("test-product", shop)
    f = File.objects.create(name="test")
    f2 = File.objects.create(name="test2")
    assert not ProductMedia.objects.count()

    view_func = ProductMediaBulkAdderView.as_view()
    # bad request - no params
    request = apply_request_middleware(rf.post("/"),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 400
    assert not ProductMedia.objects.count()
    # bad request - invalid shop
    request = apply_request_middleware(rf.post(
        "/", {
            "shop_id": 0,
            "file_ids": [f.id],
            "kind": "media"
        }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 400
    assert not ProductMedia.objects.count()
    # bad request - invalid product
    request = apply_request_middleware(rf.post("/", {
        "file_ids": [f.id],
        "kind": "media"
    }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=100)
    assert response.status_code == 400
    assert not ProductMedia.objects.count()
    # bad request - invalid kind
    request = apply_request_middleware(rf.post("/", {
        "file_ids": [f.id],
        "kind": "test"
    }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 400
    assert not ProductMedia.objects.count()
    # bad request - invalid file
    request = apply_request_middleware(rf.post("/", {
        "file_ids": [0],
        "kind": "media"
    }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 400
    assert not ProductMedia.objects.count()
    # bad request - empty file array
    request = apply_request_middleware(rf.post("/", {
        "file_ids": [],
        "kind": "media"
    }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 400
    assert not ProductMedia.objects.count()
    # add one file
    request = apply_request_middleware(rf.post("/", {
        "file_ids": [f.id],
        "kind": "media"
    }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 200
    assert ProductMedia.objects.filter(
        product_id=product.pk,
        file_id=f.id,
        kind=ProductMediaKind.GENERIC_FILE).exists()
    # add two files but one already exists
    request = apply_request_middleware(rf.post(
        "/", {
            "file_ids": [f.id, f2.id],
            "kind": "media"
        }),
                                       user=admin_user,
                                       shop=shop)
    response = view_func(request, pk=product.pk)
    assert response.status_code == 200
    assert ProductMedia.objects.count() == 2
    assert ProductMedia.objects.filter(
        product_id=product.pk,
        file_id=f2.id,
        kind=ProductMediaKind.GENERIC_FILE).exists()
Exemplo n.º 44
0
def test_discount_admin_list_view(rf, admin_user):
    with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True):
        for x in range(3):
            _test_discount_list_view(rf, x)

        # Superuser gets same data as shop staff
        shop = Shop.objects.exclude(identifier=factories.DEFAULT_IDENTIFIER).order_by("?").first()
        request = apply_request_middleware(
            rf.get("/", {"jq": json.dumps({"perPage": 100, "page": 1})}), user=admin_user, shop=shop
        )
        set_shop(request, shop)
        view_instance = DiscountListView()
        view_instance.request = request
        data = json.loads(view_instance.get(request).content.decode("UTF-8"))
        assert len(data["items"]) == 4

        # In active 3 discounts to see that those are filtered out
        payload = {
            "action": "archive_discounts",
            "values": [discount.pk for discount in Discount.objects.filter(shops=shop).order_by("?")[:3]],
        }
        archive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop)
        set_shop(archive_request, shop)
        archive_request._body = json.dumps(payload).encode("UTF-8")
        view = DiscountListView.as_view()
        response = view(request=archive_request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200
        assert Discount.objects.available(shop).count() == 1

        data = json.loads(view_instance.get(request).content.decode("UTF-8"))
        assert len(data["items"]) == 1

        # Archived list should now show 3 results
        archived_view_instance = ArchivedDiscountListView()
        archived_view_instance.request = request
        data = json.loads(archived_view_instance.get(request).content.decode("UTF-8"))
        assert len(data["items"]) == 3

        # Make sure rendering this archived discounts list works
        view_func = ArchivedDiscountListView.as_view()
        request = apply_request_middleware(rf.get("/"), user=admin_user, shop=shop)
        set_shop(request, shop)
        response = view_func(request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200

        # Unarchive all discounts
        payload = {"action": "unarchive_discounts", "values": "all"}
        unarchive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop)
        set_shop(unarchive_request, shop)
        unarchive_request._body = json.dumps(payload).encode("UTF-8")
        view = ArchivedDiscountListView.as_view()
        response = view(request=unarchive_request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200
        assert Discount.objects.available(shop).count() == 4

        # Re-archive all discounts
        payload = {"action": "archive_discounts", "values": "all"}
        archive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop)
        set_shop(archive_request, shop)
        archive_request._body = json.dumps(payload).encode("UTF-8")
        view = DiscountListView.as_view()
        response = view(request=archive_request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200
        assert Discount.objects.available(shop).count() == 0

        # Unarchive just one discount
        payload = {
            "action": "unarchive_discounts",
            "values": [discount.pk for discount in Discount.objects.filter(shops=shop).order_by("?")[:1]],
        }
        unarchive_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop)
        set_shop(unarchive_request, shop)
        unarchive_request._body = json.dumps(payload).encode("UTF-8")
        view = ArchivedDiscountListView.as_view()
        response = view(request=unarchive_request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200
        assert Discount.objects.available(shop).count() == 1

        # Delete one archived discount
        payload = {
            "action": "delete_discounts",
            "values": [discount.pk for discount in Discount.objects.archived(shop).order_by("?")[:1]],
        }
        delete_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop)
        set_shop(delete_request, shop)
        delete_request._body = json.dumps(payload).encode("UTF-8")
        view = ArchivedDiscountListView.as_view()
        response = view(request=delete_request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200
        assert Discount.objects.filter(shops=shop).count() == 3

        # Delete all for this shop only
        payload = {"action": "delete_discounts", "values": "all"}
        delete_request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop)
        set_shop(delete_request, shop)
        delete_request._body = json.dumps(payload).encode("UTF-8")
        view = ArchivedDiscountListView.as_view()
        response = view(request=delete_request)
        if hasattr(response, "render"):
            response.render()

        assert response.status_code == 200
        assert Discount.objects.filter(shops=shop).count() == 1  # Since only archived can be deleted with mass action
        assert Discount.objects.available(shop).count() == 1
        assert Discount.objects.archived(shop).count() == 0
        assert Discount.objects.count() == 9
Exemplo n.º 45
0
def _test_discount_list_view(rf, index):
    shop = factories.get_shop(identifier="shop%s" % index, enabled=True)
    staff_user = factories.create_random_user(is_staff=True)
    shop.staff_members.add(staff_user)

    discount1 = Discount.objects.create(identifier="discount_without_effects_%s" % index)
    discount1.shops.add(shop)
    discount2 = Discount.objects.create(
        identifier="discount_with_amount_value_only_%s" % index,
        discount_amount_value=20,
        start_datetime=now(),
        end_datetime=now() + datetime.timedelta(days=2),
    )
    discount2.shops.add(shop)
    discount3 = Discount.objects.create(
        identifier="discount_with_amount_and_discounted_price_%s" % index,
        discount_amount_value=20,
        discounted_price_value=4,
        start_datetime=now(),
        end_datetime=now() + datetime.timedelta(days=2),
    )
    discount3.shops.add(shop)
    discount4 = Discount.objects.create(
        identifier="test_with_discounted_price_and_percentage_%s" % index,
        discounted_price_value=4,
        discount_percentage=0.20,
        start_datetime=now(),
        end_datetime=now() + datetime.timedelta(days=2),
    )
    discount4.shops.add(shop)

    view_func = DiscountListView.as_view()
    request = apply_request_middleware(
        rf.get("/", {"jq": json.dumps({"perPage": 100, "page": 1})}), user=staff_user, shop=shop
    )
    set_shop(request, shop)
    response = view_func(request)
    if hasattr(response, "render"):
        response.render()
    assert response.status_code == 200

    view_instance = DiscountListView()
    view_instance.request = request
    assert request.shop == shop
    assert view_instance.get_queryset().count() == 4

    data = json.loads(view_instance.get(request).content.decode("UTF-8"))
    assert len(data["items"]) == 4
    discount1_data = [item for item in data["items"] if item["_id"] == discount1.pk][0]
    assert discount1_data["discount_effect"] == "-"

    discount2_data = [item for item in data["items"] if item["_id"] == discount2.pk][0]
    assert len(discount2_data["discount_effect"].split(",")) == 1
    assert "20" in discount2_data["discount_effect"]

    discount3_data = [item for item in data["items"] if item["_id"] == discount3.pk][0]
    assert len(discount3_data["discount_effect"].split(",")) == 2
    assert "20" in discount3_data["discount_effect"]
    assert "4" in discount3_data["discount_effect"]

    discount4_data = [item for item in data["items"] if item["_id"] == discount4.pk][0]
    assert len(discount4_data["discount_effect"].split(",")) == 2
    assert "20" in discount4_data["discount_effect"]
    assert "4" in discount4_data["discount_effect"]
Exemplo n.º 46
0
def test_address_phase_anonymous_user(rf):
    request = apply_request_middleware(rf.get("/"), shop=get_default_shop())
    view_func = AddressesPhase.as_view()
    resp = view_func(request)
    assert 'company' in resp.context_data['form'].form_defs
Exemplo n.º 47
0
def test_services_edit_view_formsets_in_new_mode(rf, admin_user, view):
    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__, ServiceBaseFormPart)
Exemplo n.º 48
0
 def test_shipment_delete_view(shipment, shop, user):
     request = apply_request_middleware(rf.post("/"), user=user, shop=shop)
     response = ShipmentDeleteView.as_view()(request, pk=shipment.pk, supplier_pk=supplier.pk)
Exemplo n.º 49
0
 def test_payment_delete_view(payment, shop, user):
     request = apply_request_middleware(rf.post("/"), user=user, shop=shop)
     response = OrderDeletePaymentView.as_view()(request, pk=payment.pk)
Exemplo n.º 50
0
def test_get_login_form(rf):
    from shuup.front.template_helpers import general
    request = apply_request_middleware(rf.get("/"), shop=get_default_shop())
    form = general.get_login_form(request=request)
    assert isinstance(form, EmailAuthenticationForm)
Exemplo n.º 51
0
def get_blocks(rf, admin_user):
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = HomeView.as_view()(request)
    assert response.status_code == 200
    return response.context_data.get("blocks", [])
Exemplo n.º 52
0
def test_create_company_from_customer_dashboard(
        allow_company_registration, company_registration_requires_approval,
        client, rf, admin_user):
    if "shuup.front.apps.registration" not in settings.INSTALLED_APPS:
        pytest.skip("shuup.front.apps.registration required in installed apps")

    shop = get_default_shop()
    configuration.set(None, "allow_company_registration",
                      allow_company_registration)
    configuration.set(None, "company_registration_requires_approval",
                      company_registration_requires_approval)

    Script.objects.create(
        event_identifier="company_registration_received",
        name="Send Company Registration Received Email",
        enabled=True,
        shop=shop,
        template="company_registration_received_email",
        _step_data=[{
            'conditions': [],
            'next':
            'stop',
            'cond_op':
            'all',
            'actions': [
                {
                    'fallback_language': {
                        'constant': 'en'
                    },
                    'template_data': {
                        'en': {
                            'content_type': 'html',
                            'subject': 'Company Registered',
                            'body': 'Waiting approval'
                        },
                    },
                    'recipient': {
                        'variable': 'customer_email'
                    },
                    'language': {
                        'variable': 'language'
                    },
                    'identifier': 'send_email'
                },
            ],
            'enabled':
            True
        }],
    )
    Script.objects.create(
        event_identifier="company_approved_by_admin",
        name="Send Company Activated Email",
        enabled=True,
        shop=shop,
        template="company_activated_email",
        _step_data=[{
            'actions': [{
                'fallback_language': {
                    'constant': 'en'
                },
                'template_data': {
                    'en': {
                        'content_type':
                        'html',
                        'subject':
                        'Company activated',
                        'body':
                        'Company has been approved. '
                        'Please activate your account by clicking the link: {{activation_url}}'
                    },
                },
                'recipient': {
                    'variable': 'customer_email'
                },
                'language': {
                    'variable': 'language'
                },
                'identifier': 'send_email'
            }],
            'enabled':
            True,
            'next':
            'stop',
            'conditions': [],
            'cond_op':
            'all'
        }])
    # This view creates CompanyContact object for already registered user
    view_func = CompanyEditView.as_view()

    if not allow_company_registration:
        # If company registration is not allowed,
        # can't create company contacts from customer dashboard
        request = apply_request_middleware(rf.get("/"), user=admin_user)
        response = view_func(request)
        assert response.status_code == 404
    else:
        request = apply_request_middleware(rf.post(
            "/", {
                'contact-name': "Test company",
                'contact-name_ext': "test",
                'contact-tax_number': "12345",
                'contact-email': "*****@*****.**",
                'contact-phone': "123123",
                'contact-www': "",
                'billing-name': "testa tesat",
                'billing-phone': "testa tesat",
                'billing-email': email,
                'billing-street': "testa tesat",
                'billing-street2': "",
                'billing-postal_code': "12345",
                'billing-city': "test test",
                'billing-region': "",
                'billing-region_code': "",
                'billing-country': "FI",
                'shipping-name': "testa tesat",
                'shipping-phone': "testa tesat",
                'shipping-email': email,
                'shipping-street': "testa tesat",
                'shipping-street2': "",
                'shipping-postal_code': "12345",
                'shipping-city': "test test",
                'shipping-region': "",
                'shipping-region_code': "",
                'shipping-country': "FI",
            }),
                                           user=admin_user)
        response = view_func(request)
        if company_registration_requires_approval:
            # CompanyContact was created as inactive but PersonContact stays active
            assert CompanyContact.objects.filter(is_active=False).count() == 1
            assert PersonContact.objects.filter(is_active=True).count() == 1
            assert mail.outbox[0].subject == "Company Registered"
            # Activate new CompanyContact from admin
            request = apply_request_middleware(rf.post("/",
                                                       {"set_is_active": "1"}),
                                               user=admin_user)
            view_func = ContactDetailView.as_view()
            response = view_func(request, pk=CompanyContact.objects.first().pk)
            urls = re.findall(
                'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                mail.outbox[1].body)
            assert mail.outbox[1].subject == "Company activated"
            assert CompanyContact.objects.filter(is_active=True).count() == 1
        else:
            assert CompanyContact.objects.filter(is_active=True).count() == 1
            assert PersonContact.objects.filter(is_active=True).count() == 1

        contact = PersonContact.objects.first()
        assert contact.in_shop(shop)
        assert contact.in_shop(shop, only_registration=True)  # registered here

        company = CompanyContact.objects.first()
        assert company.in_shop(shop)
        assert company.in_shop(shop, only_registration=True)  # registered here
Exemplo n.º 53
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 = OrderEditView.as_view()(request)
    assert_contains(response, "unknown command", status_code=400)
Exemplo n.º 54
0
 def test_shipment_view(order, shop, supplier, user):
     request = apply_request_middleware(rf.get("/"), user=user, shop=shop)
     response = OrderCreateShipmentView.as_view()(request, pk=order.pk, supplier_pk=supplier.pk)
Exemplo n.º 55
0
def test_supplier_create(rf, admin_user):
    shop = factories.get_default_shop()
    edit_view = SupplierEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = edit_view(request, **{"pk": None})
    assert response.status_code == 200
Exemplo n.º 56
0
def test_cms_block(rf, admin_user):
    shop = get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = HomeView.as_view()(request)
    assert not any("web page" in b.text
                   for b in response.context_data["blocks"])
Exemplo n.º 57
0
def test_company_registration(django_user_model, client,
                              allow_company_registration,
                              company_registration_requires_approval, rf,
                              admin_user):
    if "shuup.front.apps.registration" not in settings.INSTALLED_APPS:
        pytest.skip("shuup.front.apps.registration required in installed apps")

    shop = get_default_shop()

    configuration.set(shop, "allow_company_registration",
                      allow_company_registration)
    configuration.set(shop, "company_registration_requires_approval",
                      company_registration_requires_approval)

    url = reverse("shuup:registration_register_company")
    Script.objects.create(
        event_identifier="company_approved_by_admin",
        name="Send Company Activated Email",
        enabled=True,
        shop=shop,
        template="company_activated_email",
        _step_data=[{
            'actions': [{
                'fallback_language': {
                    'constant': 'en'
                },
                'template_data': {
                    'en': {
                        'content_type':
                        'html',
                        'subject':
                        'Company activated',
                        'body':
                        'Company has been approved. '
                        'Please activate your account by clicking the link: {{activation_url}}'
                    },
                },
                'recipient': {
                    'variable': 'customer_email'
                },
                'language': {
                    'variable': 'language'
                },
                'identifier': 'send_email'
            }],
            'enabled':
            True,
            'next':
            'stop',
            'conditions': [],
            'cond_op':
            'all'
        }])
    Script.objects.create(
        event_identifier="company_registration_received",
        name="Send Company Registration Received Email",
        enabled=True,
        shop=shop,
        template="company_registration_received_email",
        _step_data=[{
            'conditions': [],
            'next':
            'stop',
            'cond_op':
            'all',
            'actions': [{
                'fallback_language': {
                    'constant': 'en'
                },
                'template_data': {
                    'en': {
                        'content_type': 'html',
                        'subject': 'Generic welcome message',
                        'body': 'Welcome!'
                    },
                },
                'recipient': {
                    'variable': 'customer_email'
                },
                'language': {
                    'variable': 'language'
                },
                'identifier': 'send_email'
            }, {
                'fallback_language': {
                    'constant': 'en'
                },
                'template_data': {
                    'en': {
                        'content_type': 'plain',
                        'subject': 'New company registered',
                        'body': 'New company registered'
                    },
                },
                'recipient': {
                    'constant': '*****@*****.**'
                },
                'language': {
                    'constant': 'en'
                },
                'identifier': 'send_email'
            }],
            'enabled':
            True
        }],
    )
    if not allow_company_registration:
        response = client.get(url)
        assert response.status_code == 404
    else:
        response = client.post(url,
                               data={
                                   'company-name': "Test company",
                                   'company-name_ext': "test",
                                   'company-tax_number': "12345",
                                   'company-email': "*****@*****.**",
                                   'company-phone': "123123",
                                   'company-www': "",
                                   'billing-street': "testa tesat",
                                   'billing-street2': "",
                                   'billing-postal_code': "12345",
                                   'billing-city': "test test",
                                   'billing-region': "",
                                   'billing-region_code': "",
                                   'billing-country': "FI",
                                   'contact_person-first_name': "Test",
                                   'contact_person-last_name': "Tester",
                                   'contact_person-email': email,
                                   'contact_person-phone': "123",
                                   'user_account-username': username,
                                   'user_account-password1': "password",
                                   'user_account-password2': "password",
                               })

        user = django_user_model.objects.get(username=username)
        contact = PersonContact.objects.get(user=user)
        company = CompanyContact.objects.get(members__in=[contact])

        # one of each got created
        assert django_user_model.objects.count(
        ) == 2  # admin_user + registered user
        assert PersonContact.objects.count() == 1
        assert CompanyContact.objects.count() == 1

        if company_registration_requires_approval:
            assert PersonContact.objects.filter(is_active=False).count() == 1
            assert PersonContact.objects.filter(
                user__is_active=False).count() == 1
            assert CompanyContact.objects.filter(is_active=False).count() == 1
            assert mail.outbox[0].subject == "Generic welcome message"
            assert mail.outbox[1].subject == "New company registered"
            # Activating Company for the first time from admin triggers company_approved_by_admin event
            request = apply_request_middleware(rf.post("/",
                                                       {"set_is_active": "1"}),
                                               user=admin_user)
            view_func = ContactDetailView.as_view()
            response = view_func(request, pk=company.pk)
            urls = re.findall(
                'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
                mail.outbox[2].body)
            assert mail.outbox[2].subject == "Company activated"
            assert user.registrationprofile.activation_key in urls[0]
            # User receives link to activate his own account
            response = client.get(urls[0], follow=True)
            user.refresh_from_db()
            assert user.is_active is True
        else:
            assert PersonContact.objects.filter(is_active=True).count() == 1

            # Since we don't support company registration without the activation
            # the user here is still False. Then it is up to merchant to customize
            # the activation notification so that the activation email is sent to
            # the newly created user. This is tested in the previous unit test.
            assert PersonContact.objects.filter(
                user__is_active=False).count() == 1
            assert CompanyContact.objects.filter(is_active=True).count() == 1
            assert mail.outbox[0].subject == "Generic welcome message"

        contact = PersonContact.objects.first()
        assert contact.in_shop(shop)
        assert contact.in_shop(shop, only_registration=True)  # registered here

        company = CompanyContact.objects.first()
        assert company.in_shop(shop)
        assert company.in_shop(shop, only_registration=True)  # registered here
Exemplo n.º 58
0
def test_order_creator_view_GET(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response =OrderEditView.as_view()(request)
    assert_contains(response, "shippingMethods")  # in the config
    assert_contains(response, "shops")  # in the config
Exemplo n.º 59
0
def test_contact_group_delete_button(rf, admin_user):
    get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    check_for_delete(request, get_default_customer_group(), True)
Exemplo n.º 60
0
def test_content_wizard_pane2(rf, admin_user, settings):
    settings.SHUUP_SETUP_WIZARD_PANE_SPEC = [
        "shuup.testing.modules.content.views.ContentWizardPane"
    ]

    shop = get_default_shop()
    request = apply_request_middleware(rf.get("/"), user=admin_user)

    settings.INSTALLED_APPS.remove("shuup.simple_cms")
    settings.INSTALLED_APPS.remove("shuup.xtheme")
    settings.INSTALLED_APPS.remove("shuup.notify")

    # no pane, because ContentWizardPane is invalid (no necessary app installed)
    assert wizard.load_setup_wizard_panes(shop, request) == []
    assert wizard.load_setup_wizard_panes(shop, request,
                                          visible_only=False) == []
    pane_data = {
        'pane_id': 'content',
        'content-privacy_policy': True,
        'content-terms_conditions': True,
        'content-refund_policy': True,
        'content-about_us': True,
        'content-configure_footer': True,
        'behaviors-order_confirm_notification': True
    }

    request = apply_request_middleware(rf.get("/"), skip_session=True)
    response = WizardView.as_view()(request)
    assert response.status_code == 302
    assert response["Location"].startswith(reverse("shuup:login"))

    # add the simple cms - create only the pages and footer
    request = apply_request_middleware(rf.get("/"),
                                       user=admin_user,
                                       skip_session=True)
    settings.INSTALLED_APPS.append("shuup.simple_cms")
    assert len(
        wizard.load_setup_wizard_panes(shop, request, visible_only=False)) == 1
    request = apply_request_middleware(rf.post("/", data=pane_data),
                                       user=admin_user)
    response = WizardView.as_view()(request)
    assert response.status_code == 200
    assert Page.objects.count() == 4
    assert SavedViewConfig.objects.count() == 0
    assert Script.objects.count() == 0
    settings.INSTALLED_APPS.remove("shuup.simple_cms")
    Page.objects.all().delete()

    # add the xtheme - create the footer
    settings.INSTALLED_APPS.append("shuup.xtheme")
    assert len(
        wizard.load_setup_wizard_panes(shop, request, visible_only=False)) == 1
    request = apply_request_middleware(rf.post("/", data=pane_data),
                                       user=admin_user)
    response = WizardView.as_view()(request)
    assert response.status_code == 200
    assert Page.objects.count() == 0
    assert SavedViewConfig.objects.count() == 1
    assert Script.objects.count() == 0
    settings.INSTALLED_APPS.remove("shuup.xtheme")
    SavedViewConfig.objects.all().delete()

    # add the notify - create only the notification
    settings.INSTALLED_APPS.append("shuup.notify")
    assert len(
        wizard.load_setup_wizard_panes(shop, request, visible_only=False)) == 1
    request = apply_request_middleware(rf.post("/", data=pane_data),
                                       user=admin_user)
    response = WizardView.as_view()(request)
    assert response.status_code == 200
    assert Page.objects.count() == 0
    assert SavedViewConfig.objects.count() == 0
    assert Script.objects.count() == 1
    settings.INSTALLED_APPS.remove("shuup.notify")
    Script.objects.all().delete()

    settings.INSTALLED_APPS.append("shuup.simple_cms")
    settings.INSTALLED_APPS.append("shuup.xtheme")
    settings.INSTALLED_APPS.append("shuup.notify")