コード例 #1
0
ファイル: views_test.py プロジェクト: mitodl/mitxpro
def assert_api_call(
    client,
    url,
    payload,
    expected,
    expect_authenticated=False,
    expect_status=status.HTTP_200_OK,
    use_defaults=True,
):
    """Run the API call and perform basic assertions"""
    assert bool(get_user(client).is_authenticated) is False

    response = client.post(reverse(url),
                           payload,
                           content_type="application/json")
    actual = response.json()

    defaults = {
        "errors": [],
        "field_errors": {},
        "redirect_url": None,
        "extra_data": {},
        "state": None,
        "provider": EmailAuth.name,
        "flow": None,
        "partial_token": any_instance_of(str),
    }

    assert actual == ({**defaults, **expected} if use_defaults else expected)
    assert response.status_code == expect_status

    assert bool(get_user(client).is_authenticated) is expect_authenticated

    return actual
コード例 #2
0
ファイル: api_test.py プロジェクト: mitodl/mitxpro
def test_build_user_specific_messages(mocker):
    """
    Tests that build_user_specific_messages loops through an iterable of user message properties
    and builds a message object from each one
    """
    patched_build_message = mocker.patch("mail.api.build_message")
    mocker.patch("mail.api.get_base_context", return_value={"base": "context"})
    mocker.patch("mail.api.mail.get_connection")
    template_name = "sample"
    user_message_props_iter = [
        UserMessageProps(
            "*****@*****.**",
            {"first": "context"},
            metadata=EmailMetadata(tags=["tag1"], user_variables=None),
        ),
        UserMessageProps("*****@*****.**", {"second": "context"}),
        UserMessageProps("*****@*****.**"),
    ]

    messages = list(
        build_user_specific_messages(template_name, user_message_props_iter)
    )
    assert len(messages) == len(user_message_props_iter)
    for user_message_props in user_message_props_iter:
        patched_build_message.assert_any_call(
            connection=any_instance_of(mocker.Mock),
            template_name=template_name,
            recipient=user_message_props.recipient,
            context={"base": "context", **user_message_props.context},
            metadata=user_message_props.metadata,
        )
コード例 #3
0
ファイル: api_test.py プロジェクト: mitodl/mitxpro
def test_build_messages(mocker):
    """
    Tests that build_messages creates message objects for a set of recipients with the correct context
    """
    patched_build_message = mocker.patch("mail.api.build_message")
    patched_base_context = mocker.patch(
        "mail.api.get_base_context", return_value={"base": "context"}
    )
    patched_get_connection = mocker.patch("mail.api.mail.get_connection")
    template_name = "sample"
    recipients = ["*****@*****.**", "*****@*****.**"]
    extra_context = {"extra": "context"}
    metadata = EmailMetadata(tags=None, user_variables={"k1": "v1"})

    messages = list(
        build_messages(template_name, recipients, extra_context, metadata=metadata)
    )
    assert patched_build_message.call_count == len(recipients)
    assert len(messages) == len(recipients)
    patched_get_connection.assert_called_once()
    patched_base_context.assert_called_once()
    for recipient in recipients:
        patched_build_message.assert_any_call(
            connection=any_instance_of(mocker.Mock),
            template_name=template_name,
            recipient=recipient,
            context={"base": "context", "extra": "context"},
            metadata=metadata,
        )
コード例 #4
0
def test_any_instance_of():
    """Tests any_instance_of()"""
    any_number = any_instance_of(int, float)

    assert any_number == 0.405
    assert any_number == 8_675_309
    assert any_number != "not a number"
    assert any_number != {}
    assert any_number != []
コード例 #5
0
ファイル: serializers_test.py プロジェクト: mitodl/mitxpro
def test_coupon_payment_version_serializer():
    """ Test that the CouponPaymentVersionSerializer has correct data """
    payment_version = CouponPaymentVersionFactory.create()
    serialized = CouponPaymentVersionSerializer(payment_version).data
    assert serialized == {
        "tag": payment_version.tag,
        "automatic": payment_version.automatic,
        "coupon_type": payment_version.coupon_type,
        "num_coupon_codes": payment_version.num_coupon_codes,
        "max_redemptions": payment_version.max_redemptions,
        "max_redemptions_per_user": payment_version.max_redemptions_per_user,
        "amount": str(payment_version.amount),
        "expiration_date": payment_version.expiration_date.strftime(datetime_format),
        "activation_date": payment_version.activation_date.strftime(datetime_format),
        "payment_type": payment_version.payment_type,
        "payment_transaction": payment_version.payment_transaction,
        "company": payment_version.company.id,
        "payment": payment_version.payment.id,
        "id": payment_version.id,
        "created_on": any_instance_of(str),
        "updated_on": any_instance_of(str),
    }
コード例 #6
0
def test_make_sync_message():
    """Test make_sync_message produces a properly formatted sync-message"""
    object_id = fake.pyint()
    value = fake.word()
    properties = {"prop": value, "blank": None}
    sync_message = api.make_sync_message(object_id, properties)
    assert sync_message == (
        {
            "integratorObjectId": "{}-{}".format(settings.HUBSPOT_ID_PREFIX, object_id),
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": {"prop": value, "blank": ""},
        }
    )
