How can I hide my stack frames in a TestCase subclass?

Peter Otten __peter__ at web.de
Fri Oct 5 04:12:54 EDT 2012


Manuel Pégourié-Gonnard wrote:

> Peter Otten scripsit :
> 
>> David Banks wrote:
>>
>>> Note that the custom assert method causes a stack trace with two frames,
>>> one inside the method itself, whereas the stock unittest method only has
>>> one frame, the relevant line in the user's code.  How can I apply this
>>> frame-hiding behaviour to my own method?
>>
>> Move MyTestCase in a separate module and define a global variable
>>
>> __unittest = True
>>
> Hum, is it documented somewhere? I can't find it in the doc. Also, I'm
> curious to know what kind of magic it's using.

I took advantage of the fact that Python is open source and had a look into 
the source code ;)

$ cd /usr/lib/python2.7/unittest
$ grep frame *.py -C2
...
result.py-
result.py-    def _is_relevant_tb_level(self, tb):
result.py:        return '__unittest' in tb.tb_frame.f_globals
result.py-
...

$ grep _is_relevant_tb_level *.py -C5
result.py-
result.py-    def _exc_info_to_string(self, err, test):
result.py-        """Converts a sys.exc_info()-style tuple of values into a 
string."""
result.py-        exctype, value, tb = err
result.py-        # Skip test runner traceback levels
result.py:        while tb and self._is_relevant_tb_level(tb):
result.py-            tb = tb.tb_next
result.py-
...

And so on. I actually used an editor, not grep -- but you get the idea.




More information about the Python-list mailing list