def test_update_injection(): shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") page = ensure_gdpr_privacy_policy(shop) shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.enabled = True shop_gdpr.privacy_policy = page shop_gdpr.save() assert_update(client, index_url, False) # nothing consented in past, should not show user = factories.create_random_user("en") password = "******" user.set_password(password) user.save() client.login(username=user.username, password=password) assert_update(client, index_url, False) # no consent given, should not be visible create_user_consent_for_all_documents(shop, user) assert_update(client, index_url, False) with reversion.create_revision(): page.save() assert not is_documents_consent_in_sync(shop, user) assert_update(client, index_url, True) # consent client.get(reverse("shuup:gdpr_policy_consent", kwargs=dict(page_id=page.pk))) assert is_documents_consent_in_sync(shop, user) assert_update(client, index_url, False)
def test_update_injection(): shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") page = ensure_gdpr_privacy_policy(shop) shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.enabled = True shop_gdpr.privacy_policy = page shop_gdpr.save() assert_update(client, index_url, False) # nothing consented in past, should not show user = factories.create_random_user("en") password = "******" user.set_password(password) user.save() client.login(username=user.username, password=password) assert_update(client, index_url, False) # no consent given, should not be visible create_user_consent_for_all_documents(shop, user) assert_update(client, index_url, False) with reversion.create_revision(): page.save() assert not is_documents_consent_in_sync(shop, user) assert_update(client, index_url, True) # consent client.get(reverse("shuup:gdpr_policy_consent", kwargs=dict(page_id=page.pk))) assert is_documents_consent_in_sync(shop, user) assert_update(client, index_url, False)
def test_resource_injection(client): """ Test that the GDPR warning is injected into the front template when enabled """ activate("en") shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") response = client.get(index_url) assert "gdpr-consent-warn-bar" not in response.content.decode("utf-8") # create a GDPR setting for the shop shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.cookie_banner_content = "my cookie banner content" shop_gdpr.cookie_privacy_excerpt = " my cookie privacyexcerpt" shop_gdpr.enabled = True shop_gdpr.save() # the contents should be injected in the html response = client.get(index_url) response_content = response.content.decode("utf-8") assert "gdpr-consent-warn-bar" in response_content assert shop_gdpr.cookie_banner_content in response_content assert shop_gdpr.cookie_privacy_excerpt in response_content # create cookie categories cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=True, cookies="cookie1,cookie2,_cookie3", name="RequiredCookies", how_is_used="to make the site work", ) default_active_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, default_active=True, cookies="analyticsCookie", name="Analytics", how_is_used="to track users", ) response, soup = client.response_and_soup(index_url) response_content = response.content.decode("utf-8") assert "gdpr-consent-warn-bar" in response_content assert cookie_category.cookies in response_content assert cookie_category.name in response_content assert cookie_category.how_is_used in response_content default_active_input = soup.find( "input", {"name": "cookie_category_%d" % default_active_cookie_category.pk}) assert default_active_input.has_attr("checked") # make sure no other shop has this with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True): shop2 = factories.get_shop(identifier="shop2", status=ShopStatus.DISABLED, domain="shop2") response = client.get(index_url, HTTP_HOST=shop2.domain) response_content = response.content.decode("utf-8") assert "gdpr-consent-warn-bar" not in response_content
def test_consent_cookies(client): """ Test that the GDPR consent is generated and saved into a cooki """ shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") response = client.get(index_url) # create a GDPR setting for the shop shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.cookie_banner_content = "my cookie banner content" shop_gdpr.cookie_privacy_excerpt = "my cookie privacyexcerpt" shop_gdpr.enabled = True shop_gdpr.save() # create cookie categories required_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=True, cookies="cookie1,cookir2,_cookie3", name="RequiredCookies", how_is_used="to make the site work") optional_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, cookies="_opt1,_opt2,_opt3", name="OptionalCookies", how_is_used="to spy users") # create privacy policy GDPR document privacy_policy = Page.objects.create( shop=shop, title="Privacy policy", url="privacy-policy", page_type=PageType.GDPR_CONSENT_DOCUMENT, content="you just agree", available_from=now()) response = client.get(index_url) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME not in response.cookies # send consent response = client.post( reverse("shuup:gdpr_consent"), data={ "cookie_category_{}".format(required_cookie_category.id): "on", "cookie_category_{}".format(optional_cookie_category.id): "on" }) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME in response.cookies cookies_data = json.loads( response.cookies[settings.SHUUP_GDPR_CONSENT_COOKIE_NAME].value) assert privacy_policy.id == cookies_data["documents"][0]["id"] assert privacy_policy.url == cookies_data["documents"][0]["url"] for cookie in required_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] for cookie in optional_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"]
def test_consent_cookies(): """ Test that the GDPR consent is generated and saved into a cooki """ for code, lang in settings.LANGUAGES: activate(code) shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") response = client.get(index_url) # create a GDPR setting for the shop shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.cookie_banner_content = "my cookie banner content" shop_gdpr.cookie_privacy_excerpt = "my cookie privacyexcerpt" shop_gdpr.enabled = True shop_gdpr.save() # create cookie categories required_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=True, cookies="cookie1,cookir2,_cookie3", name="RequiredCookies", how_is_used="to make the site work" ) optional_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, cookies="_opt1,_opt2,_opt3", name="OptionalCookies", how_is_used="to spy users" ) # create privacy policy GDPR document privacy_policy = ensure_gdpr_privacy_policy(shop) response = client.get(index_url) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME not in response.cookies # send consent response = client.post(reverse("shuup:gdpr_consent"), data={ "cookie_category_{}".format(required_cookie_category.id): "on", "cookie_category_{}".format(optional_cookie_category.id): "on" }) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME in response.cookies cookies_data = json.loads(response.cookies[settings.SHUUP_GDPR_CONSENT_COOKIE_NAME].value) assert privacy_policy.id == cookies_data["documents"][0]["id"] assert privacy_policy.url == cookies_data["documents"][0]["url"] for cookie in required_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] for cookie in optional_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"]
def test_download_examples(rf, admin_user): shop = get_default_shop() import_url = reverse("shuup_admin:importer.import.new") shop.staff_members.add(admin_user) client = SmartClient() client.login(username="******", password="******") # test downloading all default importers from shuup.importer.utils import get_importer, get_importer_choices assert len(get_importer_choices()) for importer, name in get_importer_choices(): importer_cls = get_importer(importer) if importer_cls.has_example_file(): import_response = client.get("{}?importer={}".format( import_url, importer_cls.identifier)) assert import_response.status_code == 200 assert "This importer provides example files" in import_response.content.decode( "utf-8") for example_file in importer_cls.example_files: assert example_file.file_name in import_response.content.decode( "utf-8") # download file download_url = "{}?importer={}&file_name={}".format( reverse("shuup_admin:importer.download_example"), importer_cls.identifier, example_file.file_name) response = client.get(download_url) if importer_cls.identifier == "dummy_file_importer": assert response.status_code == 404 else: assert response.status_code == 200 assert response._headers["content-type"] == ( "Content-Type", str(example_file.content_type)) assert response._headers["content-disposition"] == ( "Content-Disposition", "attachment; filename=%s" % example_file.file_name, ) if example_file.template_name: from django.template.loader import get_template template_file = get_template( example_file.template_name).template.filename assert open( template_file, "r").read().strip() == response.content.decode( "utf-8").strip() else: assert response.content
def test_shop_remove_available_languages(admin_user): shop = factories.get_default_shop() client = SmartClient() with override_settings(LANGUAGES=[ ("en", "English"), ("fi", "Finnish"), ], LANGUAGE_CODE="en", PARLER_DEFAULT_LANGUAGE_CODE="en"): # there is no language set for the shop, the first one will be used response = client.get(reverse("shuup:index")) assert get_language() == "en" # request js catalog file response = client.get(reverse("shuup:js-catalog")) assert get_language() == "en" # when requesting admin js catalog, the language should be any of the available client.get("shuup_admin:js-catalog") assert get_language() == "en" set_shop_available_languages(shop, ["fi"]) response = client.get(reverse("shuup:index")) assert get_language() == "fi" response = client.get(reverse("shuup:js-catalog")) assert get_language() == "fi" client.get("shuup_admin:js-catalog") assert get_language() == "en"
def test_shop_remove_available_languages(admin_user): shop = factories.get_default_shop() client = SmartClient() with override_settings( LANGUAGES=[ ("en", "English"), ("fi", "Finnish"), ], LANGUAGE_CODE="en", PARLER_DEFAULT_LANGUAGE_CODE = "en" ): # there is no language set for the shop, the first one will be used response = client.get(reverse("shuup:index")) assert get_language() == "en" # request js catalog file response = client.get(reverse("shuup:js-catalog")) assert get_language() == "en" # when requesting admin js catalog, the language should be any of the available client.get("shuup_admin:js-catalog") assert get_language() == "en" set_shop_available_languages(shop, ["fi"]) response = client.get(reverse("shuup:index")) assert get_language() == "fi" response = client.get(reverse("shuup:js-catalog")) assert get_language() == "fi" client.get("shuup_admin:js-catalog") assert get_language() == "en"
def test_authenticate_form_without_consent_checkboxes(client): activate("en") shop = factories.get_default_shop() user = factories.create_random_user("en") user.email = "*****@*****.**" user.set_password("1234") user.save() consent_text = printable_gibberish() gdpr_settings = GDPRSettings.get_for_shop(shop) gdpr_settings.enabled = True gdpr_settings.skip_consent_on_auth = True gdpr_settings.auth_consent_text = consent_text gdpr_settings.save() # create privacy policy GDPR document privacy_policy = ensure_gdpr_privacy_policy(shop) redirect_target = "/redirect-success/" client = SmartClient() login_url = reverse("shuup:login") response = client.get(login_url) soup = BeautifulSoup(response.content) login_form = soup.find("form", {"action": "/login/"}) assert len(login_form.findAll("input")) == 4 assert consent_text in login_form.text # user didn't check the privacy policy agreement response = client.post(login_url, data={ "username": user.email, "password": "******", REDIRECT_FIELD_NAME: redirect_target }) assert response.status_code == 302
def test_get_installments_3x_no_intereset(): """ Max 3 installs with no intereset """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) CieloConfig.objects.create(shop=shop, max_installments=3, installments_without_interest=3) order_total = PRODUCT_QTNTY * PRODUCT_PRICE total_price_str = "{0}".format(format_money(shop.create_price(order_total))) response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == 3 assert json_content['installments'][0]['number'] == 1 assert total_price_str in json_content['installments'][0]['name'] total_2x_no_interest = format_money(shop.create_price(order_total / Decimal(2))) assert json_content['installments'][1]['number'] == 2 assert total_price_str in json_content['installments'][1]['name'] assert total_2x_no_interest in json_content['installments'][1]['name'] total_3x_no_interest = format_money(shop.create_price(order_total / Decimal(3))) assert json_content['installments'][2]['number'] == 3 assert total_price_str in json_content['installments'][2]['name'] assert total_3x_no_interest in json_content['installments'][2]['name']
def test_get_installments_cc_does_not_allow_installments(): """ Max 9 installs with SIMPLE intereset interest_rate = 4.00% Credit card does not allow installments """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) CieloConfig.objects.create(shop=shop, max_installments=9, installments_without_interest=3, interest_type=InterestType.Simple, interest_rate=Decimal(4.0)) order_total = (PRODUCT_QTNTY * PRODUCT_PRICE) total_price_str = "{0}".format(format_money(shop.create_price(order_total))) response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Discover}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == 1 assert json_content['installments'][0]['number'] == 1 assert total_price_str in json_content['installments'][0]['name']
def test_get_installments_cc_does_not_allow_installments(): """ Max 9 installs with SIMPLE intereset interest_rate = 4.00% Credit card does not allow installments """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) CieloConfig.objects.create(shop=shop, max_installments=9, installments_without_interest=3, interest_type=InterestType.Simple, interest_rate=Decimal(4.0)) order_total = (PRODUCT_QTNTY * PRODUCT_PRICE) total_price_str = "{0}".format(format_money( shop.create_price(order_total))) response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Discover}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == 1 assert json_content['installments'][0]['number'] == 1 assert total_price_str in json_content['installments'][0]['name']
def test_get_installments_12x_with_simples_intereset(): """ Max 12 installs with PRICE intereset interest_rate = 2.30% min_installment_amount = 30.00 """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) cielo_config = CieloConfig.objects.create(shop=shop, max_installments=12, installments_without_interest=2, interest_type=InterestType.Price, interest_rate=Decimal(2.3), min_installment_amount=Decimal(30)) order_total = (PRODUCT_QTNTY * PRODUCT_PRICE) installment_choices = InstallmentContext(order_total, cielo_config).get_intallments_choices() response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == len(installment_choices) for installment in range(len(installment_choices)): total = format_money(shop.create_price(installment_choices[installment][2])) installment_amount = format_money(shop.create_price(installment_choices[installment][1])) assert json_content['installments'][installment]['number'] == installment+1 assert installment_amount in json_content['installments'][installment]['name'] assert total in json_content['installments'][installment]['name']
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("shuup: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 reverse("shuup:customer_edit") in response.url response = client.post(company_edit_url, data) assert reverse("shuup:customer_edit") in response.url
def test_notify_on_company_created(regular_user, allow_company_registration): if "shuup.front.apps.customer_information" not in settings.INSTALLED_APPS: pytest.skip("shuup.front.apps.customer_information required in installed apps") if "shuup.notify" not in settings.INSTALLED_APPS: pytest.skip("shuup.notify required in installed apps") configuration.set(None, "allow_company_registration", allow_company_registration) step = Step( cond_op=StepConditionOperator.NONE, actions=[ AddNotification( { "message": {"constant": "It Works. {{ customer_email }}"}, "message_identifier": {"constant": "company_created"}, } ) ], next=StepNext.STOP, ) script = Script( event_identifier=CompanyAccountCreated.identifier, name="Test Script", enabled=True, shop=get_default_shop() ) script.set_steps([step]) script.save() assert not Notification.objects.filter(identifier="company_created").exists() assert get_person_contact(regular_user) assert not get_company_contact(regular_user) client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("shuup:company_edit") if allow_company_registration: client.soup(company_edit_url) data = _default_company_data() data.update(_default_address_data("billing")) data.update(_default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert get_company_contact(regular_user) assert Notification.objects.filter(identifier="company_created").count() == 1 notification = Notification.objects.filter(identifier="company_created").first() assert notification assert data["contact-email"] in notification.message # New save should not add new notifications response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert Notification.objects.filter(identifier="company_created").count() == 1 script.delete() else: response = client.get(company_edit_url) assert reverse("shuup:customer_edit") in response.url assert Notification.objects.filter(identifier="company_created").count() == 0
def test_resource_injection(client): """ Test that the GDPR warning is injected into the front template when enabled """ activate("en") shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") response = client.get(index_url) assert "gdpr-consent-warn-bar" not in response.content.decode("utf-8") # create a GDPR setting for the shop shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.cookie_banner_content = "my cookie banner content" shop_gdpr.cookie_privacy_excerpt = " my cookie privacyexcerpt" shop_gdpr.enabled = True shop_gdpr.save() # the contents should be injected in the html response = client.get(index_url) response_content = response.content.decode("utf-8") assert "gdpr-consent-warn-bar" in response_content assert shop_gdpr.cookie_banner_content in response_content assert shop_gdpr.cookie_privacy_excerpt in response_content # create cookie categories cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=True, cookies="cookie1,cookie2,_cookie3", name="RequiredCookies", how_is_used="to make the site work" ) response = client.get(index_url) response_content = response.content.decode("utf-8") assert "gdpr-consent-warn-bar" in response_content assert cookie_category.cookies in response_content assert cookie_category.name in response_content assert cookie_category.how_is_used in response_content # make sure no other shop has this with override_settings(SHUUP_ENABLE_MULTIPLE_SHOPS=True): shop2 = factories.get_shop(identifier="shop2", status=ShopStatus.DISABLED, domain="shop2") response = client.get(index_url, HTTP_HOST=shop2.domain) response_content = response.content.decode("utf-8") assert "gdpr-consent-warn-bar" not in response_content
def test_download_examples(rf, admin_user): shop = get_default_shop() import_url = reverse("shuup_admin:importer.import") shop.staff_members.add(admin_user) client = SmartClient() client.login(username="******", password="******") # test downloading all default importers from shuup.importer.utils import get_importer, get_importer_choices assert len(get_importer_choices()) for importer, name in get_importer_choices(): importer_cls = get_importer(importer) if importer_cls.has_example_file(): import_response = client.get("{}?importer={}".format(import_url, importer_cls.identifier)) assert import_response.status_code == 200 assert "This importer provides example files" in import_response.content.decode("utf-8") for example_file in importer_cls.example_files: assert example_file.file_name in import_response.content.decode("utf-8") # download file download_url = "{}?importer={}&file_name={}".format( reverse("shuup_admin:importer.download_example"), importer_cls.identifier, example_file.file_name ) response = client.get(download_url) if importer_cls.identifier == "dummy_file_importer": assert response.status_code == 404 else: assert response.status_code == 200 assert response._headers["content-type"] == ("Content-Type", str(example_file.content_type)) assert response._headers["content-disposition"] == ("Content-Disposition", 'attachment; filename=%s' % example_file.file_name) if example_file.template_name: from django.template.loader import get_template template_file = get_template(example_file.template_name).template.filename assert open(template_file, "r").read().strip() == response.content.decode("utf-8").strip() else: assert response.content
def test_shop_available_languages(admin_user): original_language = get_language() shop = factories.get_default_shop() client = SmartClient() with override_settings( LANGUAGES=[ ("it", "Italian"), ("fr", "French"), ("fi", "Finnish"), ("pt", "Portuguese") ], LANGUAGE_CODE="it", PARLER_DEFAULT_LANGUAGE_CODE = "it" ): # there is no language set for the shop, the first one will be used response = client.get(reverse("shuup:index")) assert get_language() == "it" # set an invalid language code with pytest.raises(ValueError): set_shop_available_languages(shop, ["xpto"]) # limit the langauges for the shop to "fi" and "pt" set_shop_available_languages(shop, ["fi", "pt"]) # the middleware will automatically set the language to "fi" as that is the first one available for the shop response = client.get(reverse("shuup:index")) assert get_language() == "fi" # the same won't happen for any other url - the middleware will only affect front urls client.get("shuup_admin:index") assert get_language() == "it" # test againt front again client.get(reverse("shuup:index")) assert get_language() == "fi" # again for admin client.get("shuup_admin:index") assert get_language() == "it" # remote all available languages set_shop_available_languages(shop, []) # this should fallback to settings.LAGUAGE_CODE response = client.get(reverse("shuup:index")) assert get_language() == "it" activate(original_language)
def test_serialize_data(): """ Test contact dashboard views """ activate("en") shop = factories.get_default_shop() customer = factories.create_random_person("en") user = factories.create_random_user("en") user.set_password("1234") user.save() customer.user = user customer.default_billing_address = factories.create_random_address() customer.default_shipping_address = factories.create_random_address() customer.save() company = factories.create_random_company() company.default_billing_address = factories.create_random_address() company.default_shipping_address = factories.create_random_address() company.save() company.members.add(customer) product = factories.create_product("p1", shop, factories.get_default_supplier()) for basket_customer in [customer, company]: [ factories.create_random_order(basket_customer, [product]) for order in range(3) ] client = SmartClient() client.login(username=user.username, password="******") response = client.get(reverse("shuup:gdpr_customer_dashboard")) assert response.status_code == 200 assert "My Data" in response.content.decode("utf-8") response = client.post(reverse("shuup:gdpr_download_data")) assert response._headers["content-disposition"][0] == "Content-Disposition" assert response.status_code == 200 from shuup.tasks.models import Task, TaskType from shuup.gdpr.models import GDPR_ANONYMIZE_TASK_TYPE_IDENTIFIER response = client.post(reverse("shuup:gdpr_anonymize_account")) assert response.status_code == 302 assert response.url.endswith(reverse("shuup:index")) task_type = TaskType.objects.get( identifier=GDPR_ANONYMIZE_TASK_TYPE_IDENTIFIER, shop=shop) assert Task.objects.get(type=task_type, shop=shop) user.refresh_from_db() assert user.is_active is False refreshed_customer = PersonContact.objects.get(id=customer.id) assert refreshed_customer.is_active is False assert refreshed_customer.name == customer.name # nothing changed yet
def test_notify_on_company_created(regular_user, allow_company_registration): if "shuup.front.apps.customer_information" not in settings.INSTALLED_APPS: pytest.skip("shuup.front.apps.customer_information required in installed apps") if "shuup.notify" not in settings.INSTALLED_APPS: pytest.skip("shuup.notify required in installed apps") configuration.set(None, "allow_company_registration", allow_company_registration) step = Step( cond_op=StepConditionOperator.NONE, actions=[ AddNotification({ "message": {"constant": "It Works. {{ customer_email }}"}, "message_identifier": {"constant": "company_created"}, }) ], next=StepNext.STOP ) script = Script( event_identifier=CompanyAccountCreated.identifier, name="Test Script", enabled=True, shop=get_default_shop()) script.set_steps([step]) script.save() assert not Notification.objects.filter(identifier="company_created").exists() assert get_person_contact(regular_user) assert not get_company_contact(regular_user) client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("shuup:company_edit") if allow_company_registration: client.soup(company_edit_url) data = _default_company_data() data.update(_default_address_data("billing")) data.update(_default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert get_company_contact(regular_user) assert Notification.objects.filter(identifier="company_created").count() == 1 notification = Notification.objects.filter(identifier="company_created").first() assert notification assert data["contact-email"] in notification.message # New save should not add new notifications response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert Notification.objects.filter(identifier="company_created").count() == 1 script.delete() else: response = client.get(company_edit_url) assert reverse("shuup:customer_edit") in response.url assert Notification.objects.filter(identifier="company_created").count() == 0
def test_get_installments_options_rest(): patch_cielo_request() shop = get_default_shop() c = SmartClient() # method not allowed response = c.post(INSTALLMENTS_PATH) assert response.status_code == 405 # missing parameters response = c.get(INSTALLMENTS_PATH) assert response.status_code == 400 # no CieloConfig for shop response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) assert response.status_code == 400 CieloConfig.objects.create(shop=shop) # basket not valid (no products and not payment/shipping methods) response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) assert response.status_code == 400 create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') # configures the user basket _configure_basket(c) # only 1 installment, because no configurations were set on CieloConfig response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) assert response.status_code == 200 # should be the order total order_total = PRODUCT_QTNTY * PRODUCT_PRICE total_price_str = "{0}".format(format_money( shop.create_price(order_total))) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == 1 assert json_content['installments'][0]['number'] == 1 assert total_price_str in json_content['installments'][0]['name']
def test_get_installments_options_rest(): patch_cielo_request() shop = get_default_shop() c = SmartClient() # method not allowed response = c.post(INSTALLMENTS_PATH) assert response.status_code == 405 # missing parameters response = c.get(INSTALLMENTS_PATH) assert response.status_code == 400 # no CieloConfig for shop response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) assert response.status_code == 400 CieloConfig.objects.create(shop=shop) # basket not valid (no products and not payment/shipping methods) response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) assert response.status_code == 400 create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') # configures the user basket _configure_basket(c) # only 1 installment, because no configurations were set on CieloConfig response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) assert response.status_code == 200 # should be the order total order_total = PRODUCT_QTNTY * PRODUCT_PRICE total_price_str = "{0}".format(format_money(shop.create_price(order_total))) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == 1 assert json_content['installments'][0]['number'] == 1 assert total_price_str in json_content['installments'][0]['name']
def test_shop_available_languages(admin_user): original_language = get_language() shop = factories.get_default_shop() client = SmartClient() with override_settings( LANGUAGES=[("it", "Italian"), ("fr", "French"), ("fi", "Finnish"), ("pt", "Portuguese")], LANGUAGE_CODE="it", PARLER_DEFAULT_LANGUAGE_CODE="it", ): # there is no language set for the shop, the first one will be used response = client.get(reverse("shuup:index")) assert get_language() == "it" # set an invalid language code with pytest.raises(ValueError): set_shop_available_languages(shop, ["xpto"]) # limit the langauges for the shop to "fi" and "pt" set_shop_available_languages(shop, ["fi", "pt"]) # the middleware will automatically set the language to "fi" as that is the first one available for the shop response = client.get(reverse("shuup:index")) assert get_language() == "fi" # the same won't happen for any other url - the middleware will only affect front urls client.get("shuup_admin:index") assert get_language() == "it" # test againt front again client.get(reverse("shuup:index")) assert get_language() == "fi" # again for admin client.get("shuup_admin:index") assert get_language() == "it" # remote all available languages set_shop_available_languages(shop, []) # this should fallback to settings.LAGUAGE_CODE response = client.get(reverse("shuup:index")) assert get_language() == "it" activate(original_language)
def test_serialize_data(): """ Test contact dashboard views """ activate("en") shop = factories.get_default_shop() customer = factories.create_random_person("en") user = factories.create_random_user("en") user.set_password("1234") user.save() customer.user = user customer.default_billing_address = factories.create_random_address() customer.default_shipping_address = factories.create_random_address() customer.save() company = factories.create_random_company() company.default_billing_address = factories.create_random_address() company.default_shipping_address = factories.create_random_address() company.save() company.members.add(customer) product = factories.create_product("p1", shop, factories.get_default_supplier()) for basket_customer in [customer, company]: [factories.create_random_order(basket_customer, [product]) for order in range(3)] client = SmartClient() client.login(username=user.username, password="******") response = client.get(reverse("shuup:gdpr_customer_dashboard")) assert response.status_code == 200 assert "My Data" in response.content.decode("utf-8") response = client.post(reverse("shuup:gdpr_download_data")) assert response._headers["content-disposition"][0] == "Content-Disposition" assert response.status_code == 200 from shuup.tasks.models import Task, TaskType from shuup.gdpr.models import GDPR_ANONYMIZE_TASK_TYPE_IDENTIFIER response = client.post(reverse("shuup:gdpr_anonymize_account")) assert response.status_code == 302 assert response.url.endswith(reverse("shuup:index")) task_type = TaskType.objects.get(identifier=GDPR_ANONYMIZE_TASK_TYPE_IDENTIFIER, shop=shop) assert Task.objects.get(type=task_type, shop=shop) user.refresh_from_db() assert user.is_active is False refreshed_customer = PersonContact.objects.get(id=customer.id) assert refreshed_customer.is_active is False assert refreshed_customer.name == customer.name # nothing changed yet
def test_task_type_admin(admin_user): activate("en") shop = factories.get_default_shop() admin_user.set_password(ADMIN_PWD) admin_user.save() admin_contact = get_person_contact(admin_user) admin_contact.shops.add(shop) client = SmartClient() client.login(username=admin_user.username, password=ADMIN_PWD) # Create new task type new_task_type_url = reverse("shuup_admin:task_type.new") assert TaskType.objects.count() == 0 # get the form fields soup = client.soup(new_task_type_url) payload = extract_form_fields(soup) payload.update({ "name__en": "My Task Type" }) response = client.post(new_task_type_url, payload) assert response.status_code == 302 assert TaskType.objects.count() == 1 task_type = TaskType.objects.first() # List task types list_task_type_url = reverse("shuup_admin:task_type.list") list_data = { "jq": json.dumps({ "sort": None, "perPage": 20, "page": 1, "filters": {} }) } response = client.get(list_task_type_url, data=list_data) assert task_type.name in response.content.decode("utf-8") # Edit task type edit_task_type_url = reverse("shuup_admin:task_type.edit", kwargs=dict(pk=task_type.pk)) soup = client.soup(edit_task_type_url) payload = extract_form_fields(soup) payload.update({ "name__en": "My Task Type Edited" }) response = client.post(edit_task_type_url, payload) assert response.status_code == 302
def test_authenticate_form(client): activate("en") shop = factories.get_default_shop() user = factories.create_random_user("en") user.email = "*****@*****.**" user.set_password("1234") user.save() gdpr_settings = GDPRSettings.get_for_shop(shop) gdpr_settings.enabled = True gdpr_settings.save() # create privacy policy GDPR document privacy_policy = ensure_gdpr_privacy_policy(shop) redirect_target = "/redirect-success/" client = SmartClient() login_url = reverse("shuup:login") response = client.get(login_url) soup = BeautifulSoup(response.content) login_form = soup.find("form", {"action": "/login/"}) assert len(login_form.findAll("input")) == 5 # 4 + privacy policy checkbox # user didn't check the privacy policy agreement response = client.post(reverse("shuup:login"), data={ "username": user.email, "password": "******", REDIRECT_FIELD_NAME: redirect_target }) assert response.status_code == 200 assert "You must accept this in order to authenticate." in response.content.decode( "utf-8") response = client.post( reverse("shuup:login"), data={ "username": user.email, "password": "******", "accept_%d" % privacy_policy.id: "on", REDIRECT_FIELD_NAME: redirect_target, }, ) assert response.status_code == 302 assert response.get("location") assert response.get("location").endswith(redirect_target)
def test_serialize_data(): """ Test contact dashboard views """ activate("en") shop = factories.get_default_shop() customer = factories.create_random_person("en") user = factories.create_random_user("en") user.set_password("1234") user.save() customer.user = user customer.default_billing_address = factories.create_random_address() customer.default_shipping_address = factories.create_random_address() customer.save() company = factories.create_random_company() company.default_billing_address = factories.create_random_address() company.default_shipping_address = factories.create_random_address() company.save() company.members.add(customer) product = factories.create_product("p1", shop, factories.get_default_supplier()) for basket_customer in [customer, company]: [ factories.create_random_order(basket_customer, [product]) for order in range(3) ] client = SmartClient() client.login(username=user.username, password="******") response = client.get(reverse("shuup:gdpr_customer_dashboard")) assert response.status_code == 200 assert "My Data" in response.content.decode("utf-8") response = client.post(reverse("shuup:gdpr_download_data")) assert response._headers["content-disposition"][0] == "Content-Disposition" assert response.status_code == 200 response = client.post(reverse("shuup:gdpr_anonymize_account")) assert response.status_code == 302 assert response.url.endswith(reverse("shuup:index"))
def test_get_installments_9x_with_simples_intereset(): """ Max 9 installs with SIMPLE intereset interest_rate = 4.00% """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) cielo_config = CieloConfig.objects.create( shop=shop, max_installments=9, installments_without_interest=3, interest_type=InterestType.Simple, interest_rate=Decimal(4.0)) SHIP_AMOUNT = Decimal(19.0) shipping_method = get_default_shipping_method() shipping_method.behavior_components.add( FixedCostBehaviorComponent.objects.create(price_value=SHIP_AMOUNT)) order_total = (PRODUCT_QTNTY * PRODUCT_PRICE) + SHIP_AMOUNT installment_choices = InstallmentContext( order_total, cielo_config).get_intallments_choices() response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == len(installment_choices) for installment in range(len(installment_choices)): total = format_money( shop.create_price(installment_choices[installment][2])) installment_amount = format_money( shop.create_price(installment_choices[installment][1])) assert json_content['installments'][installment][ 'number'] == installment + 1 assert installment_amount in json_content['installments'][installment][ 'name'] assert total in json_content['installments'][installment]['name']
def test_get_installments_12x_with_simples_intereset(): """ Max 12 installs with PRICE intereset interest_rate = 2.30% min_installment_amount = 30.00 """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) cielo_config = CieloConfig.objects.create( shop=shop, max_installments=12, installments_without_interest=2, interest_type=InterestType.Price, interest_rate=Decimal(2.3), min_installment_amount=Decimal(30)) order_total = (PRODUCT_QTNTY * PRODUCT_PRICE) installment_choices = InstallmentContext( order_total, cielo_config).get_intallments_choices() response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == len(installment_choices) for installment in range(len(installment_choices)): total = format_money( shop.create_price(installment_choices[installment][2])) installment_amount = format_money( shop.create_price(installment_choices[installment][1])) assert json_content['installments'][installment][ 'number'] == installment + 1 assert installment_amount in json_content['installments'][installment][ 'name'] assert total in json_content['installments'][installment]['name']
def test_get_installments_9x_with_simples_intereset(): """ Max 9 installs with SIMPLE intereset interest_rate = 4.00% """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) cielo_config = CieloConfig.objects.create(shop=shop, max_installments=9, installments_without_interest=3, interest_type=InterestType.Simple, interest_rate=Decimal(4.0)) SHIP_AMOUNT = Decimal(19.0) shipping_method = get_default_shipping_method() shipping_method.behavior_components.add( FixedCostBehaviorComponent.objects.create(price_value=SHIP_AMOUNT) ) order_total = (PRODUCT_QTNTY * PRODUCT_PRICE) + SHIP_AMOUNT installment_choices = InstallmentContext(order_total, cielo_config).get_intallments_choices() response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == len(installment_choices) for installment in range(len(installment_choices)): total = format_money(shop.create_price(installment_choices[installment][2])) installment_amount = format_money(shop.create_price(installment_choices[installment][1])) assert json_content['installments'][installment]['number'] == installment+1 assert installment_amount in json_content['installments'][installment]['name'] assert total in json_content['installments'][installment]['name']
def test_get_installments_3x_no_intereset(): """ Max 3 installs with no intereset """ patch_cielo_request() shop = get_default_shop() create_default_order_statuses() populate_if_required() set_current_theme('shuup.themes.classic_gray') c = SmartClient() _configure_basket(c) CieloConfig.objects.create(shop=shop, max_installments=3, installments_without_interest=3) order_total = PRODUCT_QTNTY * PRODUCT_PRICE total_price_str = "{0}".format(format_money( shop.create_price(order_total))) response = c.get(INSTALLMENTS_PATH, {"cc_brand": CieloCardBrand.Visa}) json_content = json.loads(response.content.decode("utf-8")) assert len(json_content['installments']) == 3 assert json_content['installments'][0]['number'] == 1 assert total_price_str in json_content['installments'][0]['name'] total_2x_no_interest = format_money( shop.create_price(order_total / Decimal(2))) assert json_content['installments'][1]['number'] == 2 assert total_price_str in json_content['installments'][1]['name'] assert total_2x_no_interest in json_content['installments'][1]['name'] total_3x_no_interest = format_money( shop.create_price(order_total / Decimal(3))) assert json_content['installments'][2]['number'] == 3 assert total_price_str in json_content['installments'][2]['name'] assert total_3x_no_interest in json_content['installments'][2]['name']
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("shuup: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 test_credit_card_success_3(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Sem URL para autenticação - 4 parcelas com juros """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.installments_without_interest = 1 cielo_config.interest_rate = Decimal(3.20) cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk }) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction( numero=1, valor=decimal_to_int_cents(ORDER_TOTAL), produto=CieloProduct.Credit, bandeira=CieloCardBrand.Visa, parcelas=CC_VISA_1X_INFO['installments'], tid=tid, return_url=None) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: pay c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) assert response.status_code == 200 json_content = json.loads(response.content.decode("utf-8")) assert json_content['redirect_url'].endswith( reverse("shuup:cielo_transaction_return", kwargs={"cielo_order_pk": 1})) choices = InstallmentContext( ORDER_TOTAL, cielo_config).get_intallments_choices() cielo_transaction = CieloTransaction.objects.get(tid=tid) assert cielo_transaction.cc_product == CieloProduct.InstallmentCredit assert abs(cielo_transaction.total_value - choices[3][2]) <= Decimal(0.01) assert cielo_transaction.status.value == transacao.status response = c.post(json_content['redirect_url']) confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() assert abs(order.taxful_total_price.value - choices[3][2]) <= Decimal(0.01) process_payment_path = reverse("shuup:order_process_payment", kwargs={ "pk": order.pk, "key": order.key }) process_payment_return_path = reverse( "shuup:order_process_payment_return", kwargs={ "pk": order.pk, "key": order.key }) response = c.get(process_payment_path) response = c.get(process_payment_return_path) cielo_transaction = CieloTransaction.objects.get( order_transaction__order=order, tid=tid) order.refresh_from_db() assert order.payment_data.get(CIELO_TRANSACTION_ID_KEY) assert order.payment_data.get(CIELO_ORDER_TRANSACTION_ID_KEY) assert order.payment_status == PaymentStatus.NOT_PAID
def test_company_tax_number_limitations(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) if allow_company_registration: client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("shuup:company_edit") soup = client.soup(company_edit_url) data = default_company_data() data.update(default_address_data("billing")) data.update(default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert get_company_contact(regular_user) # re-save should work properly response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 client.logout() # another company tries to use same tax number new_user_password = "******" new_user_username = "******" user = User.objects.create_user(new_user_username, "*****@*****.**", new_user_password) person = get_person_contact(user=user) assert not get_company_contact(user) client = SmartClient() client.login(username=new_user_username, password=new_user_password) company_edit_url = reverse("shuup:company_edit") soup = client.soup(company_edit_url) data = default_company_data() data.update(default_address_data("billing")) data.update(default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 200 # this time around, nothing was saved. assert not get_company_contact(user) # company contact yet # change tax number data["contact-tax_number"] = "111111" response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 # this time around, nothing was saved. assert get_company_contact(user) # company contact yet # go back to normal and try to get tax number approved data["contact-tax_number"] = "111110" response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 200 # this time around, nothing was saved. else: client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("shuup:company_edit") response = client.get(company_edit_url) assert response.status_code == 404
def test_credit_card_fail2(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Sem URL para autenticação - 4 parcelas - valor total do parcelado diferente do total do pedido """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class() ) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={"payment_method": payment_method.pk, "shipping_method": shipping_method.pk}) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(1, decimal_to_int_cents(ORDER_TOTAL), CieloProduct.InstallmentCredit, CieloCardBrand.Visa, CC_VISA_4X_INFO['installments'], tid, return_url=None) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: pay c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) json_content = json.loads(response.content.decode("utf-8")) response = c.post(json_content['redirect_url']) # ok, no redirect response = c.get(confirm_path) assert response.status_code == 200 # sabotagem: adiciona um item ao carrinho c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) # again, now with redirect response = c.get(confirm_path) assert response.status_code == 302 assert response.url.endswith(payment_path)
def test_consent_block_snippet_injection(rf): """ Test that the GDPR consent is required to inject xtheme scripts """ shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") # create a GDPR setting for the shop shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.cookie_banner_content = "my cookie banner content" shop_gdpr.cookie_privacy_excerpt = "my cookie privacyexcerpt" shop_gdpr.enabled = True shop_gdpr.save() # configure some snippets to be injected google_snippet = Snippet.objects.create( name="Google Analytics", snippet_type=SnippetType.InlineHTMLMarkup, location="body_end", shop=shop, snippet='<script id="google-script"></script>', ) facebook_snippet = Snippet.objects.create( name="Facebook Pixel", snippet_type=SnippetType.InlineHTMLMarkup, location="body_end", shop=shop, snippet='<script id="facebook-script"></script>', ) # create cookie categories required_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=True, cookies="cookie1,cookir2,_cookie3", name="RequiredCookies", how_is_used="to make the site work", ) google_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, cookies="_google", name="GoogleCookies", how_is_used="to spy users", ) google_cookie_category.block_snippets.add(google_snippet) faceboook_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, cookies="_facebook", name="Facebook", how_is_used="to track users", ) faceboook_cookie_category.block_snippets.add(facebook_snippet) # create privacy policy GDPR document ensure_gdpr_privacy_policy(shop) response = client.get(index_url) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME not in response.cookies # send consent only for the required and google response = client.post( reverse("shuup:gdpr_consent"), data={ "cookie_category_{}".format(required_cookie_category.id): "on", "cookie_category_{}".format(google_cookie_category.id): "on", "cookie_category_{}".format(faceboook_cookie_category.id): "off", }, ) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME in response.cookies cookies_data = json.loads( response.cookies[settings.SHUUP_GDPR_CONSENT_COOKIE_NAME].value) for cookie in required_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] for cookie in google_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] for cookie in faceboook_cookie_category.cookies.split(","): assert cookie not in cookies_data["cookies"] # send the request again, only the google script should be injected response = client.get(index_url) response.render() content = BeautifulStoneSoup(response.content) assert content.find_all("script", attrs={"id": "google-script"}) assert not content.find_all("script", attrs={"id": "facebook-script"})
def test_debit_auto_capture_with_auth(): """ Caso: - Transação com Cartão de Débito - Auto captura HABILITADO - Com URL para autenticação - 1 parcela """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") add_to_basket_resp = c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) assert add_to_basket_resp.status_code < 400 ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() assert isinstance(processor, CieloPaymentProcessor) # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) response = c.post(addresses_path, data=inputs) assert response.status_code == 302, "Address phase should redirect forth" assert response.url.endswith(methods_path) # Phase: Methods assert Order.objects.filter(payment_method=payment_method).count() == 0 response = c.post(methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk }) assert response.status_code == 302, "Methods phase should redirect forth" assert response.url.endswith(confirm_path) response = c.get(confirm_path) assert response.status_code == 302, "Confirm should first redirect forth" assert response.url.endswith(payment_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(1, decimal_to_int_cents(ORDER_TOTAL), CieloProduct.InstallmentCredit, CieloCardBrand.Visa, CC_VISA_4X_INFO['installments'], tid, return_url=None) transacao = get_approved_transaction(transacao) transacao = get_captured_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): with patch.object(CieloRequest, 'capturar', return_value=transacao): # Phase: pay response = c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) assert response.status_code == 200 json_content = json.loads(response.content.decode("utf-8")) assert json_content['redirect_url'].endswith( reverse("shuup:cielo_transaction_return", kwargs={"cielo_order_pk": 1})) cielo_transaction = CieloTransaction.objects.get(tid=tid) assert cielo_transaction.cc_brand == CC_VISA_4X_INFO[ 'cc_brand'] assert cielo_transaction.cc_holder == CC_VISA_4X_INFO[ 'cc_holder'] assert cielo_transaction.installments == CC_VISA_4X_INFO[ 'installments'] assert cielo_transaction.cc_product == CieloProduct.InstallmentCredit assert abs(cielo_transaction.total_value - ORDER_TOTAL) < 0.01 assert cielo_transaction.status.value == transacao.status response = c.post(json_content['redirect_url']) assert response.status_code == 302 assert response.url.endswith(confirm_path) # Phase: Confirm assert Order.objects.count() == 0 confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) assert response.status_code == 302, "Confirm should redirect forth" order = Order.objects.filter( payment_method=payment_method).first() process_payment_path = reverse("shuup:order_process_payment", kwargs={ "pk": order.pk, "key": order.key }) process_payment_return_path = reverse( "shuup:order_process_payment_return", kwargs={ "pk": order.pk, "key": order.key }) order_complete_path = reverse("shuup:order_complete", kwargs={ "pk": order.pk, "key": order.key }) response = c.get(process_payment_path) assert response.status_code == 302, "Payment page should redirect forth" assert response.url.endswith(process_payment_return_path) # Check payment return response = c.get(process_payment_return_path) assert response.status_code == 302, "Payment return should redirect forth" assert response.url.endswith(order_complete_path) cielo_transaction = CieloTransaction.objects.get( order_transaction__order=order, tid=tid) assert cielo_transaction.status == CieloTransactionStatus.Captured assert cielo_transaction.authorization_nsu == str( transacao.autorizacao.nsu) assert cielo_transaction.authorization_lr == str( transacao.autorizacao.lr) assert cielo_transaction.authorization_date == iso8601.parse_date( transacao.autorizacao.data_hora) assert cielo_transaction.authentication_eci == transacao.autenticacao.eci assert cielo_transaction.authentication_date == iso8601.parse_date( transacao.autenticacao.data_hora) assert cielo_transaction.total_captured_value == ORDER_TOTAL assert cielo_transaction.total_reversed_value == Decimal() order.refresh_from_db() assert order.payment_data.get(CIELO_TRANSACTION_ID_KEY) assert order.payment_data.get(CIELO_ORDER_TRANSACTION_ID_KEY) assert order.payment_status == PaymentStatus.NOT_PAID
def test_boleto_cecred_success(): """ Usuário faz a compra e seleciona boleto como forma de pagamento (3 vezes seguidas) Boleto CECRED configurado """ initialize() # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() assert isinstance(processor, BoletoPaymentProcessor) choices = processor.get_service_choices() assert len(choices) == 1 payment_method = processor.create_service( BankService.CECRED.value, identifier="cecred", shop=get_default_shop(), name="boleto cecred", enabled=True, tax_class=get_default_tax_class()) # Configura de acordo behavior_component = payment_method.behavior_components.first() behavior_component.local_pagamento = "a simple test" behavior_component.cedente = "a simple user" behavior_component.prazo_vencimento = 4 behavior_component.instrucoes = ["line1", "line2"] behavior_component.especie_doc = DocumentType.DM behavior_component.layout = 'v06' behavior_component.agencia = '123431' behavior_component.conta = '6427364732' behavior_component.convenio = '123456' behavior_component.carteira = '12' behavior_component.save() for ix in range(3): c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") add_to_basket_resp = c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) assert add_to_basket_resp.status_code < 400 # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) response = c.post(addresses_path, data=inputs) assert response.status_code == 302, "Address phase should redirect forth" assert response.url.endswith(methods_path) # Phase: Methods assert Order.objects.filter(payment_method=payment_method).count() == ix response = c.post( methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk } ) assert response.status_code == 302, "Methods phase should redirect forth" assert response.url.endswith(confirm_path) response = c.get(confirm_path) assert response.status_code == 200 # Phase: Confirm assert Order.objects.count() == ix confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) assert response.status_code == 302, "Confirm should redirect forth" assert Order.objects.count() == ix+1 order = Order.objects.filter(payment_method=payment_method).first() assert order.payment_status == PaymentStatus.NOT_PAID process_payment_path = reverse("shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) process_payment_return_path = reverse("shuup:order_process_payment_return",kwargs={"pk": order.pk, "key": order.key}) order_complete_path = reverse("shuup:order_complete",kwargs={"pk": order.pk, "key": order.key}) assert response.url.endswith(process_payment_path), ("Confirm should have redirected to payment page") response = c.get(process_payment_path) assert response.status_code == 302, "Payment page should redirect forth" assert response.url.endswith(process_payment_return_path) response = c.get(process_payment_return_path) assert response.status_code == 302, "Payment return should redirect forth" assert response.url.endswith(order_complete_path) order.refresh_from_db() assert order.payment_status == PaymentStatus.NOT_PAID from python_boleto.cecred import CecredBoleto bcecred = CecredBoleto(**order.boleto.info) bcecred.validate() assert len(order.boleto.html) > 0 # "visualiza o boleto" view_boleto_path = reverse("shuup:view_boleto", kwargs={"order_pk": order.pk, "order_key": order.key}) response = c.get(view_boleto_path) assert HttpResponse(order.boleto.html).content == response.content
def test_credit_card_fail(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Sem URL para autenticação - 4 parcelas - dados do pagamento nao existem """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk }) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(1, decimal_to_int_cents(ORDER_TOTAL), CieloProduct.InstallmentCredit, CieloCardBrand.Visa, CC_VISA_4X_INFO['installments'], tid, return_url=None) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: pay c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) json_content = json.loads(response.content.decode("utf-8")) response = c.post(json_content['redirect_url']) confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() process_payment_path = reverse("shuup:order_process_payment", kwargs={ "pk": order.pk, "key": order.key }) # FORCE CLEAR ORDER PAYMENT DATA order.payment_data = {} order.save() response = c.get(process_payment_path) order.refresh_from_db() assert order.status == OrderStatus.objects.get_default_canceled()
def test_credit_card_success_3(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Sem URL para autenticação - 4 parcelas com juros """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.installments_without_interest = 1 cielo_config.interest_rate = Decimal(3.20) cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path,data={"payment_method": payment_method.pk,"shipping_method": shipping_method.pk}) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(numero=1, valor=decimal_to_int_cents(ORDER_TOTAL), produto=CieloProduct.Credit, bandeira=CieloCardBrand.Visa, parcelas=CC_VISA_1X_INFO['installments'], tid=tid, return_url=None) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: pay c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) assert response.status_code == 200 json_content = json.loads(response.content.decode("utf-8")) assert json_content['redirect_url'].endswith(reverse("shuup:cielo_transaction_return", kwargs={"cielo_order_pk": 1})) choices = InstallmentContext(ORDER_TOTAL, cielo_config).get_intallments_choices() cielo_transaction = CieloTransaction.objects.get(tid=tid) assert cielo_transaction.cc_product == CieloProduct.InstallmentCredit assert abs(cielo_transaction.total_value - choices[3][2]) <= Decimal(0.01) assert cielo_transaction.status.value == transacao.status response = c.post(json_content['redirect_url']) confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() assert abs(order.taxful_total_price.value - choices[3][2]) <= Decimal(0.01) process_payment_path = reverse("shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) process_payment_return_path = reverse("shuup:order_process_payment_return",kwargs={"pk": order.pk, "key": order.key}) response = c.get(process_payment_path) response = c.get(process_payment_return_path) cielo_transaction = CieloTransaction.objects.get(order_transaction__order=order, tid=tid) order.refresh_from_db() assert order.payment_data.get(CIELO_TRANSACTION_ID_KEY) assert order.payment_data.get(CIELO_ORDER_TRANSACTION_ID_KEY) assert order.payment_status == PaymentStatus.NOT_PAID
def test_consent_cookies(rf): """ Test that the GDPR consent is generated and saved into a cooki """ for code, lang in settings.LANGUAGES: activate(code) shop = factories.get_default_shop() client = SmartClient() index_url = reverse("shuup:index") response = client.get(index_url) # create a GDPR setting for the shop shop_gdpr = GDPRSettings.get_for_shop(shop) shop_gdpr.cookie_banner_content = "my cookie banner content" shop_gdpr.cookie_privacy_excerpt = "my cookie privacyexcerpt" shop_gdpr.enabled = True shop_gdpr.save() # create cookie categories required_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=True, cookies="cookie1,cookir2,_cookie3", name="RequiredCookies", how_is_used="to make the site work") optional_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, cookies="_opt1,_opt2,_opt3", name="OptionalCookies", how_is_used="to spy users") default_active_cookie_category = GDPRCookieCategory.objects.create( shop=shop, always_active=False, default_active=True, cookies="_analytics", name="Analytics", how_is_used="to track users") # create privacy policy GDPR document privacy_policy = ensure_gdpr_privacy_policy(shop) response = client.get(index_url) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME not in response.cookies # send consent response = client.post( reverse("shuup:gdpr_consent"), data={ "cookie_category_{}".format(required_cookie_category.id): "on", "cookie_category_{}".format(optional_cookie_category.id): "on", "cookie_category_{}".format(default_active_cookie_category.id): "on", }) assert settings.SHUUP_GDPR_CONSENT_COOKIE_NAME in response.cookies cookies_data = json.loads( response.cookies[settings.SHUUP_GDPR_CONSENT_COOKIE_NAME].value) assert privacy_policy.id == cookies_data["documents"][0]["id"] assert privacy_policy.url == cookies_data["documents"][0]["url"] for cookie in required_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] for cookie in optional_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] for cookie in default_active_cookie_category.cookies.split(","): assert cookie in cookies_data["cookies"] engine = django.template.engines['jinja2'] template = engine.from_string("{{ gdpr.get_accepted_cookies()|json }}") request = rf.get("/") context = {'request': request} rendered_cookies = json.loads(template.render(context)) assert rendered_cookies == [] request.COOKIES = { settings.SHUUP_GDPR_CONSENT_COOKIE_NAME: (response.client.cookies[ settings.SHUUP_GDPR_CONSENT_COOKIE_NAME].value) } context = {'request': request} rendered_cookies = set(json.loads(template.render(context))) assert rendered_cookies == set([ '_opt2', 'cookie1', '_cookie3', '_opt3', '_analytics', 'cookir2', '_opt1' ])
def test_credit_card_fail(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Sem URL para autenticação - 4 parcelas - dados do pagamento nao existem """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class() ) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={"payment_method": payment_method.pk, "shipping_method": shipping_method.pk}) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(1, decimal_to_int_cents(ORDER_TOTAL), CieloProduct.InstallmentCredit, CieloCardBrand.Visa, CC_VISA_4X_INFO['installments'], tid, return_url=None) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: pay c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) json_content = json.loads(response.content.decode("utf-8")) response = c.post(json_content['redirect_url']) confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() process_payment_path = reverse("shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) # FORCE CLEAR ORDER PAYMENT DATA order.payment_data = {} order.save() response = c.get(process_payment_path) order.refresh_from_db() assert order.status == OrderStatus.objects.get_default_canceled()
def create_success_order_with_boleto(): # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() assert isinstance(processor, BoletoPaymentProcessor) choices = processor.get_service_choices() assert len(choices) == 1 payment_method = processor.create_service( BankService.CECRED.value, identifier="cecred", shop=get_default_shop(), name="boleto cecred", enabled=True, tax_class=get_default_tax_class()) # Configura de acordo behavior_component = payment_method.behavior_components.first() behavior_component.local_pagamento = "a simple test" behavior_component.cedente = "a simple user" behavior_component.prazo_vencimento = 4 behavior_component.instrucoes = ["line1", "line2"] behavior_component.especie_doc = DocumentType.DM behavior_component.layout = 'v06' behavior_component.agencia = '123431' behavior_component.conta = '6427364732' behavior_component.convenio = '123456' behavior_component.carteira = '12' behavior_component.save() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk }) c.get(confirm_path) confirm_soup = c.soup(confirm_path) c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() process_payment_path = reverse("shuup:order_process_payment", kwargs={ "pk": order.pk, "key": order.key }) process_payment_return_path = reverse("shuup:order_process_payment_return", kwargs={ "pk": order.pk, "key": order.key }) order_complete_path = reverse("shuup:order_complete", kwargs={ "pk": order.pk, "key": order.key }) c.get(process_payment_path) c.get(process_payment_return_path) c.get(order_complete_path) order.refresh_from_db() return order
def test_credit_card_fail2(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Sem URL para autenticação - 4 parcelas - valor total do parcelado diferente do total do pedido """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) ORDER_TOTAL = PRODUCT_PRICE * 10 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() # aumenta o limite máximo de parcelas para 4 cielo_config = get_cielo_config() cielo_config.max_installments = 4 cielo_config.save() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) transaction_path = reverse("shuup:cielo_make_transaction") confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk }) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(1, decimal_to_int_cents(ORDER_TOTAL), CieloProduct.InstallmentCredit, CieloCardBrand.Visa, CC_VISA_4X_INFO['installments'], tid, return_url=None) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: pay c.soup(payment_path) response = c.post(transaction_path, CC_VISA_4X_INFO) json_content = json.loads(response.content.decode("utf-8")) response = c.post(json_content['redirect_url']) # ok, no redirect response = c.get(confirm_path) assert response.status_code == 200 # sabotagem: adiciona um item ao carrinho c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 10, "supplier": get_default_supplier().pk }) # again, now with redirect response = c.get(confirm_path) assert response.status_code == 302 assert response.url.endswith(payment_path)
def test_checkout(admin_user): get_default_shop() set_current_theme('shuup.themes.classic_gray') create_default_order_statuses() populate_if_required() create_test_data() default_product = get_default_product() sp = ShopProduct.objects.get(product=default_product, shop=get_default_shop()) sp.default_price = get_default_shop().create_price(Decimal(10.0)) sp.save() service = get_custom_carrier_service() component = SpecificShippingTableBehaviorComponent.objects.create( table=ShippingTable.objects.get(identifier='table-1') ) service.behavior_components.add(component) c = SmartClient() basket_path = reverse("shuup:basket") add_to_basket_resp = c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) assert add_to_basket_resp.status_code < 400 shipping_method = service payment_method = get_payment_method(name="neat", price=4) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) inputs['shipping-postal_code'] = "89060201" inputs['shipping-country'] = "BR" response = c.post(addresses_path, data=inputs) assert response.status_code == 302, "Address phase should redirect forth" assert response.url.endswith(methods_path) # Phase: Methods assert Order.objects.filter(payment_method=payment_method).count() == 0 response = c.post( methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk } ) assert response.status_code == 302, "Methods phase should redirect forth" assert response.url.endswith(confirm_path) response = c.get(confirm_path) assert response.status_code == 200 # Phase: Confirm assert Order.objects.count() == 0 confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) assert response.status_code == 302, "Confirm should redirect forth" assert Order.objects.count() == 1 order = Order.objects.filter(payment_method=payment_method).first() assert order.payment_status == PaymentStatus.NOT_PAID
def test_boleto_cecred_error2(): """ Usuário faz a compra e seleciona boleto como forma de pagamento Boleto CECRED configurado incorretamente Pedido finalizado com sucesso, boleto NÃO é gerado """ initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") add_to_basket_resp = c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) assert add_to_basket_resp.status_code < 400 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() assert isinstance(processor, BoletoPaymentProcessor) payment_method = processor.create_service( BankService.CECRED.value, identifier="cecred", shop=get_default_shop(), name="boleto cecred", enabled=True, tax_class=get_default_tax_class()) # Configura de acordo behavior_component = payment_method.behavior_components.first() behavior_component.local_pagamento = "a simple test" behavior_component.cedente = "a simple user" behavior_component.prazo_vencimento = 4 behavior_component.instrucoes = ["line1", "line2"] behavior_component.especie_doc = DocumentType.DM behavior_component.layout = 'v06' behavior_component.agencia = '123431' behavior_component.conta = '6427364732' behavior_component.convenio = '32312' behavior_component.carteira = '12' behavior_component.save() # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) response = c.post(addresses_path, data=inputs) assert response.status_code == 302, "Address phase should redirect forth" assert response.url.endswith(methods_path) # Phase: Methods assert Order.objects.filter(payment_method=payment_method).count() == 0 response = c.post( methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk } ) assert response.status_code == 302, "Methods phase should redirect forth" assert response.url.endswith(confirm_path) response = c.get(confirm_path) assert response.status_code == 200 # quando vai gerar boleto estoura uma exceção with patch.object(CecredBoletoBehaviorComponent, 'generate_boleto') as mocked: mocked.side_effect = NotImplementedError() # Phase: Confirm assert Order.objects.count() == 0 confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) assert response.status_code == 302, "Confirm should redirect forth" assert Order.objects.count() == 1 order = Order.objects.filter(payment_method=payment_method).first() assert order.payment_status == PaymentStatus.NOT_PAID process_payment_path = reverse("shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) process_payment_return_path = reverse("shuup:order_process_payment_return",kwargs={"pk": order.pk, "key": order.key}) order_complete_path = reverse("shuup:order_complete",kwargs={"pk": order.pk, "key": order.key}) assert response.url.endswith(process_payment_path), ("Confirm should have redirected to payment page") response = c.get(process_payment_path) assert response.status_code == 302, "Payment page should redirect forth" assert response.url.endswith(process_payment_return_path) response = c.get(process_payment_return_path) assert response.status_code == 302, "Payment return should redirect forth" assert response.url.endswith(order_complete_path) order.refresh_from_db() assert order.payment_status == PaymentStatus.NOT_PAID # BOLETO NÃO EXISTE assert not hasattr(order, 'boleto') assert not StoredBoleto.objects.filter(order=order).exists()
def test_company_tax_number_limitations(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) if allow_company_registration: client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("shuup:company_edit") soup = client.soup(company_edit_url) data = default_company_data() data.update(default_address_data("billing")) data.update(default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 assert get_company_contact(regular_user) # re-save should work properly response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 client.logout() # another company tries to use same tax number new_user_password = "******" new_user_username = "******" user = User.objects.create_user(new_user_username, "*****@*****.**", new_user_password) person = get_person_contact(user=user) assert not get_company_contact(user) client = SmartClient() client.login(username=new_user_username, password=new_user_password) company_edit_url = reverse("shuup:company_edit") soup = client.soup(company_edit_url) data = default_company_data() data.update(default_address_data("billing")) data.update(default_address_data("shipping")) response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 200 # this time around, nothing was saved. assert not get_company_contact(user) # company contact yet # change tax number data["contact-tax_number"] = "111111" response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 302 # this time around, nothing was saved. assert get_company_contact(user) # company contact yet # go back to normal and try to get tax number approved data["contact-tax_number"] = "111110" response, soup = client.response_and_soup(company_edit_url, data, "post") assert response.status_code == 200 # this time around, nothing was saved. else: client = SmartClient() client.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD) company_edit_url = reverse("shuup:company_edit") response = client.get(company_edit_url) assert reverse("shuup:customer_edit") in response.url
def test_order_flow_with_phases(get_shipping_method, shipping_data, get_payment_method, payment_data): create_default_order_statuses() populate_if_required() c = SmartClient() _populate_client_basket(c) # Create methods shipping_method = get_shipping_method() payment_method = get_payment_method() # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) shipping_path = reverse("shuup:checkout", kwargs={"phase": "shipping"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) response = c.post(addresses_path, data=inputs) assert response.status_code == 302, "Address phase should redirect forth to methods" # Phase: Methods response = c.get(methods_path) assert response.status_code == 200 response = c.post( methods_path, data={ "shipping_method": shipping_method.pk, "payment_method": payment_method.pk } ) assert response.status_code == 302, "Methods phase should redirect forth" if isinstance(shipping_method.carrier, CarrierWithCheckoutPhase): # Phase: Shipping response = c.get(shipping_path) assert response.status_code == 200 response = c.post(shipping_path, data=shipping_data) assert response.status_code == 302, "Payments phase should redirect forth" if isinstance(payment_method.payment_processor, PaymentWithCheckoutPhase): # Phase: payment response = c.get(payment_path) assert response.status_code == 200 response = c.post(payment_path, data=payment_data) assert response.status_code == 302, "Payments phase should redirect forth" # Phase: Confirm assert Order.objects.count() == 0 confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) assert response.status_code == 302, "Confirm should redirect forth" order = Order.objects.first() if isinstance(shipping_method.carrier, CarrierWithCheckoutPhase): assert order.shipping_data.get("input_value") == "20540" if isinstance(payment_method.payment_processor, PaymentWithCheckoutPhase): assert order.payment_data.get("input_value") assert order.payment_status == PaymentStatus.NOT_PAID # Resolve order specific paths (payment and complete) process_payment_path = reverse( "shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) process_payment_return_path = reverse( "shuup:order_process_payment_return", kwargs={"pk": order.pk, "key": order.key}) order_complete_path = reverse( "shuup:order_complete", kwargs={"pk": order.pk, "key": order.key}) # Check confirm redirection to payment page assert response.url.endswith(process_payment_path), ( "Confirm should have redirected to payment page") # Visit payment page response = c.get(process_payment_path) assert response.status_code == 302, "Payment page should redirect forth" assert response.url.endswith(process_payment_return_path) # Check payment return response = c.get(process_payment_return_path) assert response.status_code == 302, "Payment return should redirect forth" assert response.url.endswith(order_complete_path) # Check payment status has changed to DEFERRED order = Order.objects.get(pk=order.pk) # reload assert order.payment_status == PaymentStatus.DEFERRED
def test_order_flow_with_payment_phase_credit_card_success(): """ Caso: - Transação com Cartão de Crédito - Auto captura desabilidato - Com URL para autenticação - 1 parcela sem juros """ initialize() c = SmartClient() default_product = get_default_product() ORDER_TOTAL = PRODUCT_PRICE * 1 basket_path = reverse("shuup:basket") add_to_basket_resp = c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) assert add_to_basket_resp.status_code < 400 # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() assert isinstance(processor, CieloPaymentProcessor) payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) transaction_path = reverse("shuup:cielo_make_transaction") # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) response = c.post(addresses_path, data=inputs) assert response.status_code == 302, "Address phase should redirect forth" assert response.url.endswith(methods_path) # Phase: Methods assert Order.objects.filter(payment_method=payment_method).count() == 0 response = c.post( methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk } ) assert response.status_code == 302, "Methods phase should redirect forth" assert response.url.endswith(confirm_path) response = c.get(confirm_path) assert response.status_code == 302, "Confirm should first redirect forth" assert response.url.endswith(payment_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(numero=1, valor=decimal_to_int_cents(ORDER_TOTAL), produto=CieloProduct.Credit, bandeira=CieloCardBrand.Visa, parcelas=CC_VISA_1X_INFO['installments'], tid=tid) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: Payment response = c.soup(payment_path) response = c.post(transaction_path, CC_VISA_1X_INFO) assert response.status_code == 200 json_content = json.loads(response.content.decode("utf-8")) assert json_content['redirect_url'] == AUTH_URL cielo_transaction = CieloTransaction.objects.get(tid=tid) assert cielo_transaction.status == CieloTransactionStatus.InProgress assert cielo_transaction.cc_brand == CC_VISA_1X_INFO['cc_brand'] assert cielo_transaction.cc_holder == CC_VISA_1X_INFO['cc_holder'] assert cielo_transaction.installments == CC_VISA_1X_INFO['installments'] assert cielo_transaction.cc_product == CieloProduct.Credit assert abs(cielo_transaction.total_value - ORDER_TOTAL) < 0.01 assert cielo_transaction.status.value == transacao.status transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'consultar', return_value=transacao): # Phase: Confirm Order assert Order.objects.count() == 0 confirm_soup = c.soup(confirm_path) response = c.post(confirm_path, data=extract_form_fields(confirm_soup)) assert response.status_code == 302, "Confirm should redirect forth" assert Order.objects.count() == 1 order = Order.objects.filter(payment_method=payment_method).first() process_payment_path = reverse("shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) process_payment_return_path = reverse("shuup:order_process_payment_return",kwargs={"pk": order.pk, "key": order.key}) order_complete_path = reverse("shuup:order_complete",kwargs={"pk": order.pk, "key": order.key}) # Visit payment page response = c.get(process_payment_path) assert response.status_code == 302, "Payment page should redirect forth" assert response.url.endswith(process_payment_return_path) # Check payment return response = c.get(process_payment_return_path) assert response.status_code == 302, "Payment return should redirect forth" assert response.url.endswith(order_complete_path) cielo_transaction = CieloTransaction.objects.get(order_transaction__order=order, tid=tid) assert cielo_transaction.status == CieloTransactionStatus.Authorized assert cielo_transaction.authorization_nsu == str(transacao.autorizacao.nsu) assert cielo_transaction.authorization_lr == str(transacao.autorizacao.lr) assert cielo_transaction.authorization_date == iso8601.parse_date(transacao.autorizacao.data_hora) assert cielo_transaction.authentication_eci == transacao.autenticacao.eci assert cielo_transaction.authentication_date == iso8601.parse_date(transacao.autenticacao.data_hora) assert cielo_transaction.total_captured.value == Decimal() assert cielo_transaction.total_reversed.value == Decimal() order.refresh_from_db() assert order.payment_data.get(CIELO_TRANSACTION_ID_KEY) assert order.payment_data.get(CIELO_ORDER_TRANSACTION_ID_KEY) assert order.payment_status == PaymentStatus.NOT_PAID
def test_admin(rf, admin_user): initialize() c = SmartClient() default_product = get_default_product() basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) shipping_method = get_default_shipping_method() processor = get_payment_provider() payment_method = processor.create_service( PagSeguroPaymentMethod.ONLINE_DEBIT.value, identifier="pagseguro_debit", shop=get_default_shop(), name="debit", enabled=True, tax_class=get_default_tax_class()) service_choices = processor.get_service_choices() assert len(service_choices) == 2 assert service_choices[0].identifier == PagSeguroPaymentMethod.BOLETO.value assert service_choices[ 1].identifier == PagSeguroPaymentMethod.ONLINE_DEBIT.value addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post(methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk }) c.get(confirm_path) c.soup(payment_path) c.post( payment_path, { "paymentMethod": PagSeguroPaymentMethodIdentifier.Debito, "bankOption": "{0}".format(PagSeguroPaymentMethodCode.DebitoOnlineBB.value), "senderHash": "J7E98Y37WEIRUHDIAI9U8RYE7UQE" }) confirm_soup = c.soup(confirm_path) c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() payment = PagSeguroPayment.objects.create(order=order, code="u3928uhu8y9i3") PagSeguroOrderSection() PagSeguroOrderSection.get_context_data(order) assert PagSeguroOrderSection.visible_for_object(order) is True view = load("shuup_pagseguro.admin.views.PaymentRefreshView").as_view() request = apply_request_middleware(rf.post("/"), user=admin_user) response = view(request) assert response.status_code == 400 request = apply_request_middleware(rf.post("/", {"pk": payment.pk}), user=admin_user) response = view(request) assert response.status_code == 200 # somente visita view = load("shuup_pagseguro.admin.views.config.ConfigListView").as_view() request = apply_request_middleware(rf.get("/"), user=admin_user) response = view(request) assert response.status_code == 200 view = load("shuup_pagseguro.admin.views.DashboardView").as_view() request = apply_request_middleware(rf.get("/"), user=admin_user) response = view(request) assert response.status_code == 200
def test_refresh_transaction_view(rf, admin_user): initialize() c = SmartClient() default_product = get_default_product() ORDER_TOTAL = PRODUCT_PRICE * 1 basket_path = reverse("shuup:basket") c.post(basket_path, data={ "command": "add", "product_id": default_product.pk, "quantity": 1, "supplier": get_default_supplier().pk }) # Create methods shipping_method = get_default_shipping_method() processor = get_payment_provider() payment_method = processor.create_service( CIELO_SERVICE_CREDIT, identifier="cielo_phase_cc", shop=get_default_shop(), name="credit card", enabled=True, tax_class=get_default_tax_class()) # Resolve paths addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"}) methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"}) payment_path = reverse("shuup:checkout", kwargs={"phase": "payment"}) confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"}) transaction_path = reverse("shuup:cielo_make_transaction") # Phase: Addresses addresses_soup = c.soup(addresses_path) inputs = fill_address_inputs(addresses_soup, with_company=False) c.post(addresses_path, data=inputs) c.post( methods_path, data={ "payment_method": payment_method.pk, "shipping_method": shipping_method.pk } ) c.get(confirm_path) tid = uuid.uuid4().hex transacao = get_in_progress_transaction(numero=1, valor=decimal_to_int_cents(ORDER_TOTAL), produto=CieloProduct.Credit, bandeira=CieloCardBrand.Visa, parcelas=CC_VISA_1X_INFO['installments'], tid=tid) transacao = get_approved_transaction(transacao) with patch.object(CieloRequest, 'autorizar', return_value=transacao): with patch.object(CieloRequest, 'consultar', return_value=transacao): c.soup(payment_path) c.post(transaction_path, CC_VISA_1X_INFO) confirm_soup = c.soup(confirm_path) c.post(confirm_path, data=extract_form_fields(confirm_soup)) order = Order.objects.filter(payment_method=payment_method).first() process_payment_path = reverse("shuup:order_process_payment", kwargs={"pk": order.pk, "key": order.key}) process_payment_return_path = reverse("shuup:order_process_payment_return",kwargs={"pk": order.pk, "key": order.key}) c.get(process_payment_path) c.get(process_payment_return_path) order.refresh_from_db() cielo_transaction = CieloTransaction.objects.get(order_transaction__order=order) # transacao nao capturada assert cielo_transaction.tid == tid assert cielo_transaction.total_captured.value == Decimal() view = load("shuup_cielo.admin.views.RefreshTransactionView").as_view() request = apply_request_middleware(rf.post("/"), user=admin_user) # request sem parametro - bad request response = view(request) assert response.status_code == 500 transacao = get_captured_transaction(transacao) with patch.object(CieloRequest, 'consultar', return_value=transacao): request = apply_request_middleware(rf.post("/", {"id":cielo_transaction.pk}), user=admin_user) response = view(request) assert response.status_code == 200 cielo_transaction.refresh_from_db() assert cielo_transaction.total_captured_value == order.taxful_total_price_value