コード例 #7
0
def test_make_line_item_sync_message():
    """Test make_line_item_sync_message serializes a line_item and returns a properly formatted sync message"""
    line = LineFactory()
    line_item_sync_message = api.make_line_item_sync_message(line.id)

    serialized_line = LineSerializer(line).data
    assert line_item_sync_message == [
        {
            "integratorObjectId": "{}-{}".format(settings.HUBSPOT_ID_PREFIX, line.id),
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": serialized_line,
        }
    ]
コード例 #8
0
def test_make_product_sync_message():
    """Test make_deal_sync_message serializes a deal and returns a properly formatted sync message"""
    product = ProductFactory()
    contact_sync_message = api.make_product_sync_message(product.id)

    serialized_product = ProductSerializer(product).data
    assert contact_sync_message == [
        {
            "integratorObjectId": "{}-{}".format(
                settings.HUBSPOT_ID_PREFIX, product.id
            ),
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": serialized_product,
        }
    ]
コード例 #9
0
def test_make_b2b_product_sync_message(hubspot_b2b_order):
    """Test make_b2b_product_sync_message serializes a product and returns a properly formatted sync message"""
    product_sync_message = api.make_b2b_product_sync_message(hubspot_b2b_order.id)

    serialized_product = B2BProductVersionToLineSerializer(hubspot_b2b_order).data
    for key in serialized_product.keys():
        if serialized_product[key] is None:
            serialized_product[key] = ""
    assert product_sync_message == [
        {
            "integratorObjectId": f"{settings.HUBSPOT_ID_PREFIX}-{B2B_INTEGRATION_PREFIX}{hubspot_b2b_order.id}",
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": serialized_product,
        }
    ]
コード例 #10
0
def test_make_b2b_deal_sync_message(hubspot_b2b_order):
    """Test make_b2b_deal_sync_message serializes a deal and returns a properly formatted sync message"""
    deal_sync_message = api.make_b2b_deal_sync_message(hubspot_b2b_order.id)

    serialized_order = B2BOrderToDealSerializer(hubspot_b2b_order).data
    serialized_order["order_type"] = "B2B"
    for key in serialized_order.keys():
        if serialized_order[key] is None:
            serialized_order[key] = ""
    assert deal_sync_message == [
        {
            "integratorObjectId": f"{settings.HUBSPOT_ID_PREFIX}-{B2B_INTEGRATION_PREFIX}{hubspot_b2b_order.id}",
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": serialized_order,
        }
    ]
コード例 #11
0
def test_make_contact_sync_message(user):
    """Test make_contact_sync_message serializes a user and returns a properly formatted sync message"""
    contact_sync_message = api.make_contact_sync_message(user.id)

    serialized_user = UserSerializer(user).data
    serialized_user.update(serialized_user.pop("legal_address") or {})
    serialized_user.update(serialized_user.pop("profile") or {})
    serialized_user["street_address"] = "\n".join(serialized_user.pop("street_address"))
    serialized_user.pop("unused_coupons")
    assert contact_sync_message == [
        {
            "integratorObjectId": "{}-{}".format(settings.HUBSPOT_ID_PREFIX, user.id),
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": api.sanitize_properties(serialized_user),
        }
    ]
コード例 #12
0
def test_send_verification_email(mocker, rf):
    """Test that send_verification_email sends an email with the link in it"""
    send_messages_mock = mocker.patch("mail.api.send_messages")
    email = "test@localhost"
    request = rf.post(reverse("social:complete", args=("email", )),
                      {"email": email})
    # social_django depends on request.session, so use the middleware to set that
    SessionMiddleware().process_request(request)
    strategy = load_strategy(request)
    backend = load_backend(strategy, EmailAuth.name, None)
    code = mocker.Mock(code="abc")
    verification_api.send_verification_email(strategy, backend, code, "def")

    send_messages_mock.assert_called_once_with([any_instance_of(EmailMessage)])

    email_body = send_messages_mock.call_args[0][0][0].body
    assert ("/create-account/confirm/?verification_code=abc&partial_token=def"
            in email_body)
コード例 #13
0
def test_send_verify_email_change_email(mocker, user):
    """Test email change request verification email sends with a link in it"""
    request = RequestFactory().get(reverse("account-settings"))
    change_request = ChangeEmailRequest.objects.create(
        user=user, new_email="*****@*****.**")

    send_messages_mock = mocker.patch("mail.api.send_messages")

    verification_api.send_verify_email_change_email(request, change_request)

    send_messages_mock.assert_called_once_with([any_instance_of(EmailMessage)])

    url = "{}?verification_code={}".format(
        request.build_absolute_uri(reverse("account-confirm-email-change")),
        quote_plus(change_request.code),
    )

    email_body = send_messages_mock.call_args[0][0][0].body
    assert url in email_body
コード例 #14
0
def test_make_deal_sync_message(hubspot_order):
    """Test make_deal_sync_message serializes a deal and returns a properly formatted sync message"""
    deal_sync_message = api.make_deal_sync_message(hubspot_order.id)

    serialized_order = OrderToDealSerializer(hubspot_order).data
    serialized_order.pop("lines")
    for key in serialized_order.keys():
        if serialized_order[key] is None:
            serialized_order[key] = ""
    assert deal_sync_message == [
        {
            "integratorObjectId": "{}-{}".format(
                settings.HUBSPOT_ID_PREFIX, hubspot_order.id
            ),
            "action": "UPSERT",
            "changeOccurredTimestamp": any_instance_of(int),
            "propertyNameToValues": serialized_order,
        }
    ]