def test_category_product_filters_4(browser, live_server, settings): """ Do not show manufacturer option if there is any product """ cache.clear() # Avoid cache from past tests shop, first_cat, second_cat, third_cat, first_manufacturer = initialize_db() # remove manufacturers from all products Product.objects.all().update(manufacturer=None) # show manufacturer filter set_configuration( category=first_cat, data={ "override_default_configuration": True, "sort_products_by_name": True, "sort_products_by_name_ordering": 1, "sort_products_by_price": True, "sort_products_by_price_ordering": 2, "filter_products_by_manufacturer": True, }, ) # initialize test and go to front page browser = initialize_front_browser_test(browser, live_server) # check that front page actually loaded wait_until_condition(browser, lambda x: x.is_text_present("Welcome to Default!")) url = reverse("shuup:category", kwargs={"pk": first_cat.pk, "slug": first_cat.slug}) browser.visit("%s%s" % (live_server, url)) wait_until_condition(browser, lambda x: x.is_text_present("First Category")) wait_until_condition(browser, lambda x: x.is_text_present("Sort")) assert not browser.is_text_present("Manufacturers") # Since there is no product with manufacturer # add the manufacturer to the last product so the manufacturer filter is show last_product = Product.objects.last() last_product.manufacturer = first_manufacturer last_product.save() browser.visit("%s%s" % (live_server, url)) assert browser.is_text_present("Manufacturers") # set the shop product hidden shop_product = last_product.get_shop_instance(shop) shop_product.visibility = ShopProductVisibility.NOT_VISIBLE shop_product.save() # the manufacturer filter is removed browser.visit("%s%s" % (live_server, url)) assert not browser.is_text_present("Manufacturers")
def test_order_configuration(rf, admin_user): shop = get_default_shop() # clear shop configurations ConfigurationItem.objects.filter(shop=shop).delete() client = SmartClient() client.login(username="******", password="******") url = reverse("shuup_admin:shop.edit", kwargs={"pk": shop.pk}) response, soup = client.response_and_soup(url) assert response.status_code == 200 length_form_field = "order_configuration-%s" % consts.ORDER_REFERENCE_NUMBER_LENGTH_FIELD prefix_form_field = "order_configuration-%s" % consts.ORDER_REFERENCE_NUMBER_PREFIX_FIELD length_field = soup.find("input", attrs={"id": "id_%s" % length_form_field}) prefix_field = soup.find("input", attrs={"id": "id_%s" % prefix_form_field}) assert length_field assert prefix_field assert length_field["value"] == str( settings.SHUUP_REFERENCE_NUMBER_LENGTH ) # default value because nothing set yet assert "value" not in prefix_field # field empty data = get_base_form_data(shop) data[length_form_field] = "18" data[prefix_form_field] = "123" response, soup = client.response_and_soup(url, data=data, method="post") assert "is required" not in soup.prettify() assert response.status_code == 302 # redirect after success assert configuration.get(shop, consts.ORDER_REFERENCE_NUMBER_LENGTH_FIELD) == 18 # set global system settings # TODO: Enable this before 1.3 # set_reference_method(rf, admin_user, OrderReferenceNumberMethod.RUNNING) data[length_form_field] = "19" data[prefix_form_field] = "0" client.post(url, data=data) assert configuration.get(shop, consts.ORDER_REFERENCE_NUMBER_LENGTH_FIELD) == 19 assert not configuration.get(shop, consts.ORDER_REFERENCE_NUMBER_PREFIX_FIELD ) # None because disabled line 104, else 0
def build(self): self.append( URLActionButton( url=reverse("shuup_admin:contact.edit", kwargs={"pk": self.contact.pk}), icon="fa fa-pencil", text=_("Edit"), extra_css_class="btn-primary", )) self.build_renew_password_button() self.build_new_user_button() self.build_user_button() self.build_new_order_button() self.build_provides_buttons() self.build_login_as_button()
def test_large_file(client, regular_user): client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) with override_settings( SHUUP_CUSTOMER_INFORMATION_ALLOW_PICTURE_UPLOAD=True): with override_settings(SHUUP_FRONT_MAX_UPLOAD_SIZE=10): tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg") generate_image(120, 120).save(tmp_file) with open(tmp_file.name, "rb") as data: response = client.post(reverse("shuup:media-upload"), data=dict({"file": data}), format="multipart") assert response.status_code == 400 data = json.loads(response.content.decode("utf-8")) assert "Maximum file size reached" in data["error"]
def test_uploads_allowed_setting(client, allow_image_uploads, regular_user): client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) with override_settings( SHUUP_CUSTOMER_INFORMATION_ALLOW_PICTURE_UPLOAD=allow_image_uploads ): if allow_image_uploads: tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg") generate_image(120, 120).save(tmp_file) with open(tmp_file.name, "rb") as data: response = client.post(reverse("shuup:media-upload"), data=dict({"file": data}), format="multipart") assert response.status_code == 200 data = json.loads(response.content.decode("utf-8")) assert data["file"]["id"] else: tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg") generate_image(120, 120).save(tmp_file) with open(tmp_file.name, "rb") as data: response = client.post(reverse("shuup:media-upload"), data=dict({"file": data}), format="multipart") assert response.status_code == 403
def _get_edit_object_view(rf, view, model_name, object_id, user, shop, mode=None): data = {"model": model_name, "id": object_id or ""} if mode: data["mode"] = mode request = apply_request_middleware(rf.get(reverse("shuup_admin:edit"), data), user=user, shop=shop) return view(request)
def guest_ordering_test(browser, live_server): browser.fill("login-username", "test-username") click_element(browser, "button[name='login']") # Shouldn't submit browser.fill("login-password", "test-password") click_element(browser, "button[name='login']") wait_until_condition(browser, lambda x: x.is_text_present("Please enter a correct username and password.")) wait_until_appeared(browser, "div.alert.alert-danger") click_element(browser, "button[data-id='id_checkout_method_choice-register']") # WARNING: data-original-index was removed after bootstrap-select 1.6.3 click_element(browser, "li[data-original-index='0'] a") click_element(browser, "div.clearfix button.btn.btn-primary.btn-lg.pull-right") wait_until_condition(browser, lambda x: x.is_text_present("Checkout: Addresses")) url = reverse("shuup:checkout", kwargs={"phase": "checkout_method"}) browser.visit("%s%s" % (live_server, url))
def form_valid(self, form): file = form.cleaned_data["file"] if not file.name.lower().endswith(".whl"): raise Problem(_("Only wheel files (`.whl`) are supported.")) # TODO: Maybe verify the file before saving? tmp_dir = tempfile.mkdtemp(prefix='shuup') tmp_token = os.path.basename(tmp_dir) filename = os.path.basename(file.name) with open(os.path.join(tmp_dir, filename), "wb") as outf: shutil.copyfileobj(file, outf) return HttpResponseRedirect( manipulate_query_string( reverse("shuup_admin:addon.upload_confirm"), file=filename, token=tmp_token))
def test_upload_valid_image(client, rf, admin_user): assert File.objects.count() == 0 tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg') generate_image(120, 120).save(tmp_file) #tmp_file.seek(0) client.login(username="******", password="******") with open(tmp_file.name, 'rb') as data: response = client.post( reverse("shuup_admin:media.upload"), data=dict({"action": "upload", "file": data}), format="multipart" ) assert File.objects.count() == 1
def test_menu_reset_view(rf, admin_user): arrange_url = reverse('shuup_admin:menu.arrange') menu_request = apply_request_middleware(rf.get(arrange_url), user=admin_user) admin_menu_before_save = [ m.to_dict() for m in get_menu_entry_categories(menu_request) ] data = {'menus': json.dumps(admin_menu_before_save[::-1])} AdminMenuArrangeView.as_view()(apply_request_middleware(rf.post( arrange_url, data=data), user=admin_user)) admin_menu_after_save = [ m.to_dict() for m in get_menu_entry_categories(menu_request) ] assert admin_menu_after_save == admin_menu_before_save[::-1] reset_url = reverse('shuup_admin:menu.reset') request = apply_request_middleware(rf.get(reset_url), user=admin_user) response = AdminMenuResetView.as_view()(request) assert response.status_code == 302 admin_menu_after_reset = [ m.to_dict() for m in get_menu_entry_categories(menu_request) ] assert admin_menu_after_reset == admin_menu_before_save
def test_login_with_email_1(client, regular_user, rf): get_default_shop() prepare_user(regular_user) redirect_target = "/redirect-success/" response = client.post( reverse("shuup_admin:login"), data={"username": regular_user.email, "password": REGULAR_USER_PASSWORD, REDIRECT_FIELD_NAME: redirect_target}, ) assert response.get("location") assert response.get("location").endswith(redirect_target) request = rf.get("/") request.session = client.session assert get_user(request) == regular_user, "User is logged in"
def get_context_data(self, **kwargs): context = super(OrderCreateFullRefundView, self).get_context_data(**kwargs) context["title"] = _("Create Full Refund -- %s") % context["order"] context["toolbar"] = Toolbar( [ URLActionButton( url=reverse("shuup_admin:order.create-refund", kwargs={"pk": self.object.pk}), icon="fa fa-check-circle", text=_("Cancel"), extra_css_class="btn-danger", ), ], view=self, ) return context
def test_product_detail(browser, admin_user, live_server, settings): activate(settings.PARLER_DEFAULT_LANGUAGE_CODE) shop = get_default_shop() order = create_empty_order(shop=shop) order.save() initialize_admin_browser_test(browser, live_server, settings) url = reverse("shuup_admin:order.detail", kwargs={"pk": order.pk}) browser.visit("%s%s" % (live_server, url)) wait_until_condition(browser, condition=lambda x: x.is_text_present("Order %s" % order.pk)) change_addresses(live_server, browser, order) set_status(browser, order, OrderStatus.objects.get_default_processing()) assert order.can_set_complete() set_status(browser, order, OrderStatus.objects.get_default_complete())
def test_menu_move_child(rf, admin_user): arrange_url = reverse("shuup_admin:menu.arrange") menu_request = apply_request_middleware(rf.get(arrange_url), user=admin_user) admin_menu_before_save = [m.to_dict() for m in get_menu_entry_categories(menu_request)] # move child on the top level entry = admin_menu_before_save[0]["entries"][0] del admin_menu_before_save[0]["entries"][0] admin_menu_before_save.append(entry) data = {"menus": json.dumps(admin_menu_before_save)} AdminMenuArrangeView.as_view()(apply_request_middleware(rf.post(arrange_url, data=data), user=admin_user)) admin_menu_after_save = [m.to_dict() for m in get_menu_entry_categories(menu_request)] assert admin_menu_after_save[-1]["id"] == entry["id"]
def test_user_detail_as_staff_and_login_as_url(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 ) 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) login_as_staff_url = reverse("shuup_admin:user.login-as-staff", kwargs={"pk": user.pk}) assert force_text(login_as_staff_url) in force_text(response.content) with override_settings(SHUUP_ADMIN_LOGIN_AS_STAFF_REDIRECT_VIEW="giberish"): 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) login_as_staff_url = reverse("shuup_admin:user.login-as-staff", kwargs={"pk": user.pk}) assert force_text(login_as_staff_url) not in force_text(response.content)
def test_checkout_empty_basket(rf): cache.clear() create_default_order_statuses() n_orders_pre = Order.objects.count() populate_if_required() c = SmartClient() product_ids = _populate_client_basket(c) addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup) for product_id in product_ids: Product.objects.get(pk=product_id).soft_delete() response, soup = c.response_and_soup(addresses_path, data=inputs, method="post") assert response.status_code == 200 # Should redirect forth assert b"Your shopping cart is empty." in soup.renderContents()
def form_valid(self, form): query = Q(id__in=self.ids) if isinstance(self.ids, six.string_types) and self.ids == "all": query = Q() for contact in Contact.objects.filter(query): for k, v in six.iteritems(form.cleaned_data): if not v: continue if hasattr(contact, k): setattr(contact, k, v) contact.save() messages.success(self.request, _("Contacts were changed.")) self.request.session["mass_action_ids"] = [] return HttpResponseRedirect(reverse("shuup_admin:contact.list"))
def get_toolbar(self): return Toolbar( [ URLActionButton( text=_("New Script"), icon="fa fa-plus", extra_css_class="btn-success", url=reverse("shuup_admin:notify.script.new"), ), JavaScriptActionButton(text=_("New From Template"), icon="fa fa-book", onclick="showScriptTemplates()"), ], view=self, )
def get_link_url(self): """ Get right link url for this slide. Initially external link is used. If not set link will fallback to product_link, external_link or cms_page_link in this order. :return: return correct link url for slide if set :rtype: str|None """ external_link = self.get_translated_field("external_link") if external_link: return external_link elif self.product_link: return reverse("shuup:product", kwargs=dict(pk=self.product_link.pk, slug=self.product_link.slug)) elif self.category_link: return reverse("shuup:category", kwargs=dict(pk=self.category_link.pk, slug=self.category_link.slug)) elif self.cms_page_link: return reverse("shuup:cms_page", kwargs=dict(url=self.cms_page_link.url))
def test_login_with_invalid_password(client, regular_user, rf): get_default_shop() prepare_user(regular_user) redirect_target = "/redirect-success/" response = client.post(reverse("shuup_admin:login"), data={ "username": regular_user.email, "password": "******", REDIRECT_FIELD_NAME: redirect_target }) assert not response.get("location") # No redirect since errors request = rf.get("/") request.session = client.session assert is_anonymous(get_user(request)), "User is still anonymous"
def build_login_as_button(self): user = self.contact.user if hasattr(self.contact, "user") else None current_user = self.request.user if isinstance(user, get_user_model()): has_privileges = bool( getattr(current_user, "is_superuser", False) or getattr(current_user, "is_staff", False) ) can_impersonate = bool( has_privileges and user.is_active and not user.is_superuser ) if (can_impersonate and get_front_url() and not user.is_staff): self.append(PostActionButton( post_url=reverse("shuup_admin:user.login-as", kwargs={"pk": user.pk}), text=_(u"Login as User"), extra_css_class="btn-inverse" )) elif (can_impersonate and get_admin_url() and user.is_staff): self.append(PostActionButton( post_url=reverse("shuup_admin:user.login-as-staff", kwargs={"pk": user.pk}), text=_(u"Login as Staff User"), extra_css_class="btn-inverse" ))
def test_resolve_product_url(): shop = factories.get_default_shop() product = factories.create_product("product", shop, factories.get_default_supplier(), "10") from shuup.front.template_helpers.urls import model_url product_url = reverse("shuup:product", kwargs=dict(pk=product.pk, slug=product.slug)) assert model_url({}, product) == product_url # create a new supplier and use it # the URL should still point to the default product URL (no supplier specific) # because the given supplier doesn't supplies the product supplier2 = factories.get_supplier("", shop) assert model_url({}, product, supplier=supplier2) == product_url shop_product = product.get_shop_instance(shop) shop_product.suppliers.add(supplier2) # now the url is supplier2 specific product_supplier2_url = reverse("shuup:supplier-product", kwargs=dict(pk=product.pk, slug=product.slug, supplier_pk=supplier2.pk)) assert model_url({}, product, supplier=supplier2) == product_supplier2_url
def test_gdpr_admin_anonymize(client, admin_user): """ Test that admin user can anonymize contact """ activate("en") factories.get_default_shop() person = factories.create_random_person("en") person.user = factories.create_random_user("en") person.save() client = SmartClient() admin_user.set_password("admin") admin_user.save() client.login(username=admin_user.username, password="******") admin_anonymize_url = reverse("shuup_admin:gdpr.anonymize", kwargs=dict(pk=person.pk)) response = client.post(admin_anonymize_url) assert response.status_code == 302 assert response.url.endswith( reverse("shuup_admin:contact.detail", kwargs=dict(pk=person.pk))) anonymized_person = PersonContact.objects.get(id=person.id) assert anonymized_person.name != person.name assert anonymized_person.user.username != person.user.username
def get_help_blocks(self, request, kind): if kind == "setup": shop = request.shop yield SimpleHelpBlock( text=_("Add a logo to make your store stand out"), actions=[{ "text": _("Add logo"), "url": self.get_model_url(shop, "edit"), "hash": "#shop-images-section" }], icon_url="shuup_admin/img/logo_icon.svg", done=shop.logo, required=False) shop = get_shop(request) yield SimpleHelpBlock( priority=1000, text=_("Publish your store"), description=_( "Let customers browse your store and make purchases"), css_class="green ", actions=[{ "method": "POST", "text": _("Publish shop"), "url": reverse("shuup_admin:shop.enable", kwargs={"pk": shop.pk}), "data": { "enable": True, "redirect": reverse("shuup_admin:dashboard") } }], icon_url="shuup_admin/img/publish.png", done=(not shop.maintenance_mode), required=False)
def test_with_invalid_image(client, regular_user): client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) with override_settings( SHUUP_CUSTOMER_INFORMATION_ALLOW_PICTURE_UPLOAD=True): tmp_file = tempfile.NamedTemporaryFile(suffix=".jpg") tmp_file.write(b"Hello world!") tmp_file.seek(0) with open(tmp_file.name, "rb") as data: response = client.post(reverse("shuup:media-upload"), data=dict({"file": data}), format="multipart") assert response.status_code == 400 data = json.loads(response.content.decode("utf-8")) assert "not an image or a corrupted image" in data["error"]
def stop_impersonating_staff(request): if "impersonator_user_id" not in request.session: return HttpResponseForbidden() impersonator_user_id = request.session["impersonator_user_id"] auth_user_id = request.session["_auth_user_id"] del request.session["impersonator_user_id"] logout(request) user = get_user_model().objects.get(pk=impersonator_user_id) for backend in settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break login(request, user) user_url_name = "shuup_admin:user.detail" if has_permission(user, user_url_name): url = reverse(user_url_name, args=[auth_user_id]) else: url = reverse(settings.SHUUP_ADMIN_LOGIN_AS_STAFF_REDIRECT_VIEW) return HttpResponseRedirect(url)
def test_dashboard_redirect(rf, admin_user, settings): settings.SHUUP_SETUP_WIZARD_PANE_SPEC = [] shop = get_default_shop() shop.maintenance_mode = True shop.save() request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 302 assert response["Location"] == reverse("shuup_admin:home") shop.maintenance_mode = False shop.save() request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200
def test_page_delete(rf, admin_user): request = apply_request_middleware(rf.post("/"), user=admin_user) page = create_page(url="bacon", shop=get_default_shop()) assert Page.objects.filter(pk=page.pk).not_deleted().exists() is True delete_view = PageDeleteView.as_view() response = delete_view(request, **{"pk": page.pk}) assert response.status_code == 302 assert response.url == reverse("shuup_admin:simple_cms.page.list") assert Page.objects.filter(pk=page.pk).not_deleted().exists() is False page_two = create_page(url="bacon", shop=get_default_shop()) assert Page.objects.filter(pk=page_two.pk).exists()
def post(self, request, *args, **kwargs): contact = self.get_object() contact.add_log_entry("Info! User anonymization requested.", kind=LogEntryKind.NOTE, user=self.request.user) with atomic(): anonymizer = Anonymizer() if isinstance(contact, PersonContact): anonymizer.anonymize_person(contact) elif isinstance(contact, CompanyContact): anonymizer.anonymize_company(contact) messages.success(request, _("Contact was anonymized.")) return HttpResponseRedirect( reverse("shuup_admin:contact.detail", kwargs=dict(pk=contact.pk)))
def post(self, request, *args, **kwargs): if not onboarding_complete(request): messages.error( request, _("There are still some pending actions to complete.")) return HttpResponseRedirect(reverse("shuup_admin:home")) enable = request.POST.get("enable", True) if kwargs.get("pk") == str(request.shop.pk): shop = request.shop else: shop = Shop.objects.filter(pk=kwargs.get("pk")).first() shop.maintenance_mode = not enable shop.save() messages.info(request, _("Your store is now live.")) return HttpResponseRedirect(request.POST.get("redirect"))