I am looking for an elegant and Pythonic solution, to make tests save a log to a file, though only in case of test failure. I would like to keep things simple, and stick with Python's built-in logging
module.
My current solution is to use a wrapper function for assert of every test:
import unittest
class superTestCase(unittest.TestCase):
...
def assertWithLogging(self, assertion, assertion_arguments, expected_response, actual_response, *args):
try:
assertion(*assertion_arguments)
except AssertionError as ae:
test_name = inspect.stack()[1][3]
current_date_time = datetime.datetime.now().strftime("%Y.%m.%d %H-%M-%S")
logging.basicConfig(filename='tests/{}-{}-Failure.log'.format(current_date_time, test_name),
filemode='a',
format='%(message)s',
level=logging.DEBUG
)
logger = logging.getLogger('FailureLogger')
logger.debug('{} has failed'.format(test_name))
logger.debug('Expected response(s):')
logger.debug(expected_response)
logger.debug('Actual response:')
logger.debug(actual_response)
for arg in args:
logger.debug('Additionl logging info:')
logger.debug(arg)
raise ae
def testSomething(self):
...
self.assertWithLogging(self.assertEqual,
[expected_response, actual_response]
expected_response,
actual_response,
some_other_variable
)
Though it works as I expect it to, this solution seems clumsy and not too Pythonic, to me.
- What would be (Is there) a more elegant way to achieve the same result?
- What are the downsides of current approach?
You can use various logging mechanisms where in you can set the type of logs you want to achieve.
The one below will log only error messages.
This logs
msg
with levellogging.ERROR
on this logger. The arguments are interpreted as fordebug()
.