Пример #1
0
def test_basic_order_flow(with_company):
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    c = SmartClient()
    product_ids = _populate_client_basket(c)

    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_soup = c.soup(addresses_path)
    inputs = fill_address_inputs(addresses_soup, with_company=with_company)
    response = c.post(addresses_path, data=inputs)
    assert response.status_code == 302  # Should redirect forth

    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = c.soup(methods_path)
    assert c.post(methods_path, data=extract_form_fields(methods_soup)).status_code == 302  # Should redirect forth

    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = c.soup(confirm_path)
    Product.objects.get(pk=product_ids[0]).soft_delete()
    assert c.post(confirm_path, data=extract_form_fields(confirm_soup)).status_code == 200  # user needs to reconfirm
    data = extract_form_fields(confirm_soup)
    data['product_ids'] = ','.join(product_ids[1:])
    assert c.post(confirm_path, data=data).status_code == 302  # Should redirect forth

    n_orders_post = Order.objects.count()
    assert n_orders_post > n_orders_pre, "order was created"
Пример #2
0
def _complete_checkout(client, expected_order_count):
    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_soup = client.soup(addresses_path)
    inputs = _fill_address_inputs(addresses_soup, with_company=False)
    response = client.post(addresses_path, data=inputs)
    assert response.status_code == 302  # Should redirect forth

    # Make sure the address is initialized from storage
    # Go back to addresses right before back to methods
    client.soup(addresses_path)

    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = client.soup(methods_path)
    assert client.post(methods_path, data=extract_form_fields(
        methods_soup)).status_code == 302  # Should redirect forth

    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = client.soup(confirm_path)
    data = extract_form_fields(confirm_soup)
    assert client.post(confirm_path,
                       data=data).status_code == 302  # Should redirect forth

    n_orders_post = Order.objects.count()
    assert n_orders_post == expected_order_count, "order was created"
    return Order.objects.order_by("-id").first()
Пример #3
0
def test_basic_order_flow_registered(regular_user):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    get_test_script("test script", "order_received")
    # 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"})

    template_data = STEP_DATA[0]["actions"][0]["template_data"]

    LANG_CODE = {"en": "US", "fi": "FI"}

    for lang in ["en", "fi"]:
        n_outbox_pre = len(mail.outbox)
        contact = get_person_contact(regular_user)
        contact.language = lang
        contact.save()

        c = SmartClient()
        c.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD)

        product_ids = _populate_client_basket(c)

        addresses_soup = c.soup(addresses_path)
        address = get_address(country=LANG_CODE[lang])

        inputs = fill_address_inputs(addresses_soup, address)
        response = c.post(addresses_path, data=inputs)
        assert response.status_code == 302  # Should redirect forth

        methods_soup = c.soup(methods_path)
        assert c.post(methods_path, data=extract_form_fields(
            methods_soup)).status_code == 302  # Should redirect forth

        confirm_soup = c.soup(confirm_path)
        Product.objects.get(pk=product_ids[0]).soft_delete()
        assert (
            c.post(confirm_path,
                   data=extract_form_fields(confirm_soup)).status_code == 200
        )  # user needs to reconfirm
        data = extract_form_fields(confirm_soup)
        data["accept_terms"] = True
        data["product_ids"] = ",".join(product_ids[1:])
        assert c.post(confirm_path,
                      data=data).status_code == 302  # Should redirect forth

        n_orders_post = Order.objects.count()
        assert n_orders_post > n_orders_pre, "order was created"
        assert len(mail.outbox) == n_outbox_pre + 1, "Sending email failed"
        latest_mail = mail.outbox[-1]

        # mail is always sent in fallback language since user is not registered
        assert latest_mail.subject == template_data[lang][
            "subject"], "Subject doesn't match"
        assert latest_mail.body == template_data[lang][
            "body"], "Body doesn't match"
Пример #4
0
def test_basic_order_flow_registered(regular_user):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    get_test_script("test script", "order_received")
    # 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"})

    template_data = STEP_DATA[0]["actions"][0]["template_data"]

    LANG_CODE = {
        "en": "US",
        "fi": "FI"
    }

    for lang in ["en", "fi"]:
        n_outbox_pre = len(mail.outbox)
        contact = get_person_contact(regular_user)
        contact.language = lang
        contact.save()

        c = SmartClient()
        c.login(username=REGULAR_USER_USERNAME, password=REGULAR_USER_PASSWORD)

        product_ids = _populate_client_basket(c)

        addresses_soup = c.soup(addresses_path)
        address = get_address(country=LANG_CODE[lang])

        inputs = fill_address_inputs(addresses_soup, address)
        response = c.post(addresses_path, data=inputs)
        assert response.status_code == 302  # Should redirect forth

        methods_soup = c.soup(methods_path)
        assert c.post(methods_path, data=extract_form_fields(methods_soup)).status_code == 302  # Should redirect forth

        confirm_soup = c.soup(confirm_path)
        Product.objects.get(pk=product_ids[0]).soft_delete()
        assert c.post(confirm_path, data=extract_form_fields(confirm_soup)).status_code == 200  # user needs to reconfirm
        data = extract_form_fields(confirm_soup)
        data['product_ids'] = ','.join(product_ids[1:])
        assert c.post(confirm_path, data=data).status_code == 302  # Should redirect forth

        n_orders_post = Order.objects.count()
        assert n_orders_post > n_orders_pre, "order was created"
        assert (len(mail.outbox) == n_outbox_pre + 1), "Sending email failed"
        latest_mail = mail.outbox[-1]

        # mail is always sent in fallback language since user is not registered
        assert latest_mail.subject == template_data[lang]["subject"], "Subject doesn't match"
        assert latest_mail.body == template_data[lang]["body"], "Body doesn't match"
Пример #5
0
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
Пример #6
0
def _fill_address_inputs(soup, with_company=False):
    inputs = {}
    test_address = factories.get_address()
    for key, value in extract_form_fields(soup.find('form',
                                                    id='addresses')).items():
        if not value:
            if key in ("order-tax_number", "order-company_name"):
                continue
            if key.startswith("shipping-") or key.startswith("billing-"):
                bit = key.split("-")[1]
                value = getattr(test_address, bit, None)
            if not value and "email" in key:
                value = "*****@*****.**" % random.random()
            if not value:
                value = "test"
        inputs[key] = value

    if with_company:
        inputs["company-tax_number"] = "FI1234567-1"
        inputs["company-company_name"] = "Example Oy"
    else:
        inputs = dict((k, v) for (k, v) in inputs.items()
                      if not k.startswith("company-"))

    return inputs
