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 _handle_xtheme_save(self): svc_pk = config.get(self.shop, CONTENT_FOOTER_KEY) svc = SavedViewConfig.objects.filter(pk=svc_pk).first() theme = get_current_theme(self.shop) if not svc and theme: context = {"shop": self.shop} rendered_content = template_loader.render_to_string( content_data.FOOTER_TEMPLATE, context).strip() layout = Layout(theme, "footer-bottom") # adds the footer template layout.begin_row() layout.begin_column({"md": 12}) layout.add_plugin(SnippetsPlugin.identifier, {"in_place": rendered_content}) svc = SavedViewConfig(theme_identifier=theme.identifier, shop=self.shop, view_name=XTHEME_GLOBAL_VIEW_NAME, status=SavedViewConfigStatus.CURRENT_DRAFT) svc.set_layout_data(layout.placeholder_name, layout) svc.save() svc.publish() config.set(self.shop, CONTENT_FOOTER_KEY, svc.pk)
def test_register_api(): get_default_shop() configuration.set(None, "api_permission_FrontUserViewSet", PermissionLevel.PUBLIC_WRITE) client = _get_client() register_data = { "username": "******", "password": "******" } response = client.post("/api/wshop/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_201_CREATED response_json = json.loads(response.content.decode("utf-8")) assert "token" in response_json assert get_user_model().objects.count() == 1 # Try to register with same username register_data = { "username": "******", "password": "******" } response = client.post("/api/wshop/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "User already exists" in response.content.decode("utf-8")
def set_configuration(): config = { "api_permission_ShopViewSet": 3, "api_permission_FrontShopProductViewSet": 3, "api_permission_PersonContactViewSet": 4, "api_permission_FrontUserViewSet": 2, "api_permission_FrontOrderViewSet": 4, "api_permission_AttributeViewSet": 5, "api_permission_TaxClassViewSet": 5, "api_permission_FrontProductViewSet": 3, "api_permission_ProductVariationVariableValueViewSet": 5, "api_permission_SalesUnitViewSet": 5, "api_permission_UserViewSet": 5, "api_permission_ShopReviewViewSet": 4, "api_permission_BasketViewSet": 2, "api_permission_CategoryViewSet": 1, "api_permission_ShipmentViewSet": 5, "api_permission_CgpPriceViewSet": 5, "api_permission_ShopProductViewSet": 3, "api_permission_ContactViewSet": 4, "api_permission_OrderViewSet": 5, "api_permission_ProductViewSet": 5, "api_permission_ProductTypeViewSet": 5, "api_permission_ProductVariationVariableViewSet": 5, "api_permission_SupplierViewSet": 5, "api_permission_ManufacturerViewSet": 5, "api_permission_ProductMediaViewSet": 5, "api_permission_ProductAttributeViewSet": 5, "api_permission_MutableAddressViewSet": 5, "api_permission_ProductPackageViewSet": 5, } for field, value in six.iteritems(config): configuration.set(None, field, value)
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
def toggle_all_seeing(request): return_url = request.META["HTTP_REFERER"] if not is_admin_user(request): return HttpResponseRedirect(return_url) all_seeing_key = "is_all_seeing:%d" % request.user.pk is_all_seeing = not configuration.get(None, all_seeing_key, False) configuration.set(None, all_seeing_key, is_all_seeing) return HttpResponseRedirect(return_url)
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 save(self): """ Store the fields in configuration """ if not self.is_valid(): return # that simple, aham for field, value in six.iteritems(self.cleaned_data): configuration.set(None, field, value)
def post_initialize(): """ Does some post initialization for notify tests This since straight after `initialize_admin_browser_test` DB seems to be randomly locked and we want to wait until we perform these post procedures. """ configuration.set(None, "wshop_product_tour_complete", True) Script.objects.all().delete()
def form_valid(self, form): if djangoenv.has_installed( "wshop.simple_cms") or djangoenv.has_installed("wshop.xtheme"): content_form = form["content"] content_form.save() if djangoenv.has_installed("wshop.notify"): behavior_form = form["behaviors"] behavior_form.save() configuration.set(None, "wizard_content_completed", True)
def test_view_saved_columns(rf): shop = get_default_shop() visible_fields = sorted(["shopproduct_id", "name", "select"]) configuration.set(None, "view_configuration_shopproduct_saved", True) for field in visible_fields: configuration.set(None, "view_configuration_shopproduct_%s" % field, {"active": True, "ordering": 999}) listview = ProductListView() column_names = [c.id for c in sorted(listview.columns, key=lambda x: x.id)] assert len(listview.columns) == len(visible_fields) assert column_names == visible_fields
def test_behavior_form(): shop = get_default_shop() assert Script.objects.count() == 0 assert configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) is None form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": True}) assert form._get_saved_script() is None form.save() # check if the form creates a order notification correctely script = Script.objects.first() assert script.pk == configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) assert form._get_saved_script().pk == script.pk assert len(script.get_steps()) == 1 step = script.get_steps()[0] step_data = step.serialize() assert step_data["next"] == StepNext.STOP.value action = step._actions[0] assert isinstance(action, SendEmail) action_data = action.serialize() assert action_data["recipient"]["variable"] == "customer_email" assert action_data["language"]["variable"] == "language" lang = translation.get_language() assert action_data["fallback_language"]["constant"] == lang assert action_data["template_data"][lang]["content_type"] == "html" assert action_data["template_data"][lang]["subject"] == force_text( data.ORDER_CONFIRMATION["subject"]) context = {"shop": shop} content = loader.render_to_string(data.ORDER_CONFIRMATION["body_template"], context).strip() assert action_data["template_data"][lang]["body"] == content # the widget must be disabled form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": True}) assert form.fields["order_confirm_notification"].widget.attrs[ "disabled"] is True # clear scripts Script.objects.all().delete() configuration.set(shop, BEHAVIOR_ORDER_CONFIRM_KEY, None) # save the form but do not create the order confirmation notification form = BehaviorWizardForm(shop=shop, data={"order_confirm_notification": False}) form.save() # nothing created assert Script.objects.count() == 0 assert configuration.get(shop, BEHAVIOR_ORDER_CONFIRM_KEY) is None
def post(self, request, *args, **kwargs): abort = request.POST.get("abort", False) if self.request.POST.get( "pane_id") == self.get_final_pane_identifier(): configuration.set(Shop.objects.first(), "setup_wizard_complete", True) if abort: return JsonResponse({"success": "true"}, status=200) form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form)
def set_configuration(shop=None, category=None, data=None): if category and category.pk: configuration.set(None, _get_category_configuration_key(category), data) elif shop: configuration.set(shop, FACETED_DEFAULT_CONF_KEY, data) cache.bump_version(get_theme_cache_key(shop)) # clear active keys context_cache.bump_cache_for_item(category) if not category: from wshop.core.models import Category for cat_pk in Category.objects.all().values_list("pk", flat=True): context_cache.bump_cache_for_pk(Category, cat_pk)
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)
def test_registration_company_multiple_shops(django_user_model, client): if "wshop.front.apps.registration" not in settings.INSTALLED_APPS: pytest.skip("wshop.front.apps.registration required in installed apps") configuration.set(None, "allow_company_registration", True) configuration.set(None, "company_registration_requires_approval", False) shop1 = Shop.objects.create(identifier="shop1", status=ShopStatus.ENABLED, domain="shop1.wshop.com") Shop.objects.create(identifier="shop2", status=ShopStatus.ENABLED, domain="shop2.wshop.com") username = "******" % uuid.uuid4().time email = "*****@*****.**" % username with override_settings(WSHOP_REGISTRATION_REQUIRES_ACTIVATION=False, WSHOP_MANAGE_CONTACTS_PER_SHOP=True, WSHOP_ENABLE_MULTIPLE_SHOPS=True): url = reverse("wshop:registration_register_company") 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", }, HTTP_HOST="shop1.wshop.com") user = django_user_model.objects.get(username=username) contact = PersonContact.objects.get(user=user) company = CompanyContact.objects.get(members__in=[contact]) assert shop1 in contact.shops.all() assert shop1 in company.shops.all()
def form_valid(self, form): if self.name in form.forms: used_form = form[self.name] if not used_form.has_changed(): return None # no need to save for key in used_form.fields.keys(): try: ConfigurationItem.objects.get(shop=self.object, key=key).delete() except ConfigurationItem.DoesNotExist: continue for key, value in six.iteritems(used_form.cleaned_data): configuration.set(shop=self.object, key=key, value=value)
def save(self, form): if not form.has_changed(): return False # no need to save for key in form.fields.keys(): try: ConfigurationItem.objects.get(shop=None, key=key).delete() except ConfigurationItem.DoesNotExist: continue for key, value in six.iteritems(form.cleaned_data): if isinstance(value, Enum): value = value.value configuration.set(None, key, value) return True
def test_admin(rf, admin_user): shop = get_default_shop() configuration.set(shop, "setup_wizard_complete", True) # just visit to make sure everything is ok request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200 categories = [ CategoryFactory().pk, CategoryFactory().pk, CategoryFactory().pk ] manager.save_categories(shop, categories) request = apply_request_middleware(rf.get("/"), user=admin_user) response = DashboardView.as_view()(request) assert response.status_code == 200
def initialize_admin_browser_test(browser, live_server, settings, username="******", password="******"): settings.WSHOP_SETUP_WIZARD_PANE_SPEC = [] activate("en") get_default_shop() configuration.set(None, "wshop_dashboard_tour_complete", True) url = live_server + "/sa" browser.visit(url) browser.fill('username', username) browser.fill('password', password) browser.find_by_css(".btn.btn-primary.btn-lg.btn-block").first.click() # set shop language to eng browser.find_by_id("dropdownMenu").click() browser.find_by_xpath('//a[@data-value="en"]').first.click() return browser
def run(self): for schema in self.schemata: self.objects[schema["model"]] = self.process_schema(schema) # Ensure default statuses are available print_("Creating order statuses...", end=" ") create_default_order_statuses() print_("done.") if not settings.DEBUG and is_telemetry_enabled(): try: data = json.dumps({"key": get_installation_key()}) resp = requests.get(url=settings.WSHOP_SUPPORT_ID_URL, data=data, timeout=5) if resp.json().get("support_id"): configuration.set(None, "wshop_support_id", resp.json().get("support_id")) except Exception: print_("Failed to get support id") print_("Initialization done.")
def test_product_variations_cache(admin_user): configuration.set(None, "api_permission_FrontShopProductViewSet", 2) shop = get_default_shop() supplier = get_default_supplier() product = create_product("Just-A-Product", shop, default_price=200, supplier=supplier) simple_child = create_product("product5", shop=shop, supplier=supplier) simple_child.link_to_parent(product) sp = simple_child.get_shop_instance(shop) sp.visibility_limit = ProductVisibility.VISIBLE_TO_LOGGED_IN sp.save() client = _get_client(None) response = client.get("/api/wshop/front/shop_products/") products_data = json.loads(response.content.decode("utf-8")) assert not products_data[0]["variations"][0]["product"]["is_orderable"] client = _get_client(admin_user) response = client.get("/api/wshop/front/shop_products/") products_data = json.loads(response.content.decode("utf-8")) assert products_data[0]["variations"][0]["product"]["is_orderable"]
def test_category_visibility(admin_user, regular_user): visible_public_category = Category.objects.create(status=CategoryStatus.VISIBLE, visibility=CategoryVisibility.VISIBLE_TO_ALL, identifier="visible_public", name=DEFAULT_NAME) hidden_public_category = Category.objects.create(status=CategoryStatus.INVISIBLE, visibility=CategoryVisibility.VISIBLE_TO_ALL, identifier="hidden_public", name=DEFAULT_NAME) deleted_public_category = Category.objects.create(status=CategoryStatus.DELETED, visibility=CategoryVisibility.VISIBLE_TO_ALL, identifier="deleted_public", name=DEFAULT_NAME) logged_in_category = Category.objects.create(status=CategoryStatus.VISIBLE, visibility=CategoryVisibility.VISIBLE_TO_LOGGED_IN, identifier="visible_logged_in", name=DEFAULT_NAME) group_visible_category = Category.objects.create(status=CategoryStatus.VISIBLE, visibility=CategoryVisibility.VISIBLE_TO_GROUPS, identifier="visible_groups", name=DEFAULT_NAME) assert visible_public_category.name == DEFAULT_NAME assert str(visible_public_category) == DEFAULT_NAME anon_contact = AnonymousContact() regular_contact = get_person_contact(regular_user) admin_contact = get_person_contact(admin_user) configuration.set(None, get_all_seeing_key(admin_contact), True) for (customer, category, expect) in [ (anon_contact, visible_public_category, True), (anon_contact, hidden_public_category, False), (anon_contact, deleted_public_category, False), (anon_contact, logged_in_category, False), (anon_contact, group_visible_category, False), (regular_contact, visible_public_category, True), (regular_contact, hidden_public_category, False), (regular_contact, deleted_public_category, False), (regular_contact, logged_in_category, True), (regular_contact, group_visible_category, False), (admin_contact, visible_public_category, True), (admin_contact, hidden_public_category, True), (admin_contact, deleted_public_category, False), (admin_contact, logged_in_category, True), (admin_contact, group_visible_category, True), ]: result = Category.objects.all_visible(customer=customer).filter(pk=category.pk).exists() assert result == expect, "Queryset visibility of %s for %s as expected" % (category.identifier, customer) assert category.is_visible(customer) == expect, "Direct visibility of %s for %s as expected" % (category.identifier, customer) assert not Category.objects.all_except_deleted().filter(pk=deleted_public_category.pk).exists(), "Deleted category does not show up in 'all_except_deleted'" configuration.set(None, get_all_seeing_key(admin_contact), False)
def _send_telemetry(request, max_age_hours, force_send=False): if not is_telemetry_enabled(): raise TelemetryNotSent("Telemetry not enabled", "disabled") if not force_send: if is_opt_out(): raise TelemetryNotSent("Telemetry is opted-out", "optout") if is_in_grace_period(): raise TelemetryNotSent("Telemetry in grace period", "grace") if max_age_hours is not None: last_send_time = get_last_submission_time() if last_send_time and (now() - last_send_time ).total_seconds() <= max_age_hours * 60 * 60: raise TelemetryNotSent("Trying to resend too soon", "age") data = get_telemetry_data(request) try: resp = requests.post(url=settings.WSHOP_TELEMETRY_URL, data=data, timeout=5) if (not settings.DEBUG and resp.status_code == 200 and resp.json().get("support_id") and not configuration.get(None, "wshop_support_id")): configuration.set(None, "wshop_support_id", resp.json().get("support_id")) except Exception as exc: data = { "data": data, "error": force_text(exc), } else: data = { "data": data, "response": force_text(resp.content, errors="replace"), "status": resp.status_code, } save_telemetry_submission(data) return data
def test_product_create(browser, admin_user, live_server, settings): activate("en") shop = get_default_shop() get_default_product_type() get_default_sales_unit() get_default_tax_class() configuration.set(None, "wshop_product_tour_complete", True) object_created.connect(_add_custom_product_created_message, sender=Product, dispatch_uid="object_created_signal_test") initialize_admin_browser_test(browser, live_server, settings) browser.driver.set_window_size(1920, 1080) url = reverse("wshop_admin:shop_product.new") browser.visit("%s%s" % (live_server, url)) sku = "testsku" name = "Some product name" price_value = 10 short_description = "short but gold" browser.fill("base-sku", sku) browser.fill("base-name__en", name) browser.fill("base-short_description__en", short_description) browser.fill("shop%s-default_price_value" % shop.pk, price_value) configuration.set(None, "wshop_category_tour_complete", True) _add_primary_category(browser, shop) _add_additional_category(browser, shop) click_element(browser, "button[form='product_form']") wait_until_appeared(browser, "div[class='message success']") product = Product.objects.filter(sku=sku).first() assert product.log_entries.filter( identifier=OBJECT_CREATED_LOG_IDENTIFIER).count() == 1 object_created.disconnect(sender=Product, dispatch_uid="object_created_signal_test") shop_product = product.get_shop_instance(shop) assert shop_product.categories.count() == 2
def test_product_detail(browser, admin_user, live_server, settings): shop = get_default_shop() product = create_product("test_sku", shop, default_price=10) configuration.set(None, "wshop_product_tour_complete", True) initialize_admin_browser_test(browser, live_server, settings) url = reverse("wshop_admin:shop_product.edit", kwargs={"pk": product.get_shop_instance(shop).pk}) browser.visit("%s%s" % (live_server, url)) assert browser.find_by_id("id_base-sku").value == product.sku # Test product save new_sku = "some-new-sku" browser.find_by_id("id_base-sku").fill(new_sku) browser.execute_script("window.scrollTo(0,0)") click_element(browser, "button[form='product_form']") wait_until_condition( browser, condition=lambda x: x.is_text_present("Product edited")) product.refresh_from_db() check_product_name(browser, product, new_sku) # Test that toolbar action item is there dropdowns = browser.find_by_css(".btn.dropdown-toggle") for dropdown in dropdowns: if "Actions" in dropdown.text: dropdown.click() wait_until_appeared(browser, "a[href='#%s']" % product.sku) click_element(browser, "a[href='#%s']" % product.sku) # Make sure that the tabs is clickable in small devices browser.driver.set_window_size(480, 960) click_element(browser, "#product-images-section", header_height=320) click_element(browser, "#additional-details-section", header_height=320)
def test_product_visibility(rf, admin_user, regular_user): anon_contact = get_person_contact(AnonymousUser()) shop_product = get_default_shop_product() admin_contact = get_person_contact(admin_user) regular_contact = get_person_contact(regular_user) configuration.set(None, get_all_seeing_key(admin_contact), True) with modify(shop_product.product, deleted=True): # NB: assigning to `product` here works because `get_shop_instance` populates `_product_cache` assert error_exists(shop_product.get_visibility_errors(customer=anon_contact), "product_deleted") assert error_exists(shop_product.get_visibility_errors(customer=admin_contact), "product_deleted") with pytest.raises(ProductNotVisibleProblem): shop_product.raise_if_not_visible(anon_contact) assert not shop_product.is_list_visible() with modify(shop_product, visibility_limit=ProductVisibility.VISIBLE_TO_ALL, visibility=ShopProductVisibility.NOT_VISIBLE): assert error_exists(shop_product.get_visibility_errors(customer=anon_contact), "product_not_visible") assert error_does_not_exist(shop_product.get_visibility_errors(customer=admin_contact), "product_not_visible") assert not shop_product.is_list_visible() with modify(shop_product, visibility_limit=ProductVisibility.VISIBLE_TO_LOGGED_IN, visibility=ShopProductVisibility.ALWAYS_VISIBLE): assert error_exists(shop_product.get_visibility_errors(customer=anon_contact), "product_not_visible_to_anonymous") assert error_does_not_exist(shop_product.get_visibility_errors(customer=admin_contact), "product_not_visible_to_anonymous") customer_group = get_default_customer_group() grouped_user = get_user_model().objects.create_user(username=printable_gibberish(20)) grouped_contact = get_person_contact(grouped_user) with modify(shop_product, visibility_limit=ProductVisibility.VISIBLE_TO_GROUPS, visibility=ShopProductVisibility.ALWAYS_VISIBLE): shop_product.visibility_groups.add(customer_group) customer_group.members.add(grouped_contact) customer_group.members.remove(get_person_contact(regular_user)) assert error_does_not_exist(shop_product.get_visibility_errors(customer=grouped_contact), "product_not_visible_to_group") assert error_does_not_exist(shop_product.get_visibility_errors(customer=admin_contact), "product_not_visible_to_group") assert error_exists(shop_product.get_visibility_errors(customer=regular_contact), "product_not_visible_to_group") configuration.set(None, get_all_seeing_key(admin_contact), False)
def save(self): """ Create and configure the selected objects if needed """ # User wants a order notification and Notify installed and there is no script created previously if (self.is_valid() and self.cleaned_data["order_confirm_notification"] and djangoenv.has_installed("wshop.notify") and not self._get_saved_script()): from wshop.front.notify_events import OrderReceived from wshop.notify.models.script import Script from wshop.notify.script import Step, StepNext send_email_action = self._get_send_email_action() script = Script(event_identifier=OrderReceived.identifier, name="Order Received", enabled=True, shop=self.shop) script.set_steps( [Step(next=StepNext.STOP, actions=(send_email_action, ))]) script.save() # save the PK in the configs config.set(self.shop, BEHAVIOR_ORDER_CONFIRM_KEY, script.pk)
def test_reset_password_request(admin_user): get_default_shop() client = _get_client() configuration.set(None, "api_permission_FrontUserViewSet", PermissionLevel.PUBLIC_WRITE) register_data = {"email": "*****@*****.**", "password": "******"} response = client.post("/api/wshop/front/user/", content_type="application/json", data=json.dumps(register_data)) assert response.status_code == status.HTTP_201_CREATED user = get_user_model().objects.filter( email=register_data.get("email")).first() assert user.check_password("somepassword") configuration.set(None, "api_permission_PasswordResetViewSet", PermissionLevel.PUBLIC_WRITE) response = client.post("/api/wshop/front/password/reset/", content_type="application/json", data=json.dumps({"email": "bademail"})) assert response.status_code == status.HTTP_400_BAD_REQUEST assert "email" in json.loads(response.content.decode("utf-8")) response = client.post("/api/wshop/front/password/reset/", content_type="application/json", data=json.dumps({"email": "*****@*****.**"})) assert response.status_code == status.HTTP_204_NO_CONTENT assert len(mail.outbox) == 1 content = mail.outbox[0].body url = content[content.find("http"):] _, _, _, _, uid, token, _ = url.split("/") configuration.set(None, "api_permission_SetPasswordViewSet", PermissionLevel.PUBLIC_WRITE) response = client.post("/api/wshop/front/password/", content_type="application/json", data=json.dumps({ "new_password1": "foobar", "new_password2": "foobar", "token": token, "uidb64": uid })) assert response.status_code == status.HTTP_200_OK user = get_user_model().objects.filter(email="*****@*****.**").first() assert user.check_password("foobar")
def test_order_creator_min_total(rf, admin_user): shop = get_default_shop() configuration.set(shop, ORDER_MIN_TOTAL_CONFIG_KEY, Decimal(20)) source = seed_source(admin_user) source.add_line( type=OrderLineType.PRODUCT, product=get_default_product(), supplier=get_default_supplier(), quantity=1, base_unit_price=source.create_price(10), ) creator = OrderCreator() with pytest.raises(ValidationError): creator.create_order(source) configuration.set(shop, ORDER_MIN_TOTAL_CONFIG_KEY, Decimal(1)) creator.create_order(source) # do not mess with other tests configuration.set(shop, ORDER_MIN_TOTAL_CONFIG_KEY, Decimal(0))