Martin of Hessle
Martin of Hessle

Reputation: 434

Writing a custom fail() method extending Python unittest

I have a custom specialisation of the Python unittest.TestCase class that includes automatic logging & provides customised business verification methods for use in a large number of variations of custom test scenarios.

I need a custom version of Python's unittest.TestCase.fail(...) that can function with the same message string as the logger, rather than the formatter.

I want to avoid having to define two versions of my message string like this:

def verifySomething(self, p_one:str, p_two:str):

    if self.someClass.some_command():
        self.test_result = TestResult.PASSED
        message = "my custom message : %s and %s - %s"
        self.logger.info(message, p_one, p_two, self.test_result)
    else:
        self.test_result = TestResult.FAILED
        message = "my custom message : {} and {} - {}".format(p_one, p_two, self.test_result)
        self.fail(message)

... and instead do something like this,

def verifySomething(self, p_one:str, p_two:str):
    message = "my custom message : %s and %s - %s"

    if self.someClass.some_command():
        self.test_result = TestResult.PASSED
        self.logger.info(message, p_one, p_two, self.test_result)
    else:
        self.test_result = TestResult.FAILED
        self.fail(message, p_one, p_two, self.test_result)

Note: This is a simplified example, and I've omitted Pre & Post Conditions for brevity.

Summary: How do I write a custom fail function that overrides Python's unittest.TestCase.fail(...) to do this?

Upvotes: 1

Views: 404

Answers (1)

chepner
chepner

Reputation: 532398

I would just pre-format the message:

def verifySomething(self, p_one:str, p_two:str):

    if self.someClass.some_command():
        self.test_result = TestResult.PASSED
        display_func = self.logger.info
    else:
        self.test_result = TestResult.FAILED
        display_func = self.fail

    message = "my custom message: {} and {} - {}".format(p_one, p_two, self.test_result)
    display_func(message)

There's no requirement that you take advantage of self.logger.info's ability to compose the final string for you.

Upvotes: 1

Related Questions