Skip to content

Instantly share code, notes, and snippets.

@aguadopd
Created January 27, 2022 21:26
Show Gist options
  • Select an option

  • Save aguadopd/0e515ba2b709ec9cfccbd14acc4f4daa to your computer and use it in GitHub Desktop.

Select an option

Save aguadopd/0e515ba2b709ec9cfccbd14acc4f4daa to your computer and use it in GitHub Desktop.
Python 2.7: A decorator to print out which function is being tested, and its docstring
def log_header(test_function):
    """A decorator to print out which function is being tested, and its docstring"""
    function_name = test_function.__name__  # type: str
    function_docs_str = getdoc(test_function)  # type: Optional[str]
    function_docs = []  # type: List[str]
    if function_docs_str:
        function_docs = function_docs_str.splitlines()
    def wrapper(*args, **kwargs):
        rospy.loginfo("--------------------------------------------------------------------------------")
        rospy.loginfo("TEST: {}".format(function_name))
        if function_docs:
            rospy.loginfo("TEST: {}".format(function_docs[0]))
            for i in range(1,len(function_docs)):
                rospy.loginfo("      {}".format(function_docs[i]))
        return test_function(*args, **kwargs)
    return wrapper

Example usage, in a Python's unittest test function:

@log_header
def sample_test(self):
    """This is an easy test!
    Don't stop riding your bike.
    Will Argentina win the World Cup this year?
    """
    self.assertTrue(1+1 == 2)
    pass

Output:

2022-01-27 18:23:01,121 INFO               logger: --------------------------------------------------------------------------------
2022-01-27 18:23:01,126 INFO               logger: TEST: test_sample_test
2022-01-27 18:23:01,134 INFO               logger: TEST: This is an easy test!
2022-01-27 18:23:01,139 INFO               logger:       Don't stop riding your bike.
2022-01-27 18:23:01,142 INFO               logger:       Will Argentina win the World Cup this year?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment