import unittest


def run_student_tests(print_feedback=True, show_traces=True,
                      success_required=True):
    """Run a suite of student submitted tests.

    Tests must be located in /autograder/source/student_tests/

    Args:
        print_feedback (bool): Print success or failure message
        show_traces (bool): Show failure/error stack traces
        success_required (bool): If True, this function will raise an
                                 AssertionError if any student tests fail.

    Returns:
        bool: True if all tests pass, False otherwise

    Raises:
        AssertionError if success_required is true and any test fails.

    """
    suite = unittest.defaultTestLoader.discover('student_tests',
                                                top_level_dir="./")
    result = unittest.TestResult()
    suite.run(result)

    succeeded = len(result.failures) == 0 and len(result.errors) == 0

    if not succeeded:
        if print_feedback:
            print(
                "It looks like your submission is not passing your own tests:")
            if len(result.errors) > 0:
                print("Errors:")
                for error in result.errors:
                    print(error[0]._testMethodName)
                    if show_traces:
                        print(error[1])
            if len(result.failures) > 0:
                print("Failures:")
                for failure in result.failures:
                    print(failure[0]._testMethodName)
                    if show_traces:
                        print(failure[1])
        if success_required:
            raise AssertionError("Student tests failed.")
    else:
        if print_feedback:
            print("Submission passes student tests.")

    return succeeded