config.py 2.94 KB
Newer Older
1 2 3
"""
Fixture to manipulate configuration models.
"""
4 5 6 7 8
import requests
import re
import json

from lazy import lazy
9
from common.test.acceptance.fixtures import LMS_BASE_URL
10 11


12
class ConfigModelFixtureError(Exception):
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
    """
    Error occurred while configuring the stub XQueue.
    """
    pass


class ConfigModelFixture(object):
    """
    Configure a ConfigurationModel by using it's JSON api.
    """

    def __init__(self, api_base, configuration):
        """
        Configure a ConfigurationModel exposed at `api_base` to have the configuration `configuration`.
        """
        self._api_base = api_base
        self._configuration = configuration

    def install(self):
        """
        Configure the stub via HTTP.
        """
        url = LMS_BASE_URL + self._api_base

        response = self.session.post(
            url,
            data=json.dumps(self._configuration),
            headers=self.headers,
        )

        if not response.ok:
44
            raise ConfigModelFixtureError(
45 46 47 48 49 50 51 52 53 54 55
                "Could not configure url '{}'.  response: {} - {}".format(
                    self._api_base,
                    response,
                    response.content,
                )
            )

    @lazy
    def session_cookies(self):
        """
        Log in as a staff user, then return the cookies for the session (as a dict)
56
        Raises a `ConfigModelFixtureError` if the login fails.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        """
        return {key: val for key, val in self.session.cookies.items()}

    @lazy
    def headers(self):
        """
        Default HTTP headers dict.
        """
        return {
            'Content-type': 'application/json',
            'Accept': 'application/json',
            'X-CSRFToken': self.session_cookies.get('csrftoken', '')
        }

    @lazy
    def session(self):
        """
        Log in as a staff user, then return a `requests` `session` object for the logged in user.
        Raises a `StudioApiLoginError` if the login fails.
        """
        # Use auto-auth to retrieve the session for a logged in user
        session = requests.Session()
        response = session.get(LMS_BASE_URL + "/auto_auth?superuser=true")

        # Return the session from the request
        if response.ok:
            # auto_auth returns information about the newly created user
            # capture this so it can be used by by the testcases.
85 86
            user_pattern = re.compile(r'Logged in user {0} \({1}\) with password {2} and user_id {3}'.format(
                r'(?P<username>\S+)', r'(?P<email>[^\)]+)', r'(?P<password>\S+)', r'(?P<user_id>\d+)'))
87 88
            user_matches = re.match(user_pattern, response.text)
            if user_matches:
89
                self.user = user_matches.groupdict()  # pylint: disable=attribute-defined-outside-init
90 91 92 93 94

            return session

        else:
            msg = "Could not log in to use ConfigModel restful API.  Status code: {0}".format(response.status_code)
95
            raise ConfigModelFixtureError(msg)