Пример #7
0
def test_admin_edit(rf, admin_user):
    shop = get_default_shop()

    group = get_default_customer_group(shop)
    cgpd = ContactGroupPriceDisplay.objects.for_group_and_shop(group, shop)
    view = ContactGroupPriceDisplayEditView.as_view()


    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices

    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=cgpd.pk)
    response.render()
    content = force_text(response.content)

    data = extract_form_fields(BeautifulSoup(content))

    data.update({
        "price_display_mode": [PriceDisplayChoices.HIDE.value],
        "group": group.id,
    })

    request = apply_request_middleware(rf.post("/", data), user=admin_user, shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful

    group = get_default_customer_group(shop)

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is False
    assert options.include_taxes is None

    # none, with_taxes, without_taxes, hide
    k = "price_display_mode"
    data.update({k: [PriceDisplayChoices.NONE.value]})
    request = apply_request_middleware(rf.post("/", data), user=admin_user, shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is True  # default
    assert options.include_taxes is None

    data.update({k: [PriceDisplayChoices.WITH_TAXES.value]})
    request = apply_request_middleware(rf.post("/", data), user=admin_user, shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful
    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is True  # default
    assert options.include_taxes is True

    data.update({k: [PriceDisplayChoices.WITHOUT_TAXES.value]})
    request = apply_request_middleware(rf.post("/", data), user=admin_user, shop=shop)
    response = view(request, pk=cgpd.pk)
    assert response.status_code == 302  # save successful

    options = get_price_display_options_for_group_and_shop(group, shop)
    assert options.show_prices is True
    assert options.include_taxes is False
Пример #8
0
def test_user_detail_contact_seed(rf):
    get_default_shop()
    contact = create_random_person()

    # Using random data for name and email would need escaping when
    # checking if it is rendered, therefore use something very basic instead
    contact.name = "Matti Perustyyppi"
    contact.email = "*****@*****.**"
    contact.save()

    view_func = UserDetailView.as_view()
    # Check that fields populate . . .
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}))
    response = view_func(request)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
    # POST the password too to create the user . . .
    post = extract_form_fields(BeautifulSoup(content))
    post["password"] = "******"
    request.method = "POST"
    request.POST = post
    response = view_func(request)
    assert response.status_code < 500
    # Check this new user is visible in the details now
    user = Contact.objects.get(pk=contact.pk).user
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}))
    response = view_func(request, pk=user.pk)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
Пример #9
0
def test_iframe_mode(rf, admin_user, extra_query_param, extra_query_value,
                     expected_script):
    get_default_shop()
    view = load(
        "shuup.admin.modules.categories.views:CategoryEditView").as_view()

    request = apply_request_middleware(rf.get("/", {"mode": "iframe"}),
                                       user=admin_user)
    response = view(request)
    if hasattr(response, "render"):
        response.render()
    assert 200 <= response.status_code < 300

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content, "lxml"))
    post.update({"base-name__en": "Name"})
    post.pop("base-image")

    # save iframe mode
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    request.GET = request.GET.copy()
    request.GET["mode"] = "iframe"

    if extra_query_param:
        request.GET[extra_query_param] = extra_query_value

    response = view(request)
    assert response.status_code == 302

    client = Client()
    client.login(username="******", password="******")

    response = client.get(response.url)
    assert response.status_code == 200
    assert expected_script in force_text(response.content)
Пример #10
0
def test_iframe_mode(rf, admin_user, extra_query_param, extra_query_value, expected_script):
    get_default_shop()
    view = load("shuup.admin.modules.categories.views:CategoryEditView").as_view()

    request = apply_request_middleware(rf.get("/", {"mode": "iframe"}), user=admin_user)
    response = view(request)
    if hasattr(response, "render"):
        response.render()
    assert 200 <= response.status_code < 300

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content, "lxml"))
    post.update({
        "base-name__en": "Name"
    })
    post.pop("base-image")

    # save iframe mode
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    request.GET = request.GET.copy()
    request.GET["mode"] = "iframe"

    if extra_query_param:
        request.GET[extra_query_param] = extra_query_value

    response = view(request)
    assert response.status_code == 302

    client = Client()
    client.login(username="******", password="******")

    response = client.get(response.url)
    assert response.status_code == 200
    assert expected_script in force_text(response.content)
Пример #11
0
def test_user_detail_contact_seed(rf, admin_user):
    get_default_shop()
    contact = create_random_person()

    # Using random data for name and email would need escaping when
    # checking if it is rendered, therefore use something very basic instead
    contact.name = "Matti Perustyyppi"
    contact.email = "*****@*****.**"
    contact.save()

    view_func = UserDetailView.as_view()
    # Check that fields populate . . .
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}), user=admin_user)
    response = view_func(request)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
    # POST the password too to create the user . . .
    post = extract_form_fields(BeautifulSoup(content))
    post["password"] = "******"
    request.method = "POST"
    request.POST = post
    response = view_func(request)
    assert response.status_code < 500
    # Check this new user is visible in the details now
    user = Contact.objects.get(pk=contact.pk).user
    request = apply_request_middleware(rf.get("/", {"contact_id": contact.pk}), user=admin_user)
    response = view_func(request, pk=user.pk)
    response.render()
    content = force_text(response.content)
    assert force_text(contact.first_name) in content
    assert force_text(contact.last_name) in content
    assert force_text(contact.email) in content
Пример #12
0
def _populate_client_basket(client):
    product_ids = []
    index = client.soup("/")
    product_links = index.find_all("a", rel="product-detail")
    assert product_links
    for i in range(3):  # add three different products
        product_detail_path = product_links[i]["href"]
        assert product_detail_path
        product_detail_soup = client.soup(product_detail_path)
        inputs = extract_form_fields(product_detail_soup)
        basket_path = reverse("shuup:basket")
        add_to_basket_resp = client.post(basket_path,
                                         data={
                                             "command": "add",
                                             "product_id":
                                             inputs["product_id"],
                                             "quantity": 1,
                                             "supplier":
                                             get_default_supplier().pk
                                         })
        assert add_to_basket_resp.status_code < 400
        product_ids.append(inputs["product_id"])
    basket_soup = client.soup(basket_path)
    assert b'no such element' not in basket_soup.renderContents(
    ), 'All product details are not rendered correctly'
    return product_ids
Пример #13
0
def test_edit_view_adding_messages_to_form_group(rf, admin_user):
    get_default_shop()  # obvious prerequisite
    product = get_default_product()
    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=product.pk)
    response.render()
    assert 200 <= response.status_code < 300

    assert ProductEditView.add_form_errors_as_messages

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content))
    post_data = {
        # Error in the base form part
        "base-name__en": "",
    }
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=product.pk)

    errors = response.context_data["form"].errors

    assert "base" in errors
    assert "name__en" in errors["base"]
