Модульное тестирование Python: автоматический запуск отладчика при сбое теста - PullRequest
36 голосов
/ 09 декабря 2010

Есть ли способ автоматически запустить отладчик в тот момент, когда юнит-тест не проходит?

Сейчас я просто использую pdb.set_trace () вручную, но это очень утомительно, так как мне нужно добавитьэто каждый раз и вынимай в конце.

Например:

import unittest

class tests(unittest.TestCase):

    def setUp(self):
        pass

    def test_trigger_pdb(self):
        #this is the way I do it now
        try:
            assert 1==0
        except AssertionError:
            import pdb
            pdb.set_trace()

    def test_no_trigger(self):
        #this is the way I would like to do it:
        a=1
        b=2
        assert a==b
        #magically, pdb would start here
        #so that I could inspect the values of a and b

if __name__=='__main__':
    #In the documentation the unittest.TestCase has a debug() method
    #but I don't understand how to use it
    #A=tests()
    #A.debug(A)

    unittest.main()

Ответы [ 5 ]

36 голосов
/ 16 мая 2011

Я думаю, что вы ищете нос .Он работает как тестовый прогон для unittest .

. При возникновении ошибок вы можете попасть в отладчик с помощью следующей команды:

nosetests --pdb
23 голосов
/ 09 декабря 2010
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

Я исправил код для вызова post_mortem для исключения вместо set_trace.

3 голосов
/ 18 апреля 2016

Простой вариант - просто запустить тесты без сбора результатов и позволить первому исключению разбиться в стеке (для произвольной посмертной обработки), например,

unittest.findTestCases(__main__).debug()

Другой вариант: переопределить unittest.TextTestResult addError и addFailure в отладочном тестовом средстве для немедленной отладки post_mortem (до tearDown()) - или для сбора и обработки ошибок и трассировок расширенным способом.

(Не требует дополнительных каркасов или дополнительного декоратора для методов тестирования)

Базовый пример:

import unittest, pdb

class TC(unittest.TestCase):
    def testZeroDiv(self):
        1 / 0

def debugTestRunner(post_mortem=None):
    """unittest runner doing post mortem debugging on failing tests"""
    if post_mortem is None:
        post_mortem = pdb.post_mortem
    class DebugTestResult(unittest.TextTestResult):
        def addError(self, test, err):
            # called before tearDown()
            traceback.print_exception(*err)
            post_mortem(err[2])
            super(DebugTestResult, self).addError(test, err)
        def addFailure(self, test, err):
            traceback.print_exception(*err)
            post_mortem(err[2])
            super(DebugTestResult, self).addFailure(test, err)
    return unittest.TextTestRunner(resultclass=DebugTestResult)

if __name__ == '__main__':
    ##unittest.main()
    unittest.main(testRunner=debugTestRunner())
    ##unittest.main(testRunner=debugTestRunner(pywin.debugger.post_mortem))
    ##unittest.findTestCases(__main__).debug()
0 голосов
/ 05 сентября 2017

Вот встроенный, без дополнительных модулей, решение:

import unittest
import sys
import pdb

####################################
def ppdb(e=None):
    """conditional debugging
       use with:  `if ppdb(): pdb.set_trace()` 
    """
    return ppdb.enabled

ppdb.enabled = False
###################################


class SomeTest(unittest.TestCase):

    def test_success(self):
        try:
            pass
        except Exception, e:
            if ppdb(): pdb.set_trace()
            raise

    def test_fail(self):
        try:
            res = 1/0
            #note:  a `nosetests --pdb` run will stop after any exception
            #even one without try/except and ppdb() does not not modify that.
        except Exception, e:
            if ppdb(): pdb.set_trace()
            raise


if __name__ == '__main__':
    #conditional debugging, but not in nosetests
    if "--pdb" in sys.argv:
        print "pdb requested"
        ppdb.enabled = not sys.argv[0].endswith("nosetests")
        sys.argv.remove("--pdb")

    unittest.main()

вызовите его с помощью python myunittest.py --pdb, и он остановится.В противном случае это не так.

0 голосов
/ 18 марта 2016

Чтобы применить @ cmcginty's ответ к преемнику перенос 2 ( рекомендовано переносом доступно в DebianВ системах на основе apt-get install nose2) вы можете попасть в отладчик при сбоях и ошибках, вызвав

nose2

в своем тестовом каталоге.

Для этого вам нужно иметь подходящий .unittest.cfg в вашем домашнем каталоге или unittest.cfg в каталоге проекта;он должен содержать строки

[debugger]
always-on = True
errors-only = False
...