# -*- coding: utf-8 -*-
"""
Test pylti/test_common.py module
"""
import unittest
import semantic_version

import httpretty
import oauthlib.oauth1
from urlparse import urlparse, parse_qs
import urllib

import pylti
from pylti.common import (
    LTIOAuthDataStore,
    verify_request_common,
    LTIException,
    post_message,
    post_message2,
    generate_request_xml
)
from pylti.tests.util import TEST_CLIENT_CERT


class TestCommon(unittest.TestCase):
    """
    Tests for common.py
    """
    # pylint: disable=too-many-public-methods

    # Valid XML response from LTI 1.0 consumer
    expected_response = """<?xml version="1.0" encoding="UTF-8"?>
<imsx_POXEnvelopeResponse xmlns = "http://www.imsglobal.org/services/ltiv1p1\
/xsd/imsoms_v1p0">
    <imsx_POXHeader>
        <imsx_POXResponseHeaderInfo>
            <imsx_version>V1.0</imsx_version>
            <imsx_messageIdentifier>edX_fix</imsx_messageIdentifier>
            <imsx_statusInfo>
                <imsx_codeMajor>success</imsx_codeMajor>
                <imsx_severity>status</imsx_severity>
                <imsx_description>Score for StarX/StarX_DEMO/201X_StarX:\
edge.edx.org-i4x-StarX-StarX_DEMO-lti-40559041895b4065b2818c23b9cd9da8\
:18b71d3c46cb4dbe66a7c950d88e78ec is now 0.0</imsx_description>
                <imsx_messageRefIdentifier>
                </imsx_messageRefIdentifier>
            </imsx_statusInfo>
        </imsx_POXResponseHeaderInfo>
    </imsx_POXHeader>
    <imsx_POXBody><replaceResultResponse/></imsx_POXBody>
</imsx_POXEnvelopeResponse>
        """

    @staticmethod
    def test_version():
        """
        Will raise ValueError if not a semantic version
        """
        semantic_version.Version(pylti.VERSION)

    def test_lti_oauth_data_store(self):
        """
        Tests that LTIOAuthDataStore works
        """
        consumers = {
            "key1": {"secret": "secret1"},
            "key2": {"secret": "secret2"},
            "key3": {"secret": "secret3"},
            "keyNS": {"test": "test"},
            "keyWCert": {"secret": "secret", "cert": "cert"},
        }
        store = LTIOAuthDataStore(consumers)
        self.assertEqual(store.lookup_consumer("key1").secret, "secret1")
        self.assertEqual(store.lookup_consumer("key2").secret, "secret2")
        self.assertEqual(store.lookup_consumer("key3").secret, "secret3")
        self.assertEqual(store.lookup_cert("keyWCert"), "cert")
        self.assertIsNone(store.lookup_consumer("key4"))
        self.assertIsNone(store.lookup_cert("key4"))
        self.assertIsNone(store.lookup_consumer("keyNS"))
        self.assertIsNone(store.lookup_cert("keyNS"))

    def test_lti_oauth_data_store_no_consumers(self):
        """
        If consumers are not given it there are no consumer to return.