Пример #14
0
def test_edit_view_adding_messages_to_form_group(rf, admin_user):
    shop = get_default_shop()  # obvious prerequisite
    product = get_default_product()
    shop_product = product.get_shop_instance(shop)
    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=shop_product.pk)
    response.render()
    assert 200 <= response.status_code < 300

    assert ProductEditView.add_form_errors_as_messages

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content, "lxml"))
    post_data = {
        # Error in the base form part
        "base-name__en": "",
    }
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    errors = response.context_data["form"].errors

    assert "base" in errors
    assert "name__en" in errors["base"]
Пример #15
0
def test_basic_order_flow(with_company, with_signal):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    c = SmartClient()
    product_ids = _populate_client_basket(c)

    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_soup = c.soup(addresses_path)
    inputs = fill_address_inputs(addresses_soup, with_company=with_company)
    response = c.post(addresses_path, data=inputs)
    assert response.status_code == 302  # Should redirect forth

    # Make sure the address is initialized from storage
    # Go back to addresses right before back to methods
    c.soup(addresses_path)

    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = c.soup(methods_path)
    assert c.post(methods_path, data=extract_form_fields(
        methods_soup)).status_code == 302  # Should redirect forth

    if with_signal:
        checkout_complete.connect(checkout_complete_signal,
                                  dispatch_uid="checkout_complete_signal")

    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = c.soup(confirm_path)
    Product.objects.get(pk=product_ids[0]).soft_delete()
    assert c.post(confirm_path, data=extract_form_fields(
        confirm_soup)).status_code == 200  # user needs to reconfirm
    data = extract_form_fields(confirm_soup)
    data['accept_terms'] = True
    data['product_ids'] = ','.join(product_ids[1:])
    assert c.post(confirm_path,
                  data=data).status_code == 302  # Should redirect forth

    n_orders_post = Order.objects.count()
    assert n_orders_post > n_orders_pre, "order was created"

    order = Order.objects.first()
    expected_ip = "127.0.0.2" if with_signal else "127.0.0.1"
    assert order.ip_address == expected_ip

    if with_signal:
        checkout_complete.disconnect(dispatch_uid="checkout_complete_signal")
Пример #16
0
def test_create_api_permission_groups(rf, admin_user):
    shop = factories.get_default_shop()
    group1 = Group.objects.create(name="group1")
    group2 = Group.objects.create(name="group2")

    client = SmartClient()
    client.force_login(admin_user)

    url = reverse("shuup_admin:api_permission_groups.new")
    response, soup = client.response_and_soup(url)
    assert response.status_code == 200

    inputs = extract_form_fields(soup)
    name = printable_gibberish()
    inputs["base-name"] = name
    inputs["base-groups"] = [group2.pk]

    assert APIPermissionGroups.objects.count() == 0

    response = client.post(url, data=inputs)
    assert response.status_code == 302

    permission_groups = APIPermissionGroups.objects.first()
    assert permission_groups.name == name
    assert permission_groups.groups.count() == 1
    assert group2 in permission_groups.groups.all()

    edit_url = reverse("shuup_admin:api_permission_groups.edit",
                       kwargs={"pk": permission_groups.pk})
    assert response.url == edit_url

    response, soup = client.response_and_soup(edit_url)
    assert response.status_code == 200
    inputs = extract_form_fields(soup)
    new_name = printable_gibberish()
    inputs["base-name"] = new_name
    inputs["base-groups"] = [group2.pk, group1.pk]
    response = client.post(edit_url, data=inputs)
    assert response.status_code == 302
    assert response.url == edit_url

    permission_groups.refresh_from_db()
    assert permission_groups.name == new_name
    assert permission_groups.groups.count() == 2
    assert group1 in permission_groups.groups.all()
    assert group2 in permission_groups.groups.all()
Пример #17
0
def test_reviews_view(rf):
    shop = factories.get_default_shop()
    customer = factories.create_random_person("en")
    user = factories.create_random_user("en")
    user.set_password("user")
    user.save()
    customer.user = user
    customer.save()

    client = SmartClient()
    client.login(username=user.username, password="******")

    # no reviews in dashboard
    response = client.get(reverse("shuup:dashboard"))
    assert response.status_code == 200
    response.render()
    content = response.content.decode("utf-8")
    assert "You haven't made any reviews yet" in content

    # create some reviews for customer
    [create_random_review_for_reviwer(shop, customer) for _ in range(15)]
    # create some orders to review
    [create_random_order_to_review(shop, customer) for order in range(3)]

    # reload dashboard
    response = client.get(reverse("shuup:dashboard"))
    assert response.status_code == 200
    response.render()
    content = response.content.decode("utf-8")
    assert "Last reviews" in content

    # show all reviews
    response, soup = client.response_and_soup(reverse("shuup:product_reviews"))
    assert response.status_code == 200
    response.render()
    content = response.content.decode("utf-8")
    assert "Products to Review" in content

    form_data = extract_form_fields(soup)

    for key in form_data.keys():
        if key.endswith("comment"):
            form_data[key] = Faker().text(100)
        if key.endswith("rating"):
            form_data[key] = random.randint(1, 5)
        if key.endswith("would_recommend"):
            form_data[key] = random.choice([True, False])

    # post reviews
    request = rf.post("/")
    request.person = request.customer = customer
    request.shop = shop

    response = client.post(reverse("shuup:product_reviews"), data=form_data)
    assert response.status_code == 200
    response.render()
    content = response.content.decode("utf-8")
    assert "Products to Review" not in content
Пример #18
0
def test_basic_order_flow(with_company, with_signal):
    cache.clear()
    create_default_order_statuses()
    n_orders_pre = Order.objects.count()
    populate_if_required()
    c = SmartClient()
    product_ids = _populate_client_basket(c)

    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_soup = c.soup(addresses_path)
    inputs = fill_address_inputs(addresses_soup, with_company=with_company)
    response = c.post(addresses_path, data=inputs)
    assert response.status_code == 302  # Should redirect forth

    # Make sure the address is initialized from storage
    # Go back to addresses right before back to methods
    c.soup(addresses_path)

    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = c.soup(methods_path)
    assert c.post(methods_path, data=extract_form_fields(methods_soup)).status_code == 302  # Should redirect forth

    if with_signal:
        checkout_complete.connect(checkout_complete_signal, dispatch_uid="checkout_complete_signal")

    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = c.soup(confirm_path)
    Product.objects.get(pk=product_ids[0]).soft_delete()
    assert c.post(confirm_path, data=extract_form_fields(confirm_soup)).status_code == 200  # user needs to reconfirm
    data = extract_form_fields(confirm_soup)
    data['product_ids'] = ','.join(product_ids[1:])
    assert c.post(confirm_path, data=data).status_code == 302  # Should redirect forth

    n_orders_post = Order.objects.count()
    assert n_orders_post > n_orders_pre, "order was created"

    order = Order.objects.first()
    expected_ip = "127.0.0.2" if with_signal else "127.0.0.1"
    assert order.ip_address == expected_ip

    if with_signal:
        checkout_complete.disconnect(dispatch_uid="checkout_complete_signal")
