Exemplo n.º 1
0
def test_set_non_shop_member_customer(rf):
    """
    Set some customer to the basket that is not member of the shop
    """
    with override_settings(**CORE_BASKET_SETTINGS):
        shop = factories.get_shop(False)
        assert shop != factories.get_default_shop()

        user = factories.create_random_user()
        request = apply_request_middleware(rf.get("/"), user=user)
        basket = get_basket(request, "basket")
        basket.customer = get_person_contact(user)
        assert basket.shop == factories.get_default_shop()

        person = factories.create_random_person()
        person.shops.add(shop)

        company = factories.create_random_company()
        company.shops.add(shop)

        for customer in [person, company]:
            with pytest.raises(ValidationError) as exc:
                basket_commands.handle_set_customer(request, basket, customer)
            assert exc.value.code == "invalid_customer_shop"
            assert basket.customer == get_person_contact(user)
Exemplo n.º 2
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)

    # 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)
Exemplo n.º 3
0
    def new(self, request, *args, **kwargs):
        """
        Create a brand new basket object
        """
        serializer = NewBasketSerializer(data=request.data)
        serializer.is_valid(True)
        data = serializer.validated_data

        self.process_request(with_basket=False, shop=data.get("shop"))
        basket_class = cached_load("WSHOP_BASKET_CLASS_SPEC")
        basket = basket_class(request._request)

        if "customer" in data:
            customer = data["customer"]
        else:
            customer = get_company_contact(request.user) or get_person_contact(
                request.user)

        orderer = data.get("orderer", get_person_contact(request.user))

        # set the request basket to perform the basket command
        self.request.basket = basket
        self._handle_set_customer(request=self.request._request,
                                  basket=basket,
                                  customer=customer,
                                  orderer=orderer)

        stored_basket = basket.save()
        response_data = {
            "uuid": "%s-%s" % (request.shop.pk, stored_basket.key)
        }
        response_data.update(self.get_serializer(basket).data)
        return Response(data=response_data, status=status.HTTP_201_CREATED)
Exemplo n.º 4
0
    def register(self, form):
        user = super(RegistrationViewMixin, self).register(form)

        if settings.WSHOP_ENABLE_MULTIPLE_SHOPS and settings.WSHOP_MANAGE_CONTACTS_PER_SHOP:
            get_person_contact(user).shops.add(self.request.shop)

        return user
Exemplo n.º 5
0
def test_login_as_user(rf, admin_user, regular_user):
    get_default_shop()
    view_func = LoginAsUserView.as_view()
    request = apply_request_middleware(rf.post("/"), user=admin_user)
    get_person_contact(regular_user)
    response = view_func(request, pk=regular_user.pk)
    assert response["location"] == reverse("wshop:index")
    assert get_user(request) == regular_user
Exemplo n.º 6
0
def test_omniscience(admin_user, regular_user):
    assert not get_person_contact(admin_user).is_all_seeing
    configuration.set(None, get_all_seeing_key(admin_user), True)
    assert get_person_contact(admin_user).is_all_seeing
    assert not get_person_contact(regular_user).is_all_seeing
    assert not get_person_contact(None).is_all_seeing
    assert not get_person_contact(AnonymousUser()).is_all_seeing
    assert not AnonymousContact().is_all_seeing
    configuration.set(None, get_all_seeing_key(admin_user), False)
Exemplo n.º 7
0
 def _set_person(self, request):
     request.person = get_person_contact(request.user)
     if not request.person.is_active:
         messages.add_message(
             request, messages.INFO,
             _("Logged out since this account is inactive."))
         logout(request)
         # Usually logout is connected to the `refresh_on_logout`
         # method via a signal and that already sets request.person
         # to anonymous, but set it explicitly too, just to be sure
         request.person = get_person_contact(None)
