Ejemplo n.º 1
0
def create_order_with_ecommerce_service(user, course_key, course_mode):     # pylint: disable=invalid-name
    """ Create a new order using the E-Commerce API. """
    try:
        api = EcommerceAPI()
        # Make an API call to create the order and retrieve the results
        _order_number, _order_status, data = api.create_order(user, course_mode.sku)

        # Pass the payment parameters directly from the API response.
        return HttpResponse(json.dumps(data['payment_parameters']), content_type='application/json')
    except ApiError:
        params = {'username': user.username, 'mode': course_mode.slug, 'course_id': unicode(course_key)}
        log.error('Failed to create order for %(username)s %(mode)s mode of %(course_id)s', params)
        raise
Ejemplo n.º 2
0
def create_order_with_ecommerce_service(user, course_key, course_mode):     # pylint: disable=invalid-name
    """ Create a new order using the E-Commerce API. """
    try:
        api = EcommerceAPI()
        # Make an API call to create the order and retrieve the results
        _order_number, _order_status, data = api.create_order(user, course_mode.sku)

        # Pass the payment parameters directly from the API response.
        return HttpResponse(json.dumps(data['payment_parameters']), content_type='application/json')
    except ApiError:
        params = {'username': user.username, 'mode': course_mode.slug, 'course_id': unicode(course_key)}
        log.error('Failed to create order for %(username)s %(mode)s mode of %(course_id)s', params)
        raise
