import sys
import unittest
import time
import traceback
import ConfigParser

CONF_SECTION_ALL = "*"

def parse_test_case_id(test_case):
    """Constructs TestCaseId object from the passed TestCase id."""
    test_id = test_case.id().split(".")
    return TestCaseId(test_id[0], test_id[1], test_id[2])

def get_test_item_id(test_item):
    """Constructs TestCaseId from the TestItem.
    It can create only partial objects if the test_item was not created from test function.
    """
    test_case_id = TestCaseId()
    
    if test_item.type == TestItemType.FUNCTION:
        test_case_id.function_name = test_item.name
        test_item = test_item.get_parent()
    if test_item.type == TestItemType.CLASS:
        test_case_id.class_name = test_item.name
        test_item = test_item.get_parent()
    if test_item.type == TestItemType.MODULE:
        test_case_id.module_name = test_item.name
    
    return test_case_id

def load_tests_configuration(path, ini_file="testconf.ini"):
    config_parser = ConfigParser.RawConfigParser()
    # must be case sensitive
    config_parser.optionxform = str
    filename = path + "/" + ini_file
    config_parser.read(filename)
    return config_parser

def _set_obj_attr(obj, k, v):
    """Dynamically casts the value of the attribute to the existing type.
    Applies it only if the cast was successful.
    Returns true if the attribute was successfully injected.
    """
    if hasattr(obj, k):
        val = getattr(obj, k)
        try:
            v = type(val)(v)
        except (TypeError, ValueError):
            return False
        setattr(obj, k, v)
        return True
    return False
    
def _apply_configuration(test_case, config):
    """Applies configuration to module and class objects of the test case.
    The configuration is changed only if it already exists in the object.
    Returns the set of configuration keys from the omni-section that were not applied.
    """
    not_applied = set()
    section = CONF_SECTION_ALL
    if config.has_section(section):
        test_module = sys.modules[test_case.__module__]
        for k, v in config.items(section):
            if not _set_obj_attr(test_module, k, v):
                not_applied.add(k)
    
    section = test_case.__module__
    if config.has_section(section):
        test_module = sys.modules[section]
        for k, v in config.items(section):
            if not _set_obj_attr(test_module, k, v):
                config.remove_option(section, k)
    
    section = test_case.__module__ + "." + test_case.__class__.__name__
    if config.has_section(section):
        for k, v in config.items(section):
            if not _set_obj_attr(test_case, k, v):
                config.remove_option(section, k)
    return not_applied
    
def build_tests_tree(path, config):
    """Uses unittest.TestLoader to discover all the python files in the
    current directory that start with 'test' prefix.
    Creates a tree of TestItem objects and returns its root.
    Also configures all test cases to have longMessage enabled by default.
    Additionally applies configuration to the test cases.
    """
    not_applied_keys = set(config.options(CONF_SECTION_ALL))
    test_case_id = TestCaseId()
    
    all_tests = unittest.TestLoader().discover(path)
    root_ti = TestItem("All tests", all_tests, TestItemType.ALL)
    for module_tests in all_tests:
        tests_class = []
        for class_tests in module_tests:
            tests_case = []
            for case_test in class_tests:
                test_case_id = parse_test_case_id(case_test)
                ti = TestItem(test_case_id.function_name, case_test, TestItemType.FUNCTION)
                tests_case.append(ti)
                ti.description = case_test.shortDescription()
                if ti.description == None:
                    ti.description = ""
                
                # always set longMessage to True to get more output with asserts
                setattr(case_test, 'longMessage', True)
                na_keys = _apply_configuration(case_test, config)
                not_applied_keys &= na_keys
            if tests_case:
                ti = TestItem(test_case_id.class_name, class_tests, TestItemType.CLASS)
                ti.add_children(tests_case)
                tests_class.append(ti)
        if tests_class:
            ti = TestItem(test_case_id.module_name, module_tests, TestItemType.MODULE)
            ti.add_children(tests_class)
            root_ti.add_child(ti)
    
    # remove not applied keys from omni-section
    for na_key in not_applied_keys:
        config.remove_option(CONF_SECTION_ALL, na_key)
    return root_ti