Exemplo n.º 8
0
def test_product_query(visibility, show_in_list, show_in_search, admin_user,
                       regular_user):
    shop = get_default_shop()
    product = create_product("test-sku", shop=shop)
    shop_product = product.get_shop_instance(shop)
    anon_contact = AnonymousContact()
    regular_contact = get_person_contact(regular_user)
    admin_contact = get_person_contact(admin_user)

    shop_product.visibility = visibility
    shop_product.save()

    assert shop_product.visibility_limit == ProductVisibility.VISIBLE_TO_ALL

    # Anonymous contact should be the same as no contact
    assert (product in Product.objects.listed(shop=shop)) == show_in_list
    assert (product in Product.objects.searchable(shop=shop)) == show_in_search
    assert (product
            in Product.objects.listed(shop=shop,
                                      customer=anon_contact)) == show_in_list
    assert (product in Product.objects.searchable(
        shop=shop, customer=anon_contact)) == show_in_search

    # Admin should see all non-deleted results
    configuration.set(None, get_all_seeing_key(admin_contact), True)
    assert product in Product.objects.listed(shop=shop, customer=admin_contact)
    assert product in Product.objects.searchable(shop=shop,
                                                 customer=admin_contact)

    # Anonymous contact shouldn't see products with logged in visibility limit
    shop_product.visibility_limit = ProductVisibility.VISIBLE_TO_LOGGED_IN
    shop_product.save()
    assert product not in Product.objects.listed(shop=shop,
                                                 customer=anon_contact)
    assert product not in Product.objects.searchable(shop=shop,
                                                     customer=anon_contact)

    # Reset visibility limit
    shop_product.visibility_limit = ProductVisibility.VISIBLE_TO_ALL
    shop_product.save()

    # No one should see deleted products
    product.soft_delete()
    assert product not in Product.objects.listed(shop=shop)
    assert product not in Product.objects.searchable(shop=shop)
    assert product not in Product.objects.listed(shop=shop,
                                                 customer=admin_contact)
    assert product not in Product.objects.searchable(shop=shop,
                                                     customer=admin_contact)
    configuration.set(None, get_all_seeing_key(admin_contact), False)
Exemplo n.º 9
0
def send_user_registered_notification(user, request, **kwargs):
    activation_url = None
    person_contact = get_person_contact(user)
    activation_key = user.registrationprofile.activation_key if hasattr(
        user, 'registrationprofile') else None
    if activation_key:
        activation_path = reverse('wshop:registration_activate',
                                  args=(activation_key, ))
        activation_url = request.build_absolute_uri(activation_path)

    customer = person_contact
    cls = RegistrationReceived
    email = user.email

    if person_contact:
        company = person_contact.company_memberships.first()
        if company:
            customer = company
            cls = CompanyRegistrationReceived
            email = user.email or company.email
    event = cls(
        customer=customer,
        customer_email=email,
        activation_url=activation_url,
        user_is_active=user.is_active,
    )
    event.run(shop=request.shop)
Exemplo n.º 10
0
def test_category_group_visibilities(regular_user):
    regular_contact = get_person_contact(regular_user)
    silver_group = ContactGroup.objects.create(identifier="silver")
    diamond_group = ContactGroup.objects.create(identifier="gold")
    regular_contact.groups.add(silver_group)


    silvers = Category.objects.create(
        status=CategoryStatus.VISIBLE,
        visibility=CategoryVisibility.VISIBLE_TO_GROUPS,
        identifier="silver_groups",
        name="Silvers")
    silvers.visibility_groups.add(regular_contact.get_default_group(), silver_group)

    diamonds = Category.objects.create(
        status=CategoryStatus.VISIBLE,
        visibility=CategoryVisibility.VISIBLE_TO_GROUPS,
        identifier="silver_and_diamonds_groups",
        name="Diamonds")
    diamonds.visibility_groups.add(diamond_group)

    # Multiple groups for contact should not cause duplicate results
    assert Category.objects.all_visible(customer=regular_contact).count() == 1

    regular_contact.groups.add(diamond_group)
    assert Category.objects.all_visible(customer=regular_contact).count() == 2
Exemplo n.º 11
0
def test_category_deletion(admin_user):
    admin = get_person_contact(admin_user)
    category = get_default_category()
    category.children.create(identifier="foo")
    shop_product = get_default_shop_product()
    shop_product.categories.add(category)
    shop_product.primary_category = category
    shop_product.save()

    configuration.set(None, get_all_seeing_key(admin), True)

    assert category.status == CategoryStatus.VISIBLE
    assert category.children.count() == 1

    with pytest.raises(NotImplementedError):
        category.delete()

    category.soft_delete()
    shop_product.refresh_from_db()
    shop_product.product.refresh_from_db()

    assert shop_product.categories.count() == 0
    assert shop_product.primary_category is None
    assert category.status == CategoryStatus.DELETED
    assert category.children.count() == 0
    # the child category still exists
    assert Category.objects.all_visible(customer=admin).count() == 1
    assert Category.objects.all_except_deleted().count() == 1
    configuration.set(None, get_all_seeing_key(admin), False)
