def test_comment_visibility(admin_user): shop = factories.get_default_shop() admin_contact = get_person_contact(admin_user) staff_user = factories.create_random_user("en", is_staff=True) staff_contact = get_person_contact(staff_user) shop.staff_members.add(staff_user) normal_user = factories.create_random_user("en") normal_contact = get_person_contact(normal_user) task_type = TaskType.objects.create(name="Request", shop=shop) task = create_task(shop, admin_contact, task_type, "my task") task.comment(admin_contact, "This is only visibile for super users", TaskCommentVisibility.ADMINS_ONLY) task.comment(staff_contact, "This is only visibile for staff only", TaskCommentVisibility.STAFF_ONLY) task.comment(normal_contact, "This is visibile for everyone", TaskCommentVisibility.PUBLIC) # admin see all comments assert task.comments.for_contact(admin_contact).count() == 3 # staff see all public + staff only assert task.comments.for_contact(staff_contact).count() == 2 # normal contact see all public assert task.comments.for_contact(normal_contact).count() == 1 # anonymous contact see all public assert task.comments.for_contact(AnonymousContact()).count() == 1
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.add_to_shop(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)
def test_forcing_to_person_and_anonymous_contact(rf, admin_user): company_contact = get_company_contact(admin_user) assert company_contact is None shop = factories.get_default_shop() company_contact = get_company_contact_for_shop_staff(shop, admin_user) assert isinstance(company_contact, CompanyContact) assert company_contact == get_company_contact(admin_user) person_contact = get_person_contact(admin_user) assert person_contact is not None assert not person_contact.is_anonymous force_person_contact_for_user(admin_user) assert get_company_contact(admin_user) is None force_anonymous_contact_for_user(admin_user) assert get_person_contact(admin_user).is_anonymous force_person_contact_for_user(admin_user, False) assert get_company_contact(admin_user) is None # Since the person contact is still anonymous assert get_person_contact(admin_user).is_anonymous force_anonymous_contact_for_user(admin_user, False) assert company_contact == get_company_contact(admin_user) assert not get_person_contact(admin_user).is_anonymous
def test_company_contact_for_shop_staff(rf, admin_user): company_contact = get_company_contact(admin_user) assert company_contact is None shop = factories.get_default_shop() # Let's create shop for the shop staff company_contact = get_company_contact_for_shop_staff(shop, admin_user) company_contact = get_company_contact_for_shop_staff(shop, admin_user) assert company_contact is not None # Let's create second staff member to make sure all good with # creating company contact for shop staff. new_staff_user = factories.create_random_user() with pytest.raises(AssertionError): get_company_contact_for_shop_staff(shop, new_staff_user) new_staff_user.is_staff = True new_staff_user.save() with pytest.raises(AssertionError): # Since the new staff is not in shop members. The admin user # passed since he is also superuser. get_company_contact_for_shop_staff(shop, new_staff_user) shop.staff_members.add(new_staff_user) assert company_contact == get_company_contact_for_shop_staff(shop, new_staff_user) # Make sure both user has person contact linked to the company contact company_members = company_contact.members.all() assert get_person_contact(admin_user) in company_members assert get_person_contact(new_staff_user) in company_members
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 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("E-Commerce_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)
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("E-Commerce:index") assert get_user(request) == regular_user
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)
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)
def test_forcing_to_anonymous_contact(rf, admin_user): person_contact = get_person_contact(admin_user) assert person_contact is not None assert not get_person_contact(admin_user).is_anonymous company_contact = get_company_contact(admin_user) assert company_contact is None force_anonymous_contact_for_user(admin_user) assert get_person_contact(admin_user).is_anonymous force_anonymous_contact_for_user(admin_user, False) assert not get_person_contact(admin_user).is_anonymous assert get_person_contact(admin_user).user.id == admin_user.id
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))
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
def post(self, request, *args, **kwargs): if not request.person: return HttpResponseNotFound() self.request.person.add_log_entry( "User anonymization requested", kind=LogEntryKind.NOTE, user=request.user) with atomic(): from E-Commerce.tasks.models import TaskType from E-Commerce.tasks.utils import create_task task_type = TaskType.objects.get_or_create( shop=request.shop, identifier=GDPR_ANONYMIZE_TASK_TYPE_IDENTIFIER, defaults=dict(name=_("GDPR: Anonymize")) )[0] contact = get_person_contact(request.user) create_task( request.shop, contact, task_type, _("GDPR: Anonymize contact"), _("Customer ID {customer_id} requested to be anonymized.").format(**dict(customer_id=contact.id)) ) contact.is_active = False contact.save() request.user.is_active = False request.user.save() messages.success(request, _("Anonymization requested.")) return HttpResponseRedirect(reverse("E-Commerce:index"))
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('E-Commerce: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)
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"
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
def test_save_marketing_check(rf, admin_user): admin_contact = get_person_contact(admin_user) shop = get_default_shop() with override_settings(E-Commerce_CHECKOUT_CONFIRM_FORM_PROPERTIES={}): request = apply_request_middleware(rf.get("/"), shop=shop, user=admin_user, customer=admin_contact) form = ConfirmForm(request=request) assert form.fields["marketing"].initial is False assert form.fields["marketing"].widget.__class__ == forms.CheckboxInput admin_contact.options = {} admin_contact.options["marketing_permission_asked"] = True admin_contact.save() form = ConfirmForm(request=request) assert form.fields["marketing"].initial is False assert form.fields["marketing"].widget.__class__ == forms.HiddenInput admin_contact.marketing_permission = True admin_contact.save() form = ConfirmForm(request=request) assert form.fields["marketing"].initial is True assert form.fields["marketing"].widget.__class__ == forms.HiddenInput # test with anonymous request = apply_request_middleware(rf.get("/"), shop=shop, user=admin_user, customer=AnonymousContact()) form = ConfirmForm(request=request) assert form.fields["marketing"].initial is False assert form.fields["marketing"].widget.__class__ == forms.CheckboxInput
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)
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
def test_category_group_visibilities(regular_user): shop = get_default_shop() regular_contact = get_person_contact(regular_user) silver_group = ContactGroup.objects.create(identifier="silver", shop=shop) diamond_group = ContactGroup.objects.create(identifier="gold", shop=shop) 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
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"
def test_person_contact_create_form(rf, admin_user): shop = get_default_shop() user = get_user_model().objects.create_user( username=printable_gibberish(), first_name=printable_gibberish(), last_name=printable_gibberish(), ) test_first_name = printable_gibberish() test_last_name = printable_gibberish() request = apply_request_middleware(rf.post("/"), user=admin_user, shop=shop) contact_base_form = PersonContactBaseForm(request=request, data={ "first_name": test_first_name, "last_name": test_last_name, "gender": Gender.UNDISCLOSED.value }, user=user) assert contact_base_form.is_valid(), contact_base_form.errors contact = contact_base_form.save() assert isinstance(contact, PersonContact) assert contact.user == user assert get_person_contact(user) == contact assert contact.name == "%s %s" % (test_first_name, test_last_name) assert contact.in_shop(shop) assert contact.registered_in(shop) assert contact.in_shop(shop, True)
def test_create_new_basket(admin_user): with override_settings(**REQUIRED_SETTINGS): shop = factories.get_default_shop() shop2 = create_shop("foobar") client = _get_client(admin_user) response = client.post("/api/E-Commerce/basket/new/", { "shop": shop2.pk }) assert response.status_code == status.HTTP_201_CREATED basket_data = json.loads(response.content.decode("utf-8")) basket = Basket.objects.first() assert basket.key == basket_data['uuid'].split("-")[1] assert basket.shop == shop2 admin_contact = get_person_contact(admin_user) assert basket.customer == admin_contact assert basket.orderer == admin_contact assert basket.creator == admin_user # invalid shop response = client.post("/api/E-Commerce/basket/new/", data={"shop": 1000}) assert response.status_code == status.HTTP_400_BAD_REQUEST # no shop in multishop mode response = client.post("/api/E-Commerce/basket/new/") assert response.status_code == status.HTTP_400_BAD_REQUEST # no shop in single shop mode with override_settings(E-Commerce_ENABLE_MULTIPLE_SHOPS=False): response = client.post("/api/E-Commerce/basket/new/") assert response.status_code == status.HTTP_201_CREATED basket_data = json.loads(response.content.decode("utf-8")) basket = Basket.objects.all()[1] assert basket.key == basket_data['uuid'].split("-")[1] assert basket.shop == shop assert basket.customer == admin_contact assert basket.orderer == admin_contact assert basket.creator == admin_user person = factories.create_random_person() response = client.post("/api/E-Commerce/basket/new/", data={"customer": person.pk}) assert response.status_code == status.HTTP_201_CREATED basket_data = json.loads(response.content.decode("utf-8")) basket = Basket.objects.all()[2] assert basket.key == basket_data['uuid'].split("-")[1] assert basket.shop == shop assert basket.creator == admin_user assert basket.customer.pk == person.pk assert basket.orderer.pk == person.pk assert basket.creator.pk == admin_user.pk # Try to fetch the basket as the customer user = factories.UserFactory() person.user = user person.save() response = client.get("/api/E-Commerce/basket/{}/".format(basket_data['uuid'])) assert response.status_code == 200 customer_basket_data = json.loads(response.content.decode("utf-8")) assert basket.key == customer_basket_data['key'] # Still same basket as before assert customer_basket_data['customer']['id'] == person.pk # Still same customer as before
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"
def test_cart_list(rf, regular_user): _save_cart_with_products(rf, regular_user) request = apply_request_middleware(rf.get("/"), customer=get_person_contact(regular_user), user=regular_user) response = CartListView.as_view()(request) assert response.status_code == 200 assert "carts" in response.context_data assert response.context_data["carts"].count() == 1
def test_force_contact_views(rf): shop = factories.get_default_shop() user = factories.create_random_user(is_staff=True) shop.staff_members.add(user) person_contact = get_person_contact(user) request = apply_request_middleware(rf.get("/"), user=user) assert request.customer == person_contact # Force contact to anonymous contact _call_force_view(request, force_anonymous_contact) # Re-process middlewares so we check the force contact request = apply_request_middleware(rf.get("/"), user=user) assert request.customer.is_anonymous assert get_person_contact(user).is_anonymous assert_all_good_with_random_user() # Force contact to person contact _call_force_view(request, force_person_contact) request = apply_request_middleware(rf.get("/"), user=user) assert request.customer == person_contact assert get_person_contact(user) == person_contact assert_all_good_with_random_user() # Force contact to company contact. This also ensures # company contact for staff user if does not exists. _call_force_view(request, force_company_contact) request = apply_request_middleware(rf.get("/"), user=user) assert get_company_contact(user) == request.customer assert person_contact in request.customer.members.all() assert request.person == person_contact assert_all_good_with_random_user() # Finally force back to person contact. Now without # forcing the request would have company contact # since company contact for shop staff was created # while forcing company. _call_force_view(request, force_person_contact) request = apply_request_middleware(rf.get("/"), user=user) assert request.customer == person_contact assert get_person_contact(user) == person_contact assert get_company_contact(user) is None assert_all_good_with_random_user()
def test_stop_impersonating(rf, admin_user, regular_user): get_default_shop() view_func = LoginAsUserView.as_view() request = apply_request_middleware(rf.post("/"), user=admin_user) assert get_logout_url({"request": request}) == reverse("E-Commerce:logout") get_person_contact(regular_user) response = view_func(request, pk=regular_user.pk) assert response["location"] == reverse("E-Commerce:index") assert get_user(request) == regular_user assert "impersonator_user_id" in request.session assert get_logout_url({"request": request}) == reverse("E-Commerce:stop-impersonating") assert is_authenticated(get_user(request)) response = stop_impersonating(request) assert response.status_code in [301, 302] # redirect assert "impersonator_user_id" not in request.session assert is_authenticated(get_user(request)) assert request.user == admin_user
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
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))
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