Пример #19
0
def test_create_api_access(rf, admin_user):
    shop = factories.get_default_shop()
    client = SmartClient()
    client.force_login(admin_user)

    url = reverse("shuup_admin:api_access.new")
    response, soup = client.response_and_soup(url)
    assert response.status_code == 200

    inputs = extract_form_fields(soup)
    name = printable_gibberish()
    inputs["base-name"] = name
    inputs["base-enabled"] = False

    assert APIAccess.objects.count() == 0

    response = client.post(url, data=inputs)
    assert response.status_code == 302

    api_access = APIAccess.objects.first()
    assert api_access.enabled is False
    assert api_access.name == name

    edit_url = reverse("shuup_admin:api_access.edit",
                       kwargs={"pk": api_access.pk})
    assert response.url == edit_url

    response, soup = client.response_and_soup(edit_url)
    assert response.status_code == 200
    inputs = extract_form_fields(soup)
    new_name = printable_gibberish()
    inputs["base-name"] = new_name
    inputs["base-enabled"] = True
    response = client.post(edit_url, data=inputs)
    assert response.status_code == 302
    assert response.url == edit_url

    api_access.refresh_from_db()
    assert api_access.enabled
    assert api_access.name == new_name
Пример #20
0
def test_gdpr_admin_settings(client, admin_user):
    """
    Test that admin user can enable GDPR and add cookie categories
    """
    activate("en")
    shop = factories.get_default_shop()
    client = SmartClient()
    admin_user.set_password("admin")
    admin_user.save()
    client.login(username=admin_user.username, password="******")
    admin_settings_url = reverse("shuup_admin:gdpr.settings")

    assert not GDPRSettings.objects.exists()
    response = client.soup(admin_settings_url)
    assert GDPRSettings.objects.exists()
    s = GDPRSettings.objects.first()
    assert s.cookie_banner_content == settings.SHUUP_GDPR_DEFAULT_BANNER_STRING
    assert s.cookie_privacy_excerpt == settings.SHUUP_GDPR_DEFAULT_EXCERPT_STRING
    assert GDPRCookieCategory.objects.count() == 0

    page = Page.objects.create(shop=shop, available_from=now())
    page.title = "test"
    page.save()
    # create the settings with only basic options
    payload = extract_form_fields(response)
    payload.pop("base-consent_pages")
    payload.update({
        "base-enabled": True,
        "base-privacy_policy_page": page.pk,
        "base-cookie_banner_content__en": "Banner content",
        "base-cookie_privacy_excerpt__en": "Cookie excerpt",
        "cookie_categories-0-id": "",
        "cookie_categories-0-always_active": 1,
        "cookie_categories-0-name__en": "required",
        "cookie_categories-0-how_is_used__en": "to work",
        "cookie_categories-0-cookies": "sessionid",
    })
    response = client.post(admin_settings_url, data=payload)
    assert response.status_code == 302

    assert GDPRCookieCategory.objects.count() == 1

    # add one more cookie category
    payload.update({
        "cookie_categories-1-id": "",
        "cookie_categories-1-always_active": 1,
        "cookie_categories-1-name__en": "Maybe",
        "cookie_categories-1-how_is_used__en": "to spy",
        "cookie_categories-1-cookies": "_ga",
    })
    client.post(admin_settings_url, data=payload)
    assert GDPRCookieCategory.objects.count() == 2
Пример #21
0
def test_gdpr_admin_settings(client, admin_user):
    """
    Test that admin user can enable GDPR and add cookie categories
    """
    activate("en")
    shop = factories.get_default_shop()
    client = SmartClient()
    admin_user.set_password("admin")
    admin_user.save()
    client.login(username=admin_user.username, password="******")
    admin_settings_url = reverse("shuup_admin:gdpr.settings")

    assert not GDPRSettings.objects.exists()
    response = client.soup(admin_settings_url)
    assert GDPRSettings.objects.exists()
    s = GDPRSettings.objects.first()
    assert s.cookie_banner_content == settings.SHUUP_GDPR_DEFAULT_BANNER_STRING
    assert s.cookie_privacy_excerpt == settings.SHUUP_GDPR_DEFAULT_EXCERPT_STRING
    assert GDPRCookieCategory.objects.count() == 0

    page = Page.objects.create(shop=shop, available_from=now())
    page.title = "test"
    page.save()
    # create the settings with only basic options
    payload = extract_form_fields(response)
    payload.update({
        "base-enabled": True,
        "base-privacy_policy_page": page.pk,
        "base-cookie_banner_content__en": "Banner content",
        "base-cookie_privacy_excerpt__en": "Cookie excerpt",
        "cookie_categories-0-id": "",
        "cookie_categories-0-always_active": 1,
        "cookie_categories-0-name__en": "required",
        "cookie_categories-0-how_is_used__en": "to work",
        "cookie_categories-0-cookies": "sessionid"
    })
    response = client.post(admin_settings_url, data=payload)
    assert response.status_code == 302

    assert GDPRCookieCategory.objects.count() == 1

    # add one more cookie category
    payload.update({
        "cookie_categories-1-id": "",
        "cookie_categories-1-always_active": 1,
        "cookie_categories-1-name__en": "Maybe",
        "cookie_categories-1-how_is_used__en": "to spy",
        "cookie_categories-1-cookies": "_ga"
    })
    client.post(admin_settings_url, data=payload)
    assert GDPRCookieCategory.objects.count() == 2
Пример #22
0
def _complete_checkout(client, expected_order_count):
    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_soup = client.soup(addresses_path)
    inputs = _fill_address_inputs(addresses_soup, with_company=False)
    response = client.post(addresses_path, data=inputs)
    assert response.status_code == 302  # Should redirect forth

    # Make sure the address is initialized from storage
    # Go back to addresses right before back to methods
    client.soup(addresses_path)

    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = client.soup(methods_path)
    assert client.post(methods_path, data=extract_form_fields(methods_soup)).status_code == 302  # Should redirect forth

    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = client.soup(confirm_path)
    data = extract_form_fields(confirm_soup)
    assert client.post(confirm_path, data=data).status_code == 302  # Should redirect forth

    n_orders_post = Order.objects.count()
    assert n_orders_post == expected_order_count, "order was created"
    return Order.objects.order_by("-id").first()