Exemplo n.º 12
0
def test_company_edit_form_links_company(regular_user,
                                         allow_company_registration):
    get_default_shop()
    configuration.set(None, "allow_company_registration",
                      allow_company_registration)
    person = get_person_contact(regular_user)
    assert not get_company_contact(regular_user)

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

    data = default_company_data()
    data.update(default_address_data("billing"))
    data.update(default_address_data("shipping"))
    company_edit_url = reverse("wshop:company_edit")

    if allow_company_registration:
        soup = client.soup(company_edit_url)
        response, soup = client.response_and_soup(company_edit_url, data,
                                                  "post")
        assert response.status_code == 302
        assert get_company_contact(regular_user)
    else:
        response = client.get(company_edit_url)
        assert response.status_code == 404
        response = client.post(company_edit_url, data)
        assert response.status_code == 404
Exemplo n.º 13
0
def seed_source(user, shop):
    source = BasketishOrderSource(shop)
    source.status = get_initial_order_status()
    source.customer = get_person_contact(user)
    source.payment_method = get_default_payment_method()
    source.shipping_method = get_default_shipping_method()
    return source
Exemplo n.º 14
0
def test_product_unsupplied(admin_user):
    shop_product = get_default_shop_product()
    fake_supplier = Supplier.objects.create(identifier="fake")
    admin_contact = get_person_contact(admin_user)

    with modify(shop_product, visibility_limit=ProductVisibility.VISIBLE_TO_ALL, orderable=True):
        assert any(ve.code == "invalid_supplier" for ve in shop_product.get_orderability_errors(supplier=fake_supplier, customer=admin_contact, quantity=1))
Exemplo n.º 15
0
    def form_valid(self, form):
        company = form["contact"].save(commit=False)
        is_new = not bool(company.pk)
        company.save()
        user = self.request.user
        person = get_person_contact(user)
        company.members.add(person)
        billing_address = form["billing"].save()
        shipping_address = form["shipping"].save()
        if billing_address.pk != company.default_billing_address_id:  # Identity changed due to immutability
            company.default_billing_address = billing_address
        if shipping_address.pk != company.default_shipping_address_id:  # Identity changed due to immutability
            company.default_shipping_address = shipping_address

        message = _("Company information saved successfully.")
        # If company registration requires activation,
        # company will be created as inactive.
        if is_new and configuration.get(
                None, "company_registration_requires_approval"):
            company.is_active = False
            message = _(
                "Company information saved successfully. "
                "Please follow the instructions sent to your email address.")

        company.save()
        if is_new:
            user_registered.send(sender=self.__class__,
                                 user=self.request.user,
                                 request=self.request)
            CompanyAccountCreated(
                contact=company,
                customer_email=company.email).run(shop=self.request.shop)

        messages.success(self.request, message)
        return redirect("wshop:company_edit")
Exemplo n.º 16
0
 def get_form(self, form_class):
     user = self.request.user
     company = get_company_contact(user)
     person = get_person_contact(user)
     form_group = FormGroup(**self.get_form_kwargs())
     address_form_class = cached_load("WSHOP_ADDRESS_MODEL_FORM")
     form_group.add_form_def("billing",
                             address_form_class,
                             kwargs={
                                 "instance":
                                 _get_default_address_for_contact(
                                     company, "default_billing_address",
                                     person)
                             })
     form_group.add_form_def("shipping",
                             address_form_class,
                             kwargs={
                                 "instance":
                                 _get_default_address_for_contact(
                                     company, "default_shipping_address",
                                     person)
                             })
     form_group.add_form_def("contact",
                             CompanyContactForm,
                             kwargs={"instance": company})
     return form_group
Exemplo n.º 17
0
def test_add_product_with_extra_parent_line(rf):
    """
    Add product to basket with extra info and parent line
    """
    with override_settings(**CORE_BASKET_SETTINGS):
        shop = factories.get_default_shop()
        user = factories.create_random_user()
        product = factories.create_product("product", shop, factories.get_default_supplier(), 10)
        request = apply_request_middleware(rf.get("/"), user=user)
        basket = get_basket(request, "basket")
        basket.customer = get_person_contact(user)

        cmd_response = basket_commands.handle_add(request, basket, product.id, 1, extra={"more": "stuff"})
        line_id1 = cmd_response["line_id"]
        assert cmd_response["ok"]
        line1 = basket.get_basket_line(line_id1)
        assert line1._data["more"] == "stuff"

        cmd_response = basket_commands.handle_add(
            request, basket, product.id, 1, parent_line=line1, force_new_line=True)
        line_id2 = cmd_response["line_id"]
        assert cmd_response["ok"]
        line2 = basket.get_basket_line(line_id2)
        assert not line2._data

        assert line_id1 != line_id2
        assert line2.parent_line.line_id == line_id1
