import unittest
import fnmatch


def find_tests(entity, pattern):
    """
    search for a unit tests with a matching wildcard pattern

    Looks for the first 'unittest.case.TestCase' instance where its identifier
    matches the provided wildcard pattern.

    Args:
        entity: the unit test entity to search for a pattern on
        pattern: the pattern

    Returns:
        a 2-tuple (list of tests, flag if a module error is detected)
    """
    found = []
    module_load_failure = False

    if isinstance(entity, unittest.case.TestCase):
        if fnmatch.fnmatch(entity.id(), '*{}*'.format(pattern)):
            found.append(entity)
        elif 'ModuleImportFailure' in entity.id():
            module_load_failure = True
    elif isinstance(entity, unittest.TestSuite):
        for subentity in entity:
            tests, fail = find_tests(subentity, pattern)
            if tests:
                found.extend(tests)
            if fail:
                module_load_failure = True

    return found, module_load_failure