According to the documentation I can set the verbosity level of a python unittest when calling unittest.main
, e.g.
unittest.main(verbosity=2)
How can I access this information within a unittest.TestCase
?
unittest. Verbosity enumeration class provides a means to specify the level of detail related to running tests. A higher value results in a higher level of detail.
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.
You can run by passing -v (verbose output) option which will enable a higher level of verbosity, and produce the output with more detailed results.
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.
The problem with any method based on patching or subclassing unittest.TestProgram
is that you have to get the patch in place before unittest.TestProgram
is started. But that's not going to be possible if your test case is being run via discovery:
python -m unittest discover -v
An approach that works in the discovery case is to use the inspect
module to search up the stack until a method on unittest.TestProgram
is found:
import inspect import unittest def unittest_verbosity(): """Return the verbosity setting of the currently running unittest program, or 0 if none is running. """ frame = inspect.currentframe() while frame: self = frame.f_locals.get('self') if isinstance(self, unittest.TestProgram): return self.verbosity frame = frame.f_back return 0
A way to achieve this is to subclass unittest.TestCase
and unittest.main
in a file. Here, you define a variable (e.g. globalverb
) the can be used globally or as class or Singleton, and then you override unittest.main
:
def main(*args, **kwargs): # parse arguments etc to get the verbosity number or whatever # ... # set this number to the defined class globalverb = verbose_number return unittest.main(*args, **kwargs)
Later, you subclass unittest.TestCase
:
class MyTestCase(unittest.TestCase): def my_special_function(self): if globalverb ...
With this approach it is possible to use the verbose,verbosity or any other number and information in a (derived) TestCase, from arguments passed on to a unittest.
Comments welcome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With