Python Unit Testing: Automatically Running the Debugger when a test fails

前端 未结 6 1762
日久生厌
日久生厌 2020-12-02 08:24

Is there a way to automatically start the debugger at the point at which a unittest fails?

Right now I am just using pdb.set_trace() manually, but this is very tedio

6条回答
  •  离开以前
    2020-12-02 09:12

    import unittest
    import sys
    import pdb
    import functools
    import traceback
    def debug_on(*exceptions):
        if not exceptions:
            exceptions = (AssertionError, )
        def decorator(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                try:
                    return f(*args, **kwargs)
                except exceptions:
                    info = sys.exc_info()
                    traceback.print_exception(*info) 
                    pdb.post_mortem(info[2])
            return wrapper
        return decorator
    
    class tests(unittest.TestCase):
        @debug_on()
        def test_trigger_pdb(self):
            assert 1 == 0
    

    I corrected the code to call post_mortem on the exception instead of set_trace.

提交回复
热议问题