Пример #23
0
def test_admin_form_part(admin_user):
    factories.get_default_shop()
    client = SmartClient()
    client.login(username=admin_user.username, password="******")

    assert Page.objects.count() == 0
    response, soup = client.response_and_soup(
        reverse("shuup_admin:simple_cms.page.new"))
    assert response.status_code == 200
    payload = extract_form_fields(soup)

    # do some cleaning
    for key in payload.keys():
        if payload[key] is None:
            payload[key] = ""

    # create 9 articles
    for i in range(9):
        payload.update({
            "base-title__en": "My Article %d" % i,
            "base-url__en": "my-article-%d" % i,
            "base-available_from": "0%s/01/2018 00:00:00" % (i + 1),
            "base-available_to": "0%s/01/2019 00:00:00" % (i + 1),
            "base-content__en": "Some content here %d" % i,
            "base-template_name": "shuup_cms_blog/blog_page.jinja",
            "blog-is_blog_article": True,
            "blog-image": factories.get_random_filer_image().pk,
            "blog-small_description__en": "small description %d" % i
        })
        response = client.post(reverse("shuup_admin:simple_cms.page.new"),
                               data=payload)
        assert response.status_code == 302
        assert Page.objects.count() == (i + 1)

        response, soup = client.response_and_soup(
            reverse("shuup:cms_page",
                    kwargs=dict(url=payload["base-url__en"])))
        assert response.status_code == 200
        assert soup.find("div", {"class": "article-features"})

    # update blog image of the last page
    payload.update({
        "blog-image": factories.get_random_filer_image().pk,
    })
    response = client.post(reverse("shuup_admin:simple_cms.page.edit",
                                   kwargs=dict(pk=Page.objects.last().pk)),
                           data=payload)
    assert response.status_code == 302
Пример #24
0
def test_gdpr_admin_settings(client, admin_user):
    """
    Test that admin user can enable GDPR and add cookie categories
    """
    activate("en")
    shop = factories.get_default_shop()
    client = SmartClient()
    admin_user.set_password("admin")
    admin_user.save()
    client.login(username=admin_user.username, password="******")
    admin_settings_url = reverse("shuup_admin:gdpr.settings")

    assert not GDPRSettings.objects.exists()
    response = client.soup(admin_settings_url)
    assert GDPRSettings.objects.exists()
    assert GDPRCookieCategory.objects.count() == 0

    # create the settings with only basic options
    payload = extract_form_fields(response)
    payload.update({
        "base-enabled": True,
        "base-cookie_banner_content__en": "Banner content",
        "base-cookie_privacy_excerpt__en": "Cookie excerpt",
        "cookie_categories-0-id": "",
        "cookie_categories-0-always_active": 1,
        "cookie_categories-0-name__en": "required",
        "cookie_categories-0-how_is_used__en": "to work",
        "cookie_categories-0-cookies": "sessionid"
    })
    response = client.post(admin_settings_url, data=payload)
    assert response.status_code == 302

    assert GDPRCookieCategory.objects.count() == 1
    assert Page.objects.visible(shop).filter(
        page_type=PageType.GDPR_CONSENT_DOCUMENT).exists()

    # add one more cookie category
    payload.update({
        "cookie_categories-1-id": "",
        "cookie_categories-1-always_active": 1,
        "cookie_categories-1-name__en": "Maybe",
        "cookie_categories-1-how_is_used__en": "to spy",
        "cookie_categories-1-cookies": "_ga"
    })
    client.post(admin_settings_url, data=payload)
    assert GDPRCookieCategory.objects.count() == 2
Пример #25
0
def _populate_client_basket(client):
    index = client.soup("/")
    product_links = index.find_all("a", rel="product-detail")
    assert product_links
    product_detail_path = product_links[0]["href"]
    assert product_detail_path
    product_detail_soup = client.soup(product_detail_path)
    inputs = extract_form_fields(product_detail_soup)
    basket_path = reverse("shuup:basket")
    for i in range(3):  # Add the same product thrice
        add_to_basket_resp = client.post(basket_path, data={
            "command": "add",
            "product_id": inputs["product_id"],
            "quantity": 1,
            "supplier": get_default_supplier().pk
        })
        assert add_to_basket_resp.status_code < 400
    basket_soup = client.soup(basket_path)
    assert b'no such element' not in basket_soup.renderContents(), 'All product details are not rendered correctly'
Пример #26
0
def test_new_user_information_edit():
    client = SmartClient()
    get_default_shop()
    # create new user
    user_password = "******"
    user = get_user_model().objects.create_user(
        username="******",
        email="*****@*****.**",
        password=user_password,
        first_name="Niilo",
        last_name="Nyyppä",
    )

    client.login(username=user.username, password=user_password)

    # make sure all information matches in form
    customer_edit_url = reverse("shuup:customer_edit")
    soup = client.soup(customer_edit_url)

    assert soup.find(attrs={"name": "contact-email"})["value"] == user.email
    assert soup.find(
        attrs={"name": "contact-first_name"})["value"] == user.first_name
    assert soup.find(
        attrs={"name": "contact-last_name"})["value"] == user.last_name

    # Test POSTing
    form = extract_form_fields(soup)
    new_email = "*****@*****.**"
    form["contact-email"] = new_email
    form["contact-country"] = "FI"

    for prefix in ("billing", "shipping"):
        form["%s-city" % prefix] = "test-city"
        form["%s-email" % prefix] = new_email
        form["%s-street" % prefix] = "test-street"
        form["%s-country" % prefix] = "FI"

    response, soup = client.response_and_soup(customer_edit_url, form, "post")

    assert response.status_code == 302
    assert get_user_model().objects.get(pk=user.pk).email == new_email
Пример #27
0
def fill_address_inputs(soup, address, with_company=False):
    inputs = {}
    for key, value in extract_form_fields(soup.find('form', id='addresses')).items():
        if not value:
            if key in ("order-tax_number", "order-company_name"):
                continue
            if key.startswith("shipping-") or key.startswith("billing-"):
                bit = key.split("-")[1]
                value = getattr(address, bit, None)
            if not value and "email" in key:
                value = "*****@*****.**" % random.random()
            if not value:
                value = "test"
        inputs[key] = value

    if with_company:
        inputs["company-tax_number"] = "FI1234567-1"
        inputs["company-company_name"] = "Example Oy"
    else:
        inputs = dict((k, v) for (k, v) in inputs.items() if not k.startswith("company-"))

    return inputs