def aggregate_results(test_item):
    """Recursively aggregates results of the passed TestItem."""
    num_tests, num_passed, num_skipped, num_failed, num_errors = 0, 0, 0, 0, 0
    if test_item.type == TestItemType.FUNCTION:
        num_tests += 1
        if test_item.status:
            if test_item.status.status == TestStatus.PASS:
                num_passed += 1
            if test_item.status.status == TestStatus.SKIP:
                num_skipped += 1
            if test_item.status.status == TestStatus.FAIL:
                num_failed += 1
            if test_item.status.status == TestStatus.ERROR:
                num_errors += 1
    else:
        for ti in test_item.get_children():
            nt, np, ns, nf, ne = aggregate_results(ti)
            num_tests += nt
            num_passed += np
            num_skipped += ns
            num_failed += nf
            num_errors += ne
    return num_tests, num_passed, num_skipped, num_failed, num_errors

class TestExecutor(unittest.TestResult):
    """Works as aggregator for unittest results, but works on TestItem objects.
    Takes care of timing the tests and propagating results.
    """
    def __init__(self, root_test_item, callback=None):
        unittest.TestResult.__init__(self)
        self._root_test_item = root_test_item
        self._callback = callback
        self._start_time = 0
        self.successes = []
        self.buffer = True
    
    def startTestRun(self):
        super(TestExecutor, self).startTestRun()
        if self._callback:
            self._callback.on_start_all()
    
    def stopTestRun(self):
        super(TestExecutor, self).stopTestRun()
        if self._callback:
            self._callback.on_stop_all(self.shouldStop, self.testsRun, len(self.successes), len(self.skipped), len(self.failures), len(self.errors), len(self.unexpectedSuccesses), len(self.expectedFailures))
        
    def startTest(self, test):
        super(TestExecutor, self).startTest(test)
        if self._callback:
            self._callback.on_start(test)
        self._start_time = time.time()
    
    def stopTest(self, test):
        super(TestExecutor, self).stopTest(test)
        duration_time = time.time() - self._start_time
        
        tc_id = parse_test_case_id(test)
        test_item = self._find_test_item(self._root_test_item, tc_id)
        test_item.time = duration_time
        
        self._propagate_result_up(test_item)
        if self._callback:
            self._callback.on_stop(test)
    
    def addError(self, test, err):
        super(TestExecutor, self).addError(test, err)
        self._mirrorOutput = False
        self._update_test_case_status(test, self._parse_test_err(err, True), TestStatus(TestStatus.ERROR))
    
    def addFailure(self, test, err):
        super(TestExecutor, self).addFailure(test, err)
        self._mirrorOutput = False
        self._update_test_case_status(test, self._parse_test_err(err, False), TestStatus(TestStatus.FAIL))
    
    def addUnexpectedSuccess(self, test):
        super(TestExecutor, self).addUnexpectedSuccess(test)
        self._update_test_case_status(test, "", TestStatus(TestStatus.FAIL, "Unexpected Success"))
    
    def addSuccess(self, test):
        super(TestExecutor, self).addSuccess(test)
        self.successes.append(test)
        self._update_test_case_status(test, "", TestStatus(TestStatus.PASS))
    
    def addExpectedFailure(self, test, err):
        super(TestExecutor, self).addExpectedFailure(test, err)
        self._update_test_case_status(test, self._parse_test_err(err, False), TestStatus(TestStatus.PASS, "Expected Failure"))
    
    def addSkip(self, test, reason):
        super(TestExecutor, self).addSkip(test, reason)
        self._update_test_case_status(test, self.skipped[-1][1], TestStatus(TestStatus.SKIP))
    
    def run(self):
        test = self._root_test_item.executable
        
        self.startTestRun()
        try:
            test(self)
        finally:
            self.stopTestRun()
    
    def _find_test_item(self, test_item, tc_id):
        """Recursive function that does breadth first search for the TestItem
        with specified id that resides in the tree that is defined by passed test item.
        """
        if (test_item.type == TestItemType.FUNCTION) and (test_item.name == tc_id.function_name):
            return test_item
        
        if ((test_item.type == TestItemType.ALL) or
        ((test_item.type == TestItemType.MODULE) and (test_item.name == tc_id.module_name)) or
        ((test_item.type == TestItemType.CLASS) and (test_item.name == tc_id.class_name))):
            for ti in test_item.get_children():
                ret_ti = self._find_test_item(ti, tc_id)
                if ret_ti:
                    return ret_ti
        return None
        
    def _update_test_case_status(self, test_case, test_outcome, status):
        """Finds test item from the test_case id and updates its status and output values."""
        tc_id = parse_test_case_id(test_case)
        test_item = self._find_test_item(self._root_test_item, tc_id)
        test_item.status = status
        test_item.outcome = test_outcome
        test_item.output = sys.stdout.getvalue()

    def _propagate_result_up(self, test_item):
        """Propagates result of passed TestItem to its parents and updates them accordingly."""
        parent = test_item.get_parent()
        propagate_status = True
        while parent:
            parent.time = 0
            statuses = []
            for ti in parent.get_children():
                parent.time += ti.time
                statuses.append(ti.status)
            if None in statuses:
                propagate_status = False
            
            if propagate_status:
                act_statuses = [s.status for s in statuses]
                parent.status = TestStatus(TestStatus.PASS)
                if TestStatus.FAIL in act_statuses:
                    parent.status = TestStatus(TestStatus.FAIL)
                if TestStatus.ERROR in act_statuses:
                    parent.status = TestStatus(TestStatus.ERROR)
            parent = parent.get_parent()

    def _parse_test_err(self, err, stack_trace):
        """Creates more readable exception output by omitting stack trace if specified."""
        exc_text = []
        if stack_trace:
            exctype, value, tb = err
            exc_text = traceback.format_exception(exctype, value, tb)
        else:
            exctype, value, _ = err
            exc_text = traceback.format_exception_only(exctype, value)
        return ''.join(exc_text)