Exemplo n.º 18
0
def test_product_minimum_order_quantity(admin_user):
    shop_product = get_default_shop_product()
    supplier = get_default_supplier()
    admin_contact = get_person_contact(admin_user)

    with modify(shop_product, visibility_limit=ProductVisibility.VISIBLE_TO_ALL, orderable=True, minimum_purchase_quantity=10):
        assert any(ve.code == "purchase_quantity_not_met" for ve in shop_product.get_orderability_errors(supplier=supplier, customer=admin_contact, quantity=1))
        assert not any(ve.code == "purchase_quantity_not_met" for ve in shop_product.get_orderability_errors(supplier=supplier, customer=admin_contact, quantity=15))
Exemplo n.º 19
0
def test_address_phase_authorized_user(rf, admin_user):
    request = apply_request_middleware(rf.get("/"),
                                       shop=get_default_shop(),
                                       customer=get_person_contact(admin_user),
                                       user=admin_user)
    view_func = AddressesPhase.as_view()
    resp = view_func(request)
    assert 'company' not in resp.context_data['form'].form_defs
Exemplo n.º 20
0
def test_get_company_contact(regular_user):
    person_contact = get_person_contact(regular_user)
    assert person_contact != AnonymousContact()
    assert not get_company_contact(regular_user)

    company_contact = create_random_company()
    company_contact.members.add(person_contact)
    assert get_company_contact(regular_user) == company_contact
Exemplo n.º 21
0
def test_set_company_customer(rf):
    """
    Set a company as the basket customer
    """
    with override_settings(**CORE_BASKET_SETTINGS):
        user = factories.create_random_user()
        request = apply_request_middleware(rf.get("/"), user=user)
        basket = get_basket(request, "basket")
        basket.customer = get_person_contact(user)

        person = factories.create_random_person()
        company = factories.create_random_company()

        # no orderer provided
        with pytest.raises(ValidationError) as exc:
            basket_commands.handle_set_customer(request, basket, company)
        assert exc.value.code == "invalid_orderer"
        assert basket.customer == get_person_contact(user)

        # orderer provided but not member of the company
        with pytest.raises(ValidationError) as exc:
            basket_commands.handle_set_customer(request, basket, company, person)
        assert exc.value.code == "orderer_not_company_member"
        assert basket.customer == get_person_contact(user)

        # orderer provided but user not member of the company
        company.members.add(person)
        with pytest.raises(ValidationError) as exc:
            basket_commands.handle_set_customer(request, basket, company, person)
        assert exc.value.code == "not_company_member"
        assert basket.customer == get_person_contact(user)

        # staff and admin can add any the company and orderer without being member of the company
        superuser = factories.create_random_user(is_superuser=True)
        staff = factories.create_random_user(is_staff=True)
        basket.shop.staff_members.add(staff)

        for user in [superuser, staff]:
            basket.customer = None
            basket.orderer = None

            request = apply_request_middleware(rf.get("/"), user=user)
            assert basket_commands.handle_set_customer(request, basket, company, person)["ok"] is True
            assert basket.customer == company
            assert basket.orderer == person
Exemplo n.º 22
0
def test_product_order_multiple(admin_user):
    shop_product = get_default_shop_product()
    supplier = get_default_supplier()
    admin_contact = get_person_contact(admin_user)

    with modify(shop_product, visibility_limit=ProductVisibility.VISIBLE_TO_ALL, orderable=True, purchase_multiple=7):
        assert any(ve.code == "invalid_purchase_multiple" for ve in shop_product.get_orderability_errors(supplier=supplier, customer=admin_contact, quantity=4))
        assert any(ve.code == "invalid_purchase_multiple" for ve in shop_product.get_orderability_errors(supplier=supplier, customer=admin_contact, quantity=25))
        assert not any(ve.code == "invalid_purchase_multiple" for ve in shop_product.get_orderability_errors(supplier=supplier, customer=admin_contact, quantity=49))