Пример #28
0
def test_new_user_information_edit():
    client = SmartClient()
    get_default_shop()
    # create new user
    user_password = "******"
    user = get_user_model().objects.create_user(
        username="******",
        email="*****@*****.**",
        password=user_password,
        first_name="Niilo",
        last_name="Nyyppä",
    )

    client.login(username=user.username, password=user_password)

    # make sure all information matches in form
    customer_edit_url = reverse("shuup:customer_edit")
    soup = client.soup(customer_edit_url)

    assert soup.find(attrs={"name": "contact-email"})["value"] == user.email
    assert soup.find(attrs={"name": "contact-first_name"})["value"] == user.first_name
    assert soup.find(attrs={"name": "contact-last_name"})["value"] == user.last_name

    # Test POSTing
    form = extract_form_fields(soup)
    new_email = "*****@*****.**"
    form["contact-email"] = new_email
    form["contact-country"] = "FI"

    for prefix in ("billing", "shipping"):
        form["%s-city" % prefix] = "test-city"
        form["%s-email" % prefix] = new_email
        form["%s-street" % prefix] = "test-street"
        form["%s-country" % prefix] = "FI"

    response, soup = client.response_and_soup(customer_edit_url, form, "post")

    assert response.status_code == 302
    assert get_user_model().objects.get(pk=user.pk).email == new_email
Пример #29
0
def test_checkout_with_success():
    get_default_shop()
    set_current_theme('shuup.themes.classic_gray')
    create_default_order_statuses()
    populate_if_required()

    client = SmartClient()

    # first step - register user
    person_data = {
        "email": "*****@*****.**",
        "password1": "password",
        "password2": "password",
        "person_type": PersonType.FISICA.value,
        "PF-name": "NOME DA PESSOA",
        "PF-cpf": "012.345.678-90",
        "PF-rg": "312321",
        "PF-birth_date": "03/28/1954",
        "PF-gender": Gender.MALE.value
    }

    result = client.post(reverse("shuup:registration_register"), data=person_data)
    assert not result is None
    user = get_user_model().objects.get(email=person_data['email'])
    assert user.is_active


    # second step -add something into the basket
    default_product = get_default_product()

    basket_path = reverse("shuup:basket")
    add_to_basket_resp = client.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


    # third step - go to checkout and set the addresses
    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_data = {
        'billing-name': 'maria da silva',
        'billing-street': 'rua billing',
        'billing-street2': 'apto',
        'billing-street3': 'bairro outrem',
        'billing-postal_code': '89090-200',
        'billing-city': 'plumenau',
        'billing-region': 'PR',
        'billing-country': 'BR',
        'billing-phone': '41 2332-0213',
        'billing_extra-numero': '563',
        'billing_extra-cel': '13 98431-4345',
        'billing_extra-ponto_ref': 'longe de tudo',

        'shipping-name': 'joao da silva',
        'shipping-street': 'rua shipping',
        'shipping-street2': 'complemento',
        'shipping-street3': 'bairro',
        'shipping-postal_code': '89050120',
        'shipping-city': 'indaial',
        'shipping-region': 'SC',
        'shipping-country': 'BR',
        'shipping-phone': '39 9999-2332',
        'shipping_extra-numero': '323',
        'shipping_extra-cel': '21 4444-3333',
        'shipping_extra-ponto_ref': 'proximo posto',
    }

    response = client.post(addresses_path, data=addresses_data)
    print (response.content)
    assert response.status_code == 302  # Should redirect forth


    # Set the payment and shipping methods
    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = client.soup(methods_path)
    assert client.post(methods_path, data=extract_form_fields(methods_soup)).status_code == 302  # Should redirect forth


    # Confirm the order
    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = client.soup(confirm_path)
    assert client.post(confirm_path, data=extract_form_fields(confirm_soup)).status_code == 302  # Should redirect forth
Пример #30
0
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
Пример #31
0
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()
Пример #32
0
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
Пример #33
0
def test_checkout_with_success():
    get_default_shop()
    set_current_theme('shuup.themes.classic_gray')
    create_default_order_statuses()
    populate_if_required()

    client = SmartClient()

    # first step - register user
    person_data = {
        "email": "*****@*****.**",
        "password1": "password",
        "password2": "password",
        "person_type": PersonType.FISICA.value,
        "PF-name": "NOME DA PESSOA",
        "PF-cpf": "012.345.678-90",
        "PF-rg": "312321",
        "PF-birth_date": "03/28/1954",
        "PF-gender": Gender.MALE.value
    }

    result = client.post(reverse("shuup:registration_register"),
                         data=person_data)
    assert not result is None
    user = get_user_model().objects.get(email=person_data['email'])
    assert user.is_active

    # second step -add something into the basket
    default_product = get_default_product()

    basket_path = reverse("shuup:basket")
    add_to_basket_resp = client.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

    # third step - go to checkout and set the addresses
    addresses_path = reverse("shuup:checkout", kwargs={"phase": "addresses"})
    addresses_data = {
        'billing-name': 'maria da silva',
        'billing-street': 'rua billing',
        'billing-street2': 'apto',
        'billing-street3': 'bairro outrem',
        'billing-postal_code': '89090-200',
        'billing-city': 'plumenau',
        'billing-region': 'PR',
        'billing-country': 'BR',
        'billing-phone': '41 2332-0213',
        'billing_extra-numero': '563',
        'billing_extra-cel': '13 98431-4345',
        'billing_extra-ponto_ref': 'longe de tudo',
        'shipping-name': 'joao da silva',
        'shipping-street': 'rua shipping',
        'shipping-street2': 'complemento',
        'shipping-street3': 'bairro',
        'shipping-postal_code': '89050120',
        'shipping-city': 'indaial',
        'shipping-region': 'SC',
        'shipping-country': 'BR',
        'shipping-phone': '39 9999-2332',
        'shipping_extra-numero': '323',
        'shipping_extra-cel': '21 4444-3333',
        'shipping_extra-ponto_ref': 'proximo posto',
    }

    response = client.post(addresses_path, data=addresses_data)
    print(response.content)
    assert response.status_code == 302  # Should redirect forth

    # Set the payment and shipping methods
    methods_path = reverse("shuup:checkout", kwargs={"phase": "methods"})
    methods_soup = client.soup(methods_path)
    assert client.post(methods_path, data=extract_form_fields(
        methods_soup)).status_code == 302  # Should redirect forth

    # Confirm the order
    confirm_path = reverse("shuup:checkout", kwargs={"phase": "confirm"})
    confirm_soup = client.soup(confirm_path)
    assert client.post(confirm_path, data=extract_form_fields(
        confirm_soup)).status_code == 302  # Should redirect forth
