__init__.py 4.16 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
""" Commerce app tests package. """
3 4
import datetime
import json
5

6
from django.conf import settings
7
from django.contrib.auth.models import User
8 9
from django.test import TestCase
from django.test.utils import override_settings
10
from freezegun import freeze_time
11 12 13 14
import httpretty
import jwt
import mock

15
from edx_rest_api_client import auth
16
from openedx.core.djangoapps.commerce.utils import ecommerce_api_client
17 18
from student.tests.factories import UserFactory

19
JSON = 'application/json'
20 21
TEST_PUBLIC_URL_ROOT = 'http://www.example.com'
TEST_API_URL = 'http://www-internal.example.com/api'
22 23 24 25 26 27 28 29 30 31
TEST_API_SIGNING_KEY = 'edx'
TEST_BASKET_ID = 7
TEST_ORDER_NUMBER = '100004'
TEST_PAYMENT_DATA = {
    'payment_processor_name': 'test-processor',
    'payment_form_data': {},
    'payment_page_url': 'http://example.com/pay',
}


32
@override_settings(ECOMMERCE_API_SIGNING_KEY=TEST_API_SIGNING_KEY, ECOMMERCE_API_URL=TEST_API_URL)
33
class EdxRestApiClientTest(TestCase):
34 35 36 37 38
    """ Tests to ensure the client is initialized properly. """

    TEST_USER_EMAIL = 'test@example.com'
    TEST_CLIENT_ID = 'test-client-id'

39
    def setUp(self):
40
        super(EdxRestApiClientTest, self).setUp()
41

42 43 44 45
        self.user = UserFactory()
        self.user.email = self.TEST_USER_EMAIL
        self.user.save()  # pylint: disable=no-member

46
    @httpretty.activate
47 48
    @freeze_time('2015-7-2')
    @override_settings(JWT_ISSUER='http://example.com/oauth', JWT_EXPIRATION=30)
49
    def test_tracking_context(self):
50 51 52 53
        """
        Ensure the tracking context is set up in the api client correctly and
        automatically.
        """
54

55 56 57
        # fake an ecommerce api request.
        httpretty.register_uri(
            httpretty.POST,
58
            '{}/baskets/1/'.format(TEST_API_URL),
59
            status=200, body='{}',
60
            adding_headers={'Content-Type': JSON}
61
        )
62

63
        mock_tracker = mock.Mock()
64
        mock_tracker.resolve_context = mock.Mock(return_value={'client_id': self.TEST_CLIENT_ID, 'ip': '127.0.0.1'})
65
        with mock.patch('openedx.core.djangoapps.commerce.utils.tracker.get_tracker', return_value=mock_tracker):
66
            ecommerce_api_client(self.user).baskets(1).post()
67 68 69 70

        # make sure the request's JWT token payload included correct tracking context values.
        actual_header = httpretty.last_request().headers['Authorization']
        expected_payload = {
71
            'username': self.user.username,
72
            'full_name': self.user.profile.name,
73
            'email': self.user.email,
74 75
            'iss': settings.JWT_ISSUER,
            'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=settings.JWT_EXPIRATION),
76
            'tracking_context': {
77
                'lms_user_id': self.user.id,  # pylint: disable=no-member
78
                'lms_client_id': self.TEST_CLIENT_ID,
79
                'lms_ip': '127.0.0.1',
80 81
            },
        }
82

83
        expected_header = 'JWT {}'.format(jwt.encode(expected_payload, TEST_API_SIGNING_KEY))
84
        self.assertEqual(actual_header, expected_header)
85 86 87 88 89 90 91 92 93 94 95 96 97 98

    @httpretty.activate
    def test_client_unicode(self):
        """
        The client should handle json responses properly when they contain
        unicode character data.

        Regression test for ECOM-1606.
        """
        expected_content = '{"result": "Préparatoire"}'
        httpretty.register_uri(
            httpretty.GET,
            '{}/baskets/1/order/'.format(TEST_API_URL),
            status=200, body=expected_content,
99
            adding_headers={'Content-Type': JSON},
100 101 102
        )
        actual_object = ecommerce_api_client(self.user).baskets(1).order.get()
        self.assertEqual(actual_object, {u"result": u"Préparatoire"})
103 104 105 106 107 108 109 110 111 112

    def test_client_with_user_without_profile(self):
        """
        Verify client initialize successfully for users having no profile.
        """
        worker = User.objects.create_user(username='test_worker', email='test@example.com')
        api_client = ecommerce_api_client(worker)

        self.assertEqual(api_client._store['session'].auth.__dict__['username'], worker.username)  # pylint: disable=protected-access
        self.assertIsNone(api_client._store['session'].auth.__dict__['full_name'])  # pylint: disable=protected-access