Exemplo n.º 23
0
def test_address_ownership(admin_user):
    address = get_address()
    address.save()
    saved = SavedAddress(address=address)
    saved.owner = get_person_contact(admin_user)
    assert saved.get_title(
    ), u"get_title does what it should even if there is no explicit title"
    saved.title = u"My favorite address"
    assert saved.get_title(
    ) == saved.title, u"get_title does what it should when there is an explicit title"
    assert six.text_type(
        saved) == saved.get_title(), u"str() is an alias for .get_title()"
    saved.full_clean()
    saved.save()
    assert SavedAddress.objects.for_owner(get_person_contact(admin_user)).filter(address=address).exists(), \
        "contacts can save addresses"
    assert SavedAddress.objects.for_owner(
        None).count() == 0, "Ownerless saved addresses aren't a real thing"
Exemplo n.º 24
0
def test_companies(django_user_model):
    peons = [django_user_model.objects.create_user('Peon-%d' % x, '*****@*****.**' % x, 'password') for x in range(10)]
    for cx in range(10):
        company = CompanyContact.objects.create(name="Company %d" % cx, tax_number="FI2101%d" % cx)
        assert str(company)
        for x in range(5):
            off = (cx * 3 + x) % len(peons)
            contact = get_person_contact(user=peons[off])
            company.members.add(contact)
Exemplo n.º 25
0
def _seed_source(shop, user, shipping_country, billing_country):
    source = BasketishOrderSource(shop)
    billing_address = get_address(country=billing_country)
    shipping_address = get_address(name="Test street", country=shipping_country)
    source.status = get_initial_order_status()
    source.billing_address = billing_address
    source.shipping_address = shipping_address
    source.customer = get_person_contact(user)
    return source
Exemplo n.º 26
0
def test_set_from_anonymous_to_customer_auth(rf):
    """
    Set some random customer to the basket when authenticated
    """
    with override_settings(**CORE_BASKET_SETTINGS):
        user = factories.create_random_user()
        request = apply_request_middleware(rf.get("/"), user=user)
        basket = get_basket(request, "basket")
        basket.customer = AnonymousContact()

        # can not set the customer for something different as the request customer
        with pytest.raises(ValidationError) as exc:
            basket_commands.handle_set_customer(request, basket, factories.create_random_person())
        assert exc.value.code == "no_permission"
        assert basket.customer == AnonymousContact()

        assert basket_commands.handle_set_customer(request, basket, get_person_contact(user))["ok"] is True
        assert basket.customer == get_person_contact(user)
Exemplo n.º 27
0
def test_basic_order_flow_registered(regular_user):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    get_test_script("test script", "order_received")
    # paths
    addresses_path = reverse("wshop:checkout", kwargs={"phase": "addresses"})
    methods_path = reverse("wshop:checkout", kwargs={"phase": "methods"})
    confirm_path = reverse("wshop:checkout", kwargs={"phase": "confirm"})

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

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

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

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

        product_ids = _populate_client_basket(c)

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

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

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

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

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

        # mail is always sent in fallback language since user is not registered
        assert latest_mail.subject == template_data[lang][
            "subject"], "Subject doesn't match"
        assert latest_mail.body == template_data[lang][
            "body"], "Body doesn't match"
Exemplo n.º 28
0
def test_cart_delete(rf, regular_user):
    cart = _save_cart_with_products(rf, regular_user)
    request = apply_request_middleware(
        rf.post("/"),
        customer=get_person_contact(regular_user),
        user=regular_user)
    response = CartDeleteView.as_view()(request, pk=cart.pk)
    cart.refresh_from_db()
    assert response.status_code == 200
    assert cart.deleted, "cart deleted successfully"
Exemplo n.º 29
0
def test_intra_request_user_changing(rf, regular_user):
    get_default_shop()  # Create a shop
    mw = WshopFrontMiddleware()
    request = apply_request_middleware(rf.get("/"), user=regular_user)
    mw.process_request(request)
    assert request.person == get_person_contact(regular_user)
    logout(request)
    assert request.user == AnonymousUser()
    assert request.person == AnonymousContact()
    assert request.customer == AnonymousContact()
Exemplo n.º 30
0
def test_cart_add_all(rf, regular_user):
    cart = _save_cart_with_products(rf, regular_user)
    request = apply_request_middleware(
        rf.post("/"),
        customer=get_person_contact(regular_user),
        user=regular_user)
    assert not request.basket.product_count, "cart is empty"
    response = CartAddAllProductsView.as_view()(request, pk=cart.pk)
    assert response.status_code == 200
    assert request.basket.product_count, "products added to cart"