class TestCaseId(object):
    def __init__(self, module_name="", class_name="", function_name=""):
        self.module_name = module_name
        self.class_name = class_name
        self.function_name = function_name

    def __eq__(self, other):
        if isinstance(other, self.__class__):
            if (self.module_name == other.module_name) and (self.class_name == other.class_name) and (self.function_name == other.function_name):
                return True
        return False

    def __ne__(self, other):
        return not self.__eq__(other)
    
    def __str__(self):
        return self.module_name + "." + self.class_name + "." + self.function_name
    
    def is_superset_of(self, other):
        if isinstance(other, self.__class__):
            if not self.module_name:
                return True
            if not self.class_name:
                if self.module_name == other.module_name:
                    return True
            if not self.function_name:
                if self.module_name == other.module_name and self.class_name == other.class_name:
                    return True
            return self.__eq__(other)
        return False
    
class TestStatus(object):
    PASS = "Pass"
    SKIP = "Skip"
    FAIL = "Fail"
    ERROR = "Error"
    
    def __init__(self, status, details=None):
        self.status = status
        self.details = details
    
    def __str__(self):
        out_str = self.status
        if self.details:
            out_str += " (" + self.details + ")"
        return out_str

class TestItemType(object):
    ALL = 0
    MODULE = 1
    CLASS = 2
    FUNCTION = 3

class TestItem(object):
    """Core test item that holds all the important data for each of the tests.
    It also has pointers to its children and parent.
    """
    def __init__(self, name, executable, typ):
        self.name = name
        self.executable = executable
        self.status = None
        self.type = typ
        self.outcome = ""
        self.output = ""
        self.description = ""
        self.time = 0
        self._children = []
        self._parent = None
    
    def add_child(self, child):
        self._children.append(child)
        child._parent = self
    
    def add_children(self, children):
        for child in children:
            self.add_child(child)
    
    def get_children(self):
        return self._children
    
    def get_parent(self):
        return self._parent
