def get_form_parts(request, view, object): with override_provides("service_behavior_component_form", DEFAULT_BEHAVIOR_FORMS): with override_provides("service_behavior_component_form_part", DEFAULT_BEHAVIOR_FORM_PARTS): initialized_view = view(request=request, kwargs={"pk": object.pk}) return initialized_view.get_form_parts(object)
def test_method_edit_save(rf, admin_user, view, model, get_object, service_provider_attr): """ To make things little bit more simple let's use only english as an language. """ with override_settings(LANGUAGES=[("en", "en")]): object = get_object() object.choice_identifier = "" object.save() assert object.choice_identifier == "" view = view.as_view() service_provider_attr_field = "base-%s" % service_provider_attr data = { "base-name__en": object.name, "base-shop": object.shop.id, "base-tax_class": object.tax_class.id, "base-enabled": True, service_provider_attr_field: getattr(object, service_provider_attr).pk, "base-choice_identifier": "manual" } methods_before = model.objects.count() # Behavior components is tested at shoop.tests.admin.test_service_behavior_components with override_provides("service_behavior_component_form", []): with override_provides("service_behavior_component_form_part", []): request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=object.pk) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] assert model.objects.count() == methods_before assert model.objects.get(pk=object.pk).choice_identifier == "manual"
def test_campaign_edit_save(rf, admin_user): """ To make things little bit more simple let's use only english as a language. """ with override_settings(LANGUAGES=[("en", "en")]): shop = get_default_shop() object = BasketCampaign.objects.create(name="test campaign", active=True, shop=shop) object.save() view = BasketCampaignEditView.as_view() new_name = "Test Campaign" assert object.name != new_name data = { "base-name": new_name, "base-public_name__en": "Test Campaign", "base-shop": get_default_shop().id, "base-active": True, "base-basket_line_text": "Test campaign activated!" } methods_before = BasketCampaign.objects.count() # Conditions and effects is tested separately with override_provides("campaign_basket_condition", []): with override_provides("basket_campaign_effect", []): request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=object.pk) assert response.status_code in [200, 302] assert BasketCampaign.objects.count() == methods_before assert BasketCampaign.objects.get(pk=object.pk).name == new_name
def test_rules_and_effects(rf, admin_user): """ To make things little bit more simple let's use only english as a language. """ get_default_shop() with override_settings(LANGUAGES=[("en", "en")]): shop = get_default_shop() object = BasketCampaign.objects.create(name="test campaign", active=True, shop=shop) assert object.conditions.count() == 0 assert object.effects.count() == 0 view = BasketCampaignEditView.as_view() data = { "base-name": "test campaign", "base-public_name__en": "Test Campaign", "base-shop": get_default_shop().id, "base-active": True, "base-basket_line_text": "Test campaign activated!" } with override_provides( "campaign_basket_condition", ["shoop.campaigns.admin_module.forms:BasketTotalProductAmountConditionForm"]): with override_provides( "basket_campaign_effect", ["shoop.campaigns.admin_module.forms:BasketDiscountAmountForm"]): data.update(get_products_in_basket_data()) data.update(get_free_product_data(object)) request = apply_request_middleware(rf.post("/", data=data), user=admin_user) view(request, pk=object.pk) object.refresh_from_db() assert object.conditions.count() == 1 assert object.effects.count() == 1
def test_campaign_end_date(rf, admin_user): """ To make things little bit more simple let's use only english as a language. """ with override_settings(LANGUAGES=[("en", "en")]): shop = get_default_shop() old_name = "test_campaign" object = CatalogCampaign.objects.create(name=old_name, active=True, shop=shop) object.save() view = CatalogCampaignEditView.as_view() new_name = "Test Campaign" assert object.name != new_name data = { "base-name": new_name, "base-public_name__en": "Test Campaign", "base-shop": get_default_shop().id, "base-active": True, "base-basket_line_text": "Test campaign activated!", "base-start_datetime": datetime.datetime(year=2016, month=6, day=19), "base-end_datetime": datetime.datetime(year=2016, month=6, day=10) } methods_before = CatalogCampaign.objects.count() # Conditions, effects and effects is tested separately with override_provides("campaign_context_condition", []): with override_provides("campaign_catalog_filter", []): with override_provides("catalog_campaign_effect", []): request = apply_request_middleware(rf.post("/", data=data), user=admin_user) response = view(request, pk=object.pk) assert response.status_code in [200, 302] content = response.render().content.decode("utf-8") assert "Campaign end date can't be before start date." in content assert CatalogCampaign.objects.count() == methods_before assert CatalogCampaign.objects.get(pk=object.pk).name == old_name
def test_stacked_tax_taxful_price(): source = OrderSource() source.lines = [ SourceLine(source=source, type=OrderLineType.OTHER, quantity=1, unit_price=TaxfulPrice(20)) ] with override_provides("tax_module", ["shoop_tests.functional.test_tax_system:IrvineCaliforniaTaxation"]): with override_settings(SHOOP_TAX_MODULE="irvine"): source.billing_address = Address( street="16215 Alton Pkwy", postal_code="92602", ) line = source.get_final_lines()[0] assert isinstance(line, SourceLine) assert line.taxes assert line.taxful_total_price == TaxfulPrice(20) assert abs(line.taxless_total_price.amount - Decimal("18.519")) < Decimal("0.01") source.uncache() # Let's move out to a taxless location. source.billing_address.postal_code = "11111" line = source.get_final_lines()[0] assert isinstance(line, SourceLine) assert not line.taxes assert line.taxful_total_price == TaxfulPrice(20) assert line.taxless_total_price.amount == Decimal("20")
def test_stacked_tax_taxful_price(): source = OrderSource() source.lines = [ SourceLine(source=source, type=OrderLineType.OTHER, quantity=1, unit_price=TaxfulPrice(20)) ] with override_provides( "tax_module", ["shoop_tests.functional.test_tax_system:IrvineCaliforniaTaxation"]): with override_settings(SHOOP_TAX_MODULE="irvine"): source.billing_address = Address( street="16215 Alton Pkwy", postal_code="92602", ) line = source.get_final_lines()[0] assert isinstance(line, SourceLine) assert line.taxes assert line.taxful_total_price == TaxfulPrice(20) assert abs(line.taxless_total_price.amount - Decimal("18.519")) < Decimal("0.01") source.uncache() # Let's move out to a taxless location. source.billing_address.postal_code = "11111" line = source.get_final_lines()[0] assert isinstance(line, SourceLine) assert not line.taxes assert line.taxful_total_price == TaxfulPrice(20) assert line.taxless_total_price.amount == Decimal("20")
def test_extending_shipment_form_valid_hook(rf, admin_user): shop = get_default_shop() supplier = get_default_supplier() product = create_product(sku="test-sku", shop=shop, supplier=supplier, default_price=3.33) quantity = 1 order = create_order_with_product(product, supplier, quantity=quantity, taxless_base_unit_price=1, shop=shop) extend_form_class = "shoop_tests.admin.test_shipment_creator.ShipmentFormModifierTest" with override_provides(FORM_MODIFIER_PROVIDER_KEY, [extend_form_class]): phone_number = "+358911" data = {"q_%s" % product.pk: 1, "supplier": supplier.pk, "phone": phone_number} request = apply_request_middleware(rf.post("/", data=data), user=admin_user) view = OrderCreateShipmentView.as_view() response = view(request, pk=order.pk) assert response.status_code == 302 # Order should now have shipment, but let's re fetch it first order = Order.objects.get(pk=order.pk) assert order.shipments.count() == 1 shipment = order.shipments.first() assert order.shipping_data.get(shipment.identifier).get("phone") == phone_number assert shipment.supplier_id == supplier.id assert shipment.products.count() == 1 assert shipment.products.first().product_id == product.id
def test_stacked_tax_taxful_price(): shop = get_shop(prices_include_tax=True, currency='EUR') source = OrderSource(shop) assert source.prices_include_tax source.add_line( type=OrderLineType.OTHER, quantity=1, base_unit_price=source.create_price(20) ) with override_provides("tax_module", TAX_MODULE_SPEC): with override_settings(SHOOP_TAX_MODULE="irvine"): source.shipping_address = MutableAddress( street="16215 Alton Pkwy", postal_code="92602", ) line = source.get_final_lines(with_taxes=True)[0] assert isinstance(line, SourceLine) assert line.taxes assert line.taxful_price == TaxfulPrice(20, 'EUR') assert_almost_equal(line.taxless_price, TaxlessPrice("18.518518", 'EUR')) source.uncache() # Let's move out to a taxless location. source.shipping_address.postal_code = "11111" line = source.get_final_lines(with_taxes=True)[0] assert isinstance(line, SourceLine) assert not line.taxes assert line.taxful_price == TaxfulPrice(20, source.currency) assert line.taxless_price.value == Decimal("20")
def test_simple_addon_injection(): request = get_request(edit=False) jeng = get_jinja2_engine() template = jeng.get_template("resinject.jinja") with override_current_theme_class(): with override_provides( "xtheme_resource_injection", ["shoop_tests.xtheme.test_addon_injections:add_test_injection",]): # TestInjector should add alert to end of the body for every request output = template.render(request=request) head, body = output.split("</head>", 1) assert "window.injectedFromAddon=true;" in body
def test_simple_addon_injection(): request = get_request(edit=False) jeng = get_jinja2_engine() template = jeng.get_template("resinject.jinja") with override_current_theme_class(): with override_provides("xtheme_resource_injection", [ "shoop_tests.xtheme.test_addon_injections:add_test_injection", ]): # TestInjector should add alert to end of the body for every request output = template.render(request=request) head, body = output.split("</head>", 1) assert "window.injectedFromAddon=true;" in body
def test_theme_activation(): with override_current_theme_class(): with override_provides("xtheme", [ "shoop_tests.xtheme.utils:FauxTheme", "shoop_tests.xtheme.utils:FauxTheme2" ]): ThemeSettings.objects.all().delete() assert not get_current_theme() set_current_theme(FauxTheme.identifier) assert isinstance(get_current_theme(), FauxTheme) set_current_theme(FauxTheme2.identifier) assert isinstance(get_current_theme(), FauxTheme2) with pytest.raises(ValueError): set_current_theme(printable_gibberish())
def test_theme_settings_api(): with override_provides("xtheme", [ "shoop_tests.xtheme.utils:FauxTheme", "shoop_tests.xtheme.utils:FauxTheme2" ]): ThemeSettings.objects.all().delete() theme = get_theme_by_identifier(FauxTheme2.identifier) theme.set_setting("foo", "bar") theme.set_settings(quux=[4, 8, 15, 16, 23, 42]) theme = get_theme_by_identifier(FauxTheme2.identifier) assert theme.get_setting("foo") == "bar" assert theme.get_settings() == { "foo": "bar", "quux": [4, 8, 15, 16, 23, 42] }
def initialize_editor_view(view_name, placeholder_name, request=None): if request is None: request = RequestFactory().get("/") request.user = SuperUser() if hasattr(request.GET, "_mutable"): request.GET._mutable = True # Ahem request.GET.update({ "theme": FauxTheme.identifier, "view": view_name, "ph": placeholder_name }) with plugin_override(): with override_provides("xtheme", ["shoop_tests.xtheme.utils:FauxTheme"]): with override_current_theme_class(FauxTheme): yield EditorView(request=request, args=(), kwargs={})
def test_extending_shipment_clean_hook(rf, admin_user): shop = get_default_shop() supplier = get_default_supplier() product = create_product(sku="test-sku", shop=shop, supplier=supplier, default_price=3.33) quantity = 1 order = create_order_with_product(product, supplier, quantity=quantity, taxless_base_unit_price=1, shop=shop) extend_form_class = "shoop_tests.admin.test_shipment_creator.ShipmentFormModifierTest" with override_provides(FORM_MODIFIER_PROVIDER_KEY, [extend_form_class]): data = {"q_%s" % product.pk: 1, "supplier": supplier.pk, "phone": "911"} request = apply_request_middleware(rf.post("/", data=data), user=admin_user) view = OrderCreateShipmentView.as_view() response = view(request, pk=order.pk).render() assert response.status_code == 200 soup = BeautifulSoup(response.content) assert soup.body.findAll(text=re.compile("Phone number should start with country code!"))
def test_theme_selection(): """ Test that a theme with a `template_dir` actually affects template directory selection. """ with override_current_theme_class(), override_provides("xtheme", [ "shoop_tests.xtheme.utils:FauxTheme", "shoop_tests.xtheme.utils:FauxTheme2", "shoop_tests.xtheme.utils:H2G2Theme", ]): ThemeSettings.objects.all().delete() for theme in get_provide_objects("xtheme"): set_current_theme(theme.identifier) je = get_jinja2_engine() wrapper = (noop() if theme.identifier == "h2g2" else pytest.raises(TemplateDoesNotExist)) with wrapper: t = je.get_template("42.jinja") content = t.render().strip() assert "a slice of lemon wrapped around a large gold brick" in content.replace("\n", " ")
def test_provides(): IDENTIFIED_OBJECT_SPEC = "%s:IdentifiedObject" % __name__ category = str(uuid.uuid4()) with override_provides(category, [ IDENTIFIED_OBJECT_SPEC, "%s:UnidentifiedObject" % __name__, "%s:VeryUnidentifiedObject" % __name__, ]): objects = get_provide_objects(category) assert set(objects) == set((IdentifiedObject, UnidentifiedObject, VeryUnidentifiedObject)) assert get_identifier_to_object_map(category)["identifier"] == IdentifiedObject assert get_identifier_to_spec_map(category)["identifier"] == IDENTIFIED_OBJECT_SPEC assert get_provide_specs_and_objects(category)[IDENTIFIED_OBJECT_SPEC] == IdentifiedObject # Test the context manager clears things correctly assert empty_iterable(get_provide_objects(category)) assert empty_iterable(get_provide_specs_and_objects(category)) assert empty_iterable(get_identifier_to_object_map(category)) assert empty_iterable(get_identifier_to_spec_map(category))
def test_stacked_tax_taxless_price(): source = OrderSource(get_shop(prices_include_tax=False)) assert source.prices_include_tax is False source.add_line(type=OrderLineType.OTHER, quantity=1, base_unit_price=source.create_price(10)) with override_provides("tax_module", TAX_MODULE_SPEC): with override_settings(SHOOP_TAX_MODULE="irvine"): source.shipping_address = Address(street="16215 Alton Pkwy", postal_code="92602") line = source.get_final_lines(with_taxes=True)[0] assert isinstance(line, SourceLine) assert line.taxes assert line.taxful_price.value == Decimal("10.800") source.uncache() # Let's move out to a taxless location. source.shipping_address.postal_code = "11111" line = source.get_final_lines(with_taxes=True)[0] assert isinstance(line, SourceLine) assert not line.taxes assert line.taxful_price.value == Decimal("10")
def get_bs_object_for_view(request, view, user, object=None): """ Help function to get BeautifulSoup object from the html rendered by the edit view. Also override ``service_provider_admin_form`` here to enable ``PseudoPaymentProcessor`` """ with override_provides("service_provider_admin_form", [ "shoop.testing.service_forms.PseudoPaymentProcessorForm", "shoop.admin.modules.service_providers.forms:CustomCarrierForm", "shoop.admin.modules.service_providers.forms:CustomPaymentProcessorForm" ]): request = apply_request_middleware(request, user=user) response = view(request, pk=object.pk if object else None) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] return BeautifulSoup(response.content)
def test_extending_shipment_with_extra_fields(rf, admin_user): shop = get_default_shop() supplier = get_default_supplier() product = create_product(sku="test-sku", shop=shop, supplier=supplier, default_price=3.33) quantity = 1 order = create_order_with_product(product, supplier, quantity=quantity, taxless_base_unit_price=1, shop=shop) extend_form_class = "shoop_tests.admin.test_shipment_creator.ShipmentFormModifierTest" with override_provides(FORM_MODIFIER_PROVIDER_KEY, [extend_form_class]): request = apply_request_middleware(rf.get("/"), user=admin_user) view = OrderCreateShipmentView.as_view() response = view(request, pk=order.pk).render() assert response.status_code == 200 # Should contain supplier input, input for product and input for phone soup = BeautifulSoup(response.content) assert soup.find("input", {"id": "id_q_%s" % product.pk}) assert soup.find("select", {"id": "id_supplier"}) assert soup.find("input", {"id": "id_phone"})
def get_bs_object_for_view(request, view, user, object=None): """ Help function to get BeautifulSoup object from the html rendered by the edit view. Also override ``service_provider_admin_form`` here to enable ``PseudoPaymentProcessor`` """ with override_provides("service_provider_admin_form", [ "shoop.testing.payment_forms.PseudoPaymentProcessorForm", "shoop.admin.modules.service_providers.forms:CustomCarrierForm", "shoop.admin.modules.service_providers.forms:CustomPaymentProcessorForm" ]): request = apply_request_middleware(request, user=user) response = view(request, pk=object.pk if object else None) if hasattr(response, "render"): response.render() assert response.status_code in [200, 302] return BeautifulSoup(response.content)
def test_stacked_tax_taxless_price(): source = OrderSource(get_shop(prices_include_tax=False)) assert source.prices_include_tax is False source.add_line( type=OrderLineType.OTHER, quantity=1, base_unit_price=source.create_price(10) ) with override_provides("tax_module", TAX_MODULE_SPEC): with override_settings(SHOOP_TAX_MODULE="irvine"): source.shipping_address = MutableAddress( street="16215 Alton Pkwy", postal_code="92602", ) line = source.get_final_lines(with_taxes=True)[0] assert isinstance(line, SourceLine) assert line.taxes assert line.taxful_price.value == Decimal("10.800") source.uncache() # Let's move out to a taxless location. source.shipping_address.postal_code = "11111" line = source.get_final_lines(with_taxes=True)[0] assert isinstance(line, SourceLine) assert not line.taxes assert line.taxful_price.value == Decimal("10")
def get_form_parts(request, view, object): with override_provides("campaign_context_condition", DEFAULT_CONDITION_FORMS): with override_provides("campaign_catalog_filter", DEFAULT_FILTER_FORMS): with override_provides("catalog_campaign_effect", DEFAULT_EFFECT_FORMS): initialized_view = view(request=request, kwargs={"pk": object.pk}) return initialized_view.get_form_parts(object)
def override_provides_for_expensive_sweden_shipping_method(): return override_provides("shipping_method_module", [SHIPPING_METHOD_SPEC])
def get_form_parts(request, view, object): with override_provides("service_behavior_component_form", DEFAULT_BEHAVIOR_FORMS): initialized_view = view(request=request, kwargs={"pk": object.pk}) return initialized_view.get_form_parts(object)
# This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import pytest from django.conf import settings from shoop.apps.provides import override_provides from shoop.core.pricing import ( DiscountModule, get_price_info, get_price_infos, get_pricing_steps, get_pricing_steps_for_products ) from shoop.testing.factories import create_product, get_default_shop from shoop.testing.utils import apply_request_middleware provide_overrider = override_provides( "discount_module", [__name__ + ':Minus25DiscountModule']) def setup_module(module): global original_pricing_module global original_discount_modules original_pricing_module = settings.SHOOP_PRICING_MODULE original_discount_modules = settings.SHOOP_DISCOUNT_MODULES settings.SHOOP_PRICING_MODULE = "default_pricing" settings.SHOOP_DISCOUNT_MODULES = ["minus25"] provide_overrider.__enter__() def teardown_module(module):
from shoop.apps.provides import override_provides from shoop.core.models import ( AnonymousContact, Product, Order, OrderLine, OrderLineType, Shop ) from shoop.core.order_creator import OrderSource from shoop.core.pricing import ( get_pricing_module, PriceInfo, PricingModule, TaxlessPrice ) from shoop.front.basket.objects import BaseBasket PRICING_MODULE_SPEC = __name__ + ':DummyPricingModule' original_pricing_module = settings.SHOOP_PRICING_MODULE original_discount_modules = settings.SHOOP_DISCOUNT_MODULES pricing_overrider = override_provides("pricing_module", [PRICING_MODULE_SPEC]) def setup_module(module): settings.SHOOP_PRICING_MODULE = "dummy_pricing_module" settings.SHOOP_DISCOUNT_MODULES = [] pricing_overrider.__enter__() def teardown_module(module): pricing_overrider.__exit__(None, None, None) settings.SHOOP_PRICING_MODULE = original_pricing_module settings.SHOOP_DISCOUNT_MODULES = original_discount_modules class DummyPricingModule(PricingModule):
def test_extendable_helper_ns(): with override_provides("front_template_helper_namespace", [ "%s:TestNs" % __name__ ]): ns = _get_helpers() assert ns.badgers.snake()
def plugin_override(): return override_provides("xtheme_plugin", [ "shoop.xtheme.plugins.text:TextPlugin", "shoop_tests.xtheme.test_resources:ResourceInjectorPlugin" ])
from shoop.apps.provides import override_provides from shoop.core.models import ( AnonymousContact, Product, Shop, Tax, TaxClass ) from shoop.core.pricing import PriceInfo, TaxfulPrice, TaxlessPrice from shoop.core.taxing import SourceLineTax, TaxedPrice, TaxModule from shoop.core.utils.prices import convert_taxness from shoop.utils.money import Money TAX_MODULE_SPEC = __name__ + ':DummyTaxModule' original_tax_module = settings.SHOOP_TAX_MODULE tax_mod_overrider = override_provides("tax_module", [TAX_MODULE_SPEC]) def setup_module(module): settings.SHOOP_TAX_MODULE = "dummy_tax_module" tax_mod_overrider.__enter__() def teardown_module(module): tax_mod_overrider.__exit__(None, None, None) settings.SHOOP_TAX_MODULE = original_tax_module class DummyTaxModule(TaxModule): calculations_done = 0
# # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import decimal import pytest from django.conf import settings from shoop.apps.provides import override_provides from shoop.core.pricing import (DiscountModule, get_price_info, get_price_infos, get_pricing_steps, get_pricing_steps_for_products) from shoop.testing.factories import create_product, get_default_shop from shoop.testing.utils import apply_request_middleware provide_overrider = override_provides("discount_module", [__name__ + ':Minus25DiscountModule']) def setup_module(module): global original_pricing_module global original_discount_modules original_pricing_module = settings.SHOOP_PRICING_MODULE original_discount_modules = settings.SHOOP_DISCOUNT_MODULES settings.SHOOP_PRICING_MODULE = "default_pricing" settings.SHOOP_DISCOUNT_MODULES = ["minus25"] provide_overrider.__enter__() def teardown_module(module):
def test_extendable_helper_ns(): with override_provides("front_template_helper_namespace", ["%s:TestNs" % __name__]): ns = _get_helpers() assert ns.badgers.snake()