Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print custom string upon unittest failure

I am using a for loop to iterate through a config file and pass variables within to a unit test.

for module in config:
        for testcase in config[module]:
            data = config[dict.keys(config)[0]][testcase]['foo']
            test_foo(self, data)

The problem with this method is the failures can be similar and are printed out at the end of testing. So there is no way to tell which variable it was that failed, only that n variables failed the test. Is there a way to print a custom string upon failure which would include the failed variable? Or perhaps there is even a better way to test the variables in my config file?

like image 868
mark mcmurray Avatar asked Jun 16 '15 10:06

mark mcmurray


People also ask

How do you handle exceptions in unit test Python?

There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.

What does Unittest main () do?

Internally, unittest. main() is using a few tricks to figure out the name of the module (source file) that contains the call to main() . It then imports this modules, examines it, gets a list of all classes and functions which could be tests (according the configuration) and then creates a test case for each of them.

Is Pytest better than Unittest?

Which is better – pytest or unittest? Although both the frameworks are great for performing testing in python, pytest is easier to work with. The code in pytest is simple, compact, and efficient. For unittest, we will have to import modules, create a class and define the testing functions within that class.

How are test failures identified in Python?

If the test fails, an exception will be raised with an explanatory message, and unittest will identify the test case as a failure. Any other exceptions will be treated as errors.


1 Answers

You can provide custom string in assert* method:

self.assertEqual('foo'.upper(), 'FOO', 'custom message')

This custom message will be printed on test failure

like image 79
Ivan Mushketyk Avatar answered Sep 20 '22 02:09

Ivan Mushketyk