Ejemplo n.º 3
0
    def post(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """
        Attempt to create the order and enroll the user.
        """
        user = request.user
        valid, course_key, error = self._is_data_valid(request)
        if not valid:
            return DetailResponse(error, status=HTTP_406_NOT_ACCEPTABLE)

        # Don't do anything if an enrollment already exists
        course_id = unicode(course_key)
        enrollment = CourseEnrollment.get_enrollment(user, course_key)
        if enrollment and enrollment.is_active:
            msg = Messages.ENROLLMENT_EXISTS.format(course_id=course_id,
                                                    username=user.username)
            return DetailResponse(msg, status=HTTP_409_CONFLICT)

        # If there is no honor course mode, this most likely a Prof-Ed course. Return an error so that the JS
        # redirects to track selection.
        honor_mode = CourseMode.mode_for_course(course_key, CourseMode.HONOR)

        if not honor_mode:
            msg = Messages.NO_HONOR_MODE.format(course_id=course_id)
            return DetailResponse(msg, status=HTTP_406_NOT_ACCEPTABLE)
        elif not honor_mode.sku:
            # If there are no course modes with SKUs, enroll the user without contacting the external API.
            msg = Messages.NO_SKU_ENROLLED.format(
                enrollment_mode=CourseMode.HONOR,
                course_id=course_id,
                username=user.username)
            log.debug(msg)
            self._enroll(course_key, user)
            return DetailResponse(msg)

        # Setup the API and report any errors if settings are not valid.
        try:
            api = EcommerceAPI()
        except InvalidConfigurationError:
            self._enroll(course_key, user)
            msg = Messages.NO_ECOM_API.format(username=user.username,
                                              course_id=unicode(course_key))
            log.debug(msg)
            return DetailResponse(msg)

        # Make the API call
        try:
            order_number, order_status, _body = api.create_order(
                user, honor_mode.sku)
            if order_status == OrderStatus.COMPLETE:
                msg = Messages.ORDER_COMPLETED.format(
                    order_number=order_number)
                log.debug(msg)
                return DetailResponse(msg)
            else:
                # TODO Before this functionality is fully rolled-out, this branch should be updated to NOT enroll the
                # user. Enrollments must be initiated by the E-Commerce API only.
                self._enroll(course_key, user)
                msg = u'Order %(order_number)s was received with %(status)s status. Expected %(complete_status)s. ' \
                      u'User %(username)s was enrolled in %(course_id)s by LMS.'
                msg_kwargs = {
                    'order_number': order_number,
                    'status': order_status,
                    'complete_status': OrderStatus.COMPLETE,
                    'username': user.username,
                    'course_id': course_id,
                }
                log.error(msg, msg_kwargs)

                msg = Messages.ORDER_INCOMPLETE_ENROLLED.format(
                    order_number=order_number)
                return DetailResponse(msg, status=HTTP_202_ACCEPTED)
        except ApiError as err:
            # The API will handle logging of the error.
            return InternalRequestErrorResponse(err.message)
Ejemplo n.º 4
0
class EcommerceAPITests(EcommerceApiTestMixin, TestCase):
    """ Tests for the E-Commerce API client. """

    SKU = "1234"

    def setUp(self):
        super(EcommerceAPITests, self).setUp()
        self.url = reverse("commerce:orders")
        self.user = UserFactory()
        self.api = EcommerceAPI()

    def test_constructor_url_strip(self):
        """ Verifies that the URL is stored with trailing slashes removed. """
        url = "http://example.com"
        api = EcommerceAPI(url, "edx")
        self.assertEqual(api.url, url)

        api = EcommerceAPI(url + "/", "edx")
        self.assertEqual(api.url, url)

    @override_settings(ECOMMERCE_API_URL=None, ECOMMERCE_API_SIGNING_KEY=None)
    def test_no_settings(self):
        """
        If the settings ECOMMERCE_API_URL and ECOMMERCE_API_SIGNING_KEY are invalid, the constructor should
        raise a ValueError.
        """
        self.assertRaises(InvalidConfigurationError, EcommerceAPI)

    @httpretty.activate
    def test_create_order(self):
        """ Verify the method makes a call to the E-Commerce API with the correct headers and data. """
        self._mock_ecommerce_api()
        number, status, body = self.api.create_order(self.user, self.SKU)

        # Validate the request sent to the E-Commerce API endpoint.
        request = httpretty.last_request()
        self.assertValidOrderRequest(request, self.user, self.ECOMMERCE_API_SIGNING_KEY, self.SKU)

        # Validate the data returned by the method
        self.assertEqual(number, self.ORDER_NUMBER)
        self.assertEqual(status, OrderStatus.COMPLETE)
        self.assertEqual(body, self.ECOMMERCE_API_SUCCESSFUL_BODY)

    @httpretty.activate
    @data(400, 401, 405, 406, 429, 500, 503)
    def test_create_order_with_invalid_http_status(self, status):
        """ If the E-Commerce API returns a non-200 status, the method should raise an InvalidResponseError. """
        self._mock_ecommerce_api(status=status, body=json.dumps({"user_message": "FAIL!"}))
        self.assertRaises(InvalidResponseError, self.api.create_order, self.user, self.SKU)

    @httpretty.activate
    def test_create_order_with_invalid_json(self):
        """ If the E-Commerce API returns un-parseable data, the method should raise an InvalidResponseError. """
        self._mock_ecommerce_api(body="TOTALLY NOT JSON!")
        self.assertRaises(InvalidResponseError, self.api.create_order, self.user, self.SKU)

    @httpretty.activate
    def test_create_order_with_timeout(self):
        """ If the call to the E-Commerce API times out, the method should raise a TimeoutError. """

        def request_callback(_request, _uri, _headers):
            """ Simulates API timeout """
            raise Timeout

        self._mock_ecommerce_api(body=request_callback)

        self.assertRaises(TimeoutError, self.api.create_order, self.user, self.SKU)
Ejemplo n.º 5
0
    def post(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """
        Attempt to create the order and enroll the user.
        """
        user = request.user
        valid, course_key, error = self._is_data_valid(request)
        if not valid:
            return DetailResponse(error, status=HTTP_406_NOT_ACCEPTABLE)

        # Don't do anything if an enrollment already exists
        course_id = unicode(course_key)
        enrollment = CourseEnrollment.get_enrollment(user, course_key)
        if enrollment and enrollment.is_active:
            msg = Messages.ENROLLMENT_EXISTS.format(course_id=course_id, username=user.username)
            return DetailResponse(msg, status=HTTP_409_CONFLICT)

        # If there is no honor course mode, this most likely a Prof-Ed course. Return an error so that the JS
        # redirects to track selection.
        honor_mode = CourseMode.mode_for_course(course_key, CourseMode.HONOR)

        if not honor_mode:
            msg = Messages.NO_HONOR_MODE.format(course_id=course_id)
            return DetailResponse(msg, status=HTTP_406_NOT_ACCEPTABLE)
        elif not honor_mode.sku:
            # If there are no course modes with SKUs, enroll the user without contacting the external API.
            msg = Messages.NO_SKU_ENROLLED.format(enrollment_mode=CourseMode.HONOR, course_id=course_id,
                                                  username=user.username)
            log.debug(msg)
            self._enroll(course_key, user)
            return DetailResponse(msg)

        # Setup the API and report any errors if settings are not valid.
        try:
            api = EcommerceAPI()
        except InvalidConfigurationError:
            self._enroll(course_key, user)
            msg = Messages.NO_ECOM_API.format(username=user.username, course_id=unicode(course_key))
            log.debug(msg)
            return DetailResponse(msg)

        # Make the API call
        try:
            order_number, order_status, _body = api.create_order(user, honor_mode.sku)
            if order_status == OrderStatus.COMPLETE:
                msg = Messages.ORDER_COMPLETED.format(order_number=order_number)
                log.debug(msg)
                return DetailResponse(msg)
            else:
                # TODO Before this functionality is fully rolled-out, this branch should be updated to NOT enroll the
                # user. Enrollments must be initiated by the E-Commerce API only.
                self._enroll(course_key, user)
                msg = u'Order %(order_number)s was received with %(status)s status. Expected %(complete_status)s. ' \
                      u'User %(username)s was enrolled in %(course_id)s by LMS.'
                msg_kwargs = {
                    'order_number': order_number,
                    'status': order_status,
                    'complete_status': OrderStatus.COMPLETE,
                    'username': user.username,
                    'course_id': course_id,
                }
                log.error(msg, msg_kwargs)

                msg = Messages.ORDER_INCOMPLETE_ENROLLED.format(order_number=order_number)
                return DetailResponse(msg, status=HTTP_202_ACCEPTED)
        except ApiError as err:
            # The API will handle logging of the error.
            return InternalRequestErrorResponse(err.message)
Ejemplo n.º 6
0
class EcommerceAPITests(EcommerceApiTestMixin, TestCase):
    """ Tests for the E-Commerce API client. """

    SKU = '1234'

    def setUp(self):
        super(EcommerceAPITests, self).setUp()
        self.url = reverse('commerce:orders')
        self.user = UserFactory()
        self.api = EcommerceAPI()

    def test_constructor_url_strip(self):
        """ Verifies that the URL is stored with trailing slashes removed. """
        url = 'http://example.com'
        api = EcommerceAPI(url, 'edx')
        self.assertEqual(api.url, url)

        api = EcommerceAPI(url + '/', 'edx')
        self.assertEqual(api.url, url)

    @override_settings(ECOMMERCE_API_URL=None, ECOMMERCE_API_SIGNING_KEY=None)
    def test_no_settings(self):
        """
        If the settings ECOMMERCE_API_URL and ECOMMERCE_API_SIGNING_KEY are invalid, the constructor should
        raise a ValueError.
        """
        self.assertRaises(InvalidConfigurationError, EcommerceAPI)

    @httpretty.activate
    def test_create_order(self):
        """ Verify the method makes a call to the E-Commerce API with the correct headers and data. """
        self._mock_ecommerce_api()
        number, status, body = self.api.create_order(self.user, self.SKU)

        # Validate the request sent to the E-Commerce API endpoint.
        request = httpretty.last_request()
        self.assertValidOrderRequest(request, self.user,
                                     self.ECOMMERCE_API_SIGNING_KEY, self.SKU)

        # Validate the data returned by the method
        self.assertEqual(number, self.ORDER_NUMBER)
        self.assertEqual(status, OrderStatus.COMPLETE)
        self.assertEqual(body, self.ECOMMERCE_API_SUCCESSFUL_BODY)

    @httpretty.activate
    @data(400, 401, 405, 406, 429, 500, 503)
    def test_create_order_with_invalid_http_status(self, status):
        """ If the E-Commerce API returns a non-200 status, the method should raise an InvalidResponseError. """
        self._mock_ecommerce_api(status=status,
                                 body=json.dumps({'user_message': 'FAIL!'}))
        self.assertRaises(InvalidResponseError, self.api.create_order,
                          self.user, self.SKU)

    @httpretty.activate
    def test_create_order_with_invalid_json(self):
        """ If the E-Commerce API returns un-parseable data, the method should raise an InvalidResponseError. """
        self._mock_ecommerce_api(body='TOTALLY NOT JSON!')
        self.assertRaises(InvalidResponseError, self.api.create_order,
                          self.user, self.SKU)

    @httpretty.activate
    def test_create_order_with_timeout(self):
        """ If the call to the E-Commerce API times out, the method should raise a TimeoutError. """
        def request_callback(_request, _uri, _headers):
            """ Simulates API timeout """
            raise Timeout

        self._mock_ecommerce_api(body=request_callback)

        self.assertRaises(TimeoutError, self.api.create_order, self.user,
                          self.SKU)