Python script для генерации отчета JUnit из другого результата тестирования

У меня есть приемочный тест, в результате получается обычный текст. Я хочу использовать Jenkins, чтобы показать результат, и формат JUnit подходит для меня.

Итак, я хочу проверить, существует ли существующий код python для генерации XML-формата JUnit, поэтому я могу просто добавить код разбора.

Связанный с этим вопрос.

Ответы

Ответ 1

Я нашел один модуль python https://bitbucket.org/db_atlass/python-junit-xml-output-module/, который соответствует моей потребности. спасибо Дэвид Блэк там

# code snippet for the usage
""" a short example of how to use this module """
test_cases = []
for i in range(0, 5):
    type_c = ""
    if i % 2 == 0:
        type_c = "failure"
    test_cases.append(TestCase(i, str(i) + "contents", type_c) )

junit_xml = JunitXml("demo test example", test_cases)

Ответ 2

Кори выше предложил junitxml, но я был в той же лодке, что и larrycai, в том, что я не пишу модульные тесты для проверки кода Python. Я пишу скрипты Python для тестирования системы черного ящика и просто хочу выводить результаты в JUnit XML без необходимости изобретать колесо.

Я кратко посмотрел на David Black "python junit xml output module", предложенный larrycai выше, но в итоге пошел с другим подобным пакетом. Не уверен, что лучше, так как я только пробовал этот, но в итоге он работал очень хорошо для меня.

Только по одному символу, но пакет "junit-xml": https://pypi.python.org/pypi/junit-xml/1.0

Остерегайтесь... примеры в его readme имеют ошибки и не работают. Я сообщил об ошибках в github (ссылка github, включенная на странице pypi). Кроме того, есть ошибка с его обработкой аргументов "prettyprint", но я расскажу вам о проблеме №3, о которой я также сообщил о github, в котором я включил свое исправление. Если вы загружаете источник, вы можете посмотреть его тесты test.py, но здесь также есть мой тест script, где я тестировал/экспериментировал с несколькими примерами (используя Python 3.3):

#junit-xml 1.0 downloaded from https://pypi.python.org/pypi/junit-xml
from junit_xml import TestSuite, TestCase

#Good article that has examples of how Jenkins parses JUnit XML to display output:
#http://nelsonwells.net/2012/09/how-jenkins-ci-parses-and-displays-junit-output/

#One version of JUnit XML schema: http://windyroad.org/dl/Open%20Source/JUnit.xsd


def testBasicToConsole():
    ''' Perform the very basic test with 1 suite and 1 test case, output to console.
        This is the example from the above referenced pypi webpage, but corrected to
        actually work.
    '''

    test_cases = [TestCase('Test1', 'some.class.name', 123.345, 'I am stdout!', 'I am stderr!')]
    ts = [TestSuite("my test suite", test_cases)]
    # pretty printing is on by default but can be disabled using prettyprint=False
    print(TestSuite.to_xml_string(ts, prettyprint=False))


def testBasicInfoToConsole():
    ''' Actually, even more basic than the test above, with classname, stdout, and stderror
        removed to demonstrate they are optional.  For system testing we often won't use them.
        Output to console.
    '''

    test_cases = [TestCase('PathCheck: ApplicationControl', '', .0523, '', '')]
    ts = [TestSuite("DirectorITG2", test_cases)]
    # pretty printing is on by default but can be disabled using prettyprint=False
    print(TestSuite.to_xml_string(ts))

def testFailureInfoToConsole():
    ''' 1 suite and test case with failure info added. Output to console.
    '''

    test_cases = TestCase('FileCheck: DesktopNotificationCenter', '', .0451, '', '')
    test_cases.add_failure_info('Invalid File \'DNC.exe\'.')
    ts = [TestSuite("DirectorITG2", [test_cases])]
    # pretty printing is on by default but can be disabled using prettyprint=False
    print(TestSuite.to_xml_string(ts))

def testMultiTestCasesToConsole():
    ''' Demonstrates a single test suite with multiple test cases, one of which
        has failure info. Output to console.
    '''

    test_cases = [TestCase('FileCheck: DesktopNotificationCenter', '', .0451, '', '')]
    test_cases.append(TestCase('FileCheck: PropertyServer', '', .0452, '', ''))
    test_cases[0].add_failure_info('Invalid File \'DNC.exe\'.')
    ts = [TestSuite("DirectorITG2", test_cases)]
    # pretty printing is on by default but can be disabled using prettyprint=False
    print(TestSuite.to_xml_string(ts))

def testMultiTestSuitesToConsole():
    ''' Demonstrates adding multiple test suites. Output to console.
    '''

    test_cases = [TestCase('FileCheck: DesktopNotificationCenter', '', .0451, '', '')]
    ts = [TestSuite("FileChecks", test_cases)]
    ts.append(TestSuite("ProcessChecks", [TestCase('ProcessCheck: ApplicationControl', '', 1.043, '', '')]))
    # pretty printing is on by default but can be disabled using prettyprint=False
    print(TestSuite.to_xml_string(ts))

def testMultiTestCasesToFile():
    ''' Demonstrates a single test suite with multiple test cases, one of which
        has failure info. Output to a file with PrettyPrint disabled (Jenkins-friendly).
    '''

    test_cases = [TestCase('DesktopNotificationCenter', 'Integration.FileCheck', .0451, '', '')]
    test_cases.append(TestCase('PropertyServer', 'Integration.FileCheck', .5678, '', ''))
    test_cases[0].add_failure_info('Invalid File \'DNC.exe\'.')
    ts = [TestSuite("GII_2013_R1", test_cases)]
    # open the file, then call the TestSuite to_File function with prettyprint off.
    # use raw text here to protect slashes from becoming escape characters
    with open(r'C:\Users\Administrator\.jenkins\workspace\IntegrationTests\FileCheck.xml', mode='a') as lFile:
        TestSuite.to_file(lFile, ts, prettyprint=False)
        lFile.close()


if __name__ == '__main__':
    ''' If this module is being run directly, run all of the example test functions.
        Test functions output JUnit XML for various scenarios to either screen (Console)
        or file.

    '''
    testBasicToConsole()
#    testBasicInfoToConsole()
#    testFailureInfoToConsole()
#    testMultiTestCasesToConsole()
#    testMultiTestSuitesToConsole()
#    testMultiTestCasesToFile()

else:
    ''' Function calls for an external run of this script.

    '''
    testMultiTestCasesToFile()

Ответ 3

вы можете использовать junitxml (репортер XML Python JUnit)

в PyPI: http://pypi.python.org/pypi/junitxml

если у вас есть стандартный набор тестов unittest, называемый suite. вы можете запустить его и записать результаты в xml файл следующим образом:

import junitxml

fp = file('results.xml', 'wb')
result = junitxml.JUnitXmlResult(fp)
result.startTestRun()
TestSuite(suite).run(result)
result.stopTestRun()

или открыть тесты и распечатать xml в stdout:

python -m junitxml.main discover

другой вариант - использовать nose и запустить ваш пакет с помощью:

nosetests --with-xunit

Ответ 4

collective.recipe.xmltestreport пакет рецептов сборки делает именно это. Он принимает вывод тестового бегуна и создает XML файл, подходящий для JUnit. Это, однако, buildout и использует zope.testrunner test пакет бегунов.

Если переключение на buildout не является для вас вариантом, вы можете изучить его исходный код, чтобы извлечь важные части.

Ответ 6

Хорошие ответы здесь: (есть много способов сделать это) Уроки Python в Дженкинсе?

IMHO лучшим способом является писать тесты python unittest и установить pytest (что-то вроде "yum install pytest" ), чтобы установить py.test. Затем выполните такие тесты: "py.test --junitxml results.xml test.py" . Вы можете запустить любой unittest python script и получить jUnit xml results.

https://docs.python.org/2.7/library/unittest.html

В конфигурации сборки jenkins Действия после сборки Добавьте отчет "Опубликовать отчет о результатах теста JUnit" с помощью result.xml и больше файлов результатов тестирования, которые вы создаете.