# Copyright (c) 2012, Simply Hired, Inc. All rights reserved.
from collections import OrderedDict
import json
import types
import unittest

from bs4 import BeautifulSoup

from django.test.client import Client

import serpng.jobs.services.search.search
import serpng.middleware

from jobs_app_test_common import *


def extend_cookies(cookies, more_cookies):
    """
    Extends cookies with more_cookies.
    
    This function is needed because the native "update"
    method for Python dictionaries is inadequate for cookie
    objects.
    
    In Python's Cookie module, when an assignment statement
    (e.g., cookies['a'] = 'b') is evaluated,
    the key-value pair is first converted to a Morsel object
    and then stored in the Cookie object internally as a list.
    
    This conversion is not performed when the "update" method is
    used, so please use this function instead of the native
    "udpate" method.
    """
    for key in more_cookies.keys():
        cookies[key] = more_cookies[key]
        
        
class JobsAppTest(unittest.TestCase):
    """Test that the correct HTML is generated by the jobs application"""
    pass


def __make_test_case_method(test_case):
    def TestCaseMethod(self):

        # Monkey patch the search service's call to get bridge response
        def get_response(bridge_url, headers):
            return test_case.bridge_response
        serpng.jobs.services.search.search._get_bridge_response = get_response

        # Get client
        # (See https://docs.djangoproject.com/en/1.5/topics/testing/overview/#module-django.test.client)
        c = Client()
        
        # Configure client with request cookies
        extend_cookies(c.cookies, test_case.query.request_cookies)
        
        # Get response from jobs application
        # (See https://docs.djangoproject.com/en/1.3/topics/testing/#testing-responses)
        app_response = c.get(test_case.query.request_query)
        
        # pylint: disable=E1103
        content = app_response.content
        soup = BeautifulSoup(content, "html5lib")
        
        # Call the test method on the feature under test, where,
        # if the feature tests pass, the test method returns a true value.
        self.assertTrue(test_case.test.test(query=test_case.query,
                                            bridge_response=test_case.bridge_response,
                                            app_response=app_response,
                                            soup=soup),
                        test_case.test.message)

    return TestCaseMethod
    
for test_case in test_cases_list:
    exec("JobsAppTest.test_%s = __make_test_case_method(test_case)" % test_case.name, globals(), locals())