Пример #34
0
def test_product_edit_view(rf, admin_user, settings):
    shop = get_default_shop()  # obvious prerequisite
    product = get_default_product()
    shop_product = product.get_shop_instance(shop)
    cat = CategoryFactory()

    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=product.pk)
    response.render()

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content))

    # Needed for Django 1.8 tests to pass
    post.update({
        'shop1-default_price_value': '42',
        'images-TOTAL_FORMS': '0',
        'media-TOTAL_FORMS': '0',
        'base-name__fi': 'test',
        'base-name__it': 'test',
        'base-name__ja': 'test',
        'base-name__pt-br': 'test',
        'base-name__zh-hans': 'test',
    })

    post_data = {'shop1-primary_category': [], 'shop1-categories': []}
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=product.pk)

    shop_product.refresh_from_db()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {
        'shop1-default_price_value': 12,
        'shop1-primary_category': [cat.pk],
        'shop1-categories': []
    }
    post.update(post_data)
    usable_post = {}
    for k, v in six.iteritems(post):
        if not k:
            continue
        if not post[k]:
            continue
        usable_post[k] = v

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=product.pk)

    shop_product = ShopProduct.objects.first()
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.categories.count() == 1
        assert shop_product.categories.first() == cat
    else:
        assert not shop_product.categories.count()

    assert shop_product.primary_category == cat

    post_data = {'shop1-primary_category': [], 'shop1-categories': []}
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=product.pk)

    # empty again
    shop_product = ShopProduct.objects.first()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {'shop1-primary_category': [], 'shop1-categories': [cat.pk]}
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 1
    assert shop_product.categories.first() == cat
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category

    cat2 = CategoryFactory()

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': [cat.pk, cat2.pk]
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 2
    assert cat in shop_product.categories.all()
    assert cat2 in shop_product.categories.all()
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category
Пример #35
0
def test_product_edit_view(rf, admin_user, settings):
    shop = get_default_shop()  # obvious prerequisite
    shop.staff_members.add(admin_user)
    parent = create_product("ComplexVarParent",
                            shop=shop,
                            supplier=get_default_supplier())
    sizes = [("%sL" % ("X" * x)) for x in range(4)]
    for size in sizes:
        child = create_product("ComplexVarChild-%s" % size,
                               shop=shop,
                               supplier=get_default_supplier())
        child.link_to_parent(parent, variables={"size": size})
    shop_product = parent.get_shop_instance(shop)
    cat = CategoryFactory()

    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=shop_product.pk)
    response.render()

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content, "lxml"))

    # Needed for Django 1.8 tests to pass
    post.update({
        "shop1-default_price_value": "42",
        "images-TOTAL_FORMS": "0",
        "media-TOTAL_FORMS": "0",
        "base-name__fi": "test",
        "base-name__it": "test",
        "base-name__ja": "test",
        "base-name__pt-br": "test",
        "base-name__zh-hans": "test",
        "base-name__es": "test",
    })

    post_data = {"shop1-primary_category": [], "shop1-categories": []}
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product.refresh_from_db()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {
        "shop1-default_price_value": 12,
        "shop1-primary_category": cat.pk,
        "shop1-categories": []
    }
    post.update(post_data)
    usable_post = {}
    for k, v in six.iteritems(post):
        if not k:
            continue
        if not post[k]:
            continue
        usable_post[k] = v

    with patch("django.db.transaction.on_commit", new=atomic_commit_mock):
        request = apply_request_middleware(rf.post("/", usable_post),
                                           user=admin_user)
        response = view(request, pk=shop_product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.primary_category

    # the catalog price was indexed
    catalog_price = ProductCatalogPrice.objects.filter(
        shop=shop_product.shop, product=shop_product.product).first()
    assert catalog_price.price_value == shop_product.default_price_value

    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.categories.count() == 1
        assert shop_product.categories.first() == cat
    else:
        assert not shop_product.categories.count()

    assert shop_product.primary_category == cat

    post_data = {"shop1-primary_category": [], "shop1-categories": []}
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=shop_product.pk)

    # empty again
    shop_product = ShopProduct.objects.first()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {"shop1-primary_category": [], "shop1-categories": [cat.pk]}
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 1
    assert shop_product.categories.first() == cat
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category

    cat2 = CategoryFactory()

    post_data = {
        "shop1-primary_category": [],
        "shop1-categories": [cat.pk, cat2.pk]
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post),
                                       user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 2
    assert cat in shop_product.categories.all()
    assert cat2 in shop_product.categories.all()
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category

    # Test for showing alert of validation issues
    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=shop_product.pk)
    response.render()
    content = force_text(response.content)
    soup = BeautifulSoup(content, "lxml")
    alert = soup.find_all("div", {"class": "validation-issues-alert"})
    assert not alert

    with override_provides(
            "admin_product_validator",
        ["shuup.testing.admin_product_validator:TestAdminProductValidator"],
    ):
        view = ProductEditView.as_view()
        request = apply_request_middleware(rf.get("/"), user=admin_user)
        response = view(request, pk=shop_product.pk)
        response.render()
        content = force_text(response.content)
        soup = BeautifulSoup(content, "lxml")
        alert = soup.find_all(
            "div", {"class": "validation-issues-alert alert alert-danger"})
        assert alert
        alert_danger = soup.find_all("div", {"class": "alert-danger"})
        assert alert_danger
        alert = soup.find_all(
            "div", {"class": "validation-issues-alert alert alert-warning"})
        alert_div = alert[0]
        strong = alert_div.find_all("strong")
        assert strong
        script = alert_div.find_all("script")
        assert not script
Пример #36
0
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
Пример #37
0
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
Пример #38
0
def _extract_fields(rf, user):
    request = apply_request_middleware(rf.get("/"), user=user)
    response = WizardView.as_view()(request)
    response.render()
    soup = BeautifulSoup(response.content)
    return extract_form_fields(soup.find("form"))
Пример #39
0
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
Пример #40
0
def test_product_edit_view(rf, admin_user, settings):
    shop = get_default_shop()  # obvious prerequisite
    product = get_default_product()
    shop_product = product.get_shop_instance(shop)
    cat = CategoryFactory()

    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=product.pk)
    response.render()

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content))

    # Needed for Django 1.8 tests to pass
    post.update({
        'shop1-default_price_value': '42',
        'images-TOTAL_FORMS': '0',
        'media-TOTAL_FORMS': '0',
        'base-name__fi': 'test',
        'base-name__it': 'test',
        'base-name__ja': 'test',
        'base-name__pt-br': 'test',
        'base-name__zh-hans': 'test',
    })

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': []
    }
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=product.pk)

    shop_product.refresh_from_db()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {
        'shop1-default_price_value': 12,
        'shop1-primary_category': [cat.pk],
        'shop1-categories': []
    }
    post.update(post_data)
    usable_post = {}
    for k, v in six.iteritems(post):
        if not k:
            continue
        if not post[k]:
            continue
        usable_post[k] = v

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=product.pk)

    shop_product = ShopProduct.objects.first()
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.categories.count() == 1
        assert shop_product.categories.first() == cat
    else:
        assert not shop_product.categories.count()

    assert shop_product.primary_category == cat

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': []
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=product.pk)

    # empty again
    shop_product = ShopProduct.objects.first()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': [cat.pk]
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 1
    assert shop_product.categories.first() == cat
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category

    cat2 = CategoryFactory()

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': [cat.pk, cat2.pk]
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 2
    assert cat in shop_product.categories.all()
    assert cat2 in shop_product.categories.all()
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category
Пример #41
0
def test_product_edit_view(rf, admin_user, settings):
    shop = get_default_shop()  # obvious prerequisite
    shop.staff_members.add(admin_user)
    parent = create_product("ComplexVarParent", shop=shop, supplier=get_default_supplier())
    sizes = [("%sL" % ("X" * x)) for x in range(4)]
    for size in sizes:
        child = create_product(
            "ComplexVarChild-%s" % size, shop=shop, supplier=get_default_supplier())
        child.link_to_parent(parent, variables={"size": size})
    shop_product = parent.get_shop_instance(shop)
    cat = CategoryFactory()

    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    view = ProductEditView.as_view()
    request = apply_request_middleware(rf.get("/"), user=admin_user)
    response = view(request, pk=shop_product.pk)
    response.render()

    content = force_text(response.content)
    post = extract_form_fields(BeautifulSoup(content, "lxml"))

    # Needed for Django 1.8 tests to pass
    post.update({
        'shop1-default_price_value': '42',
        'images-TOTAL_FORMS': '0',
        'media-TOTAL_FORMS': '0',
        'base-name__fi': 'test',
        'base-name__it': 'test',
        'base-name__ja': 'test',
        'base-name__pt-br': 'test',
        'base-name__zh-hans': 'test',
    })

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': []
    }
    post.update(post_data)
    request = apply_request_middleware(rf.post("/", post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product.refresh_from_db()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {
        'shop1-default_price_value': 12,
        'shop1-primary_category': cat.pk,
        'shop1-categories': []
    }
    post.update(post_data)
    usable_post = {}
    for k, v in six.iteritems(post):
        if not k:
            continue
        if not post[k]:
            continue
        usable_post[k] = v

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.primary_category

    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.categories.count() == 1
        assert shop_product.categories.first() == cat
    else:
        assert not shop_product.categories.count()

    assert shop_product.primary_category == cat

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': []
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    # empty again
    shop_product = ShopProduct.objects.first()
    assert not shop_product.categories.exists()
    assert not shop_product.primary_category

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': [cat.pk]
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 1
    assert shop_product.categories.first() == cat
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category

    cat2 = CategoryFactory()

    post_data = {
        'shop1-primary_category': [],
        'shop1-categories': [cat.pk, cat2.pk]
    }
    usable_post.update(post_data)

    request = apply_request_middleware(rf.post("/", usable_post), user=admin_user)
    response = view(request, pk=shop_product.pk)

    shop_product = ShopProduct.objects.first()
    assert shop_product.categories.count() == 2
    assert cat in shop_product.categories.all()
    assert cat2 in shop_product.categories.all()
    if settings.SHUUP_AUTO_SHOP_PRODUCT_CATEGORIES:
        assert shop_product.primary_category == cat
    else:
        assert not shop_product.primary_category
Пример #42
0
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_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
Пример #44
0
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
Пример #45
0
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()
Пример #46
0
def test_new_user_information_edit(allow_image_uploads):
    with override_settings(
            SHUUP_CUSTOMER_INFORMATION_ALLOW_PICTURE_UPLOAD=allow_image_uploads
    ):
        client = SmartClient()
        get_default_shop()
        # create new user
        user_password = "******"
        user = get_user_model().objects.create_user(
            username="******",
            email="*****@*****.**",
            password=user_password,
            first_name="Niilo",
            last_name="Nyyppä",
        )

        client.login(username=user.username, password=user_password)

        # make sure all information matches in form
        customer_edit_url = reverse("shuup:customer_edit")
        soup = client.soup(customer_edit_url)

        assert soup.find(
            attrs={"name": "contact-email"})["value"] == user.email
        assert soup.find(
            attrs={"name": "contact-first_name"})["value"] == user.first_name
        assert soup.find(
            attrs={"name": "contact-last_name"})["value"] == user.last_name

        # Test POSTing
        form = extract_form_fields(soup)
        new_email = "*****@*****.**"
        form["contact-email"] = new_email
        form["contact-country"] = "FI"

        for prefix in ("billing", "shipping"):
            form["%s-city" % prefix] = "test-city"
            form["%s-email" % prefix] = new_email
            form["%s-street" % prefix] = "test-street"
            form["%s-country" % prefix] = "FI"

        if allow_image_uploads:
            tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
            generate_image(120, 120).save(tmp_file)
            with open(tmp_file.name, 'rb') as data:
                response = client.post(reverse("shuup:media-upload"),
                                       data=dict({"file": data}),
                                       format="multipart")
            assert response.status_code == 200
            data = json.loads(response.content.decode("utf-8"))
            file_id = data["file"]["id"]
            form["contact-picture"] = file_id

        response, soup = client.response_and_soup(customer_edit_url, form,
                                                  "post")
        assert response.status_code == 302
        user = get_user_model().objects.get(pk=user.pk)
        assert user.email == new_email
        contact = get_person_contact(user)

        if allow_image_uploads:
            assert contact.picture.id == file_id

            # Fetch page and check that the picture rendered there
            customer_edit_url = reverse("shuup:customer_edit")
            soup = client.soup(customer_edit_url)
            assert int(
                soup.find(attrs={"id": "id_contact-picture-dropzone"})
                ["data-id"]) == file_id
        else:
            assert contact.picture is None
Пример #47
0
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
Пример #48
0
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
Пример #49
0
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
Пример #50
0
def _extract_fields(rf, user):
    request = apply_request_middleware(rf.get("/"), user=user)
    response = WizardView.as_view()(request)
    response.render()
    soup = BeautifulSoup(response.content)
    return extract_form_fields(soup.find("form"))