Сделайте вывод pytest таким же, как googletest?

#python #testing #pytest #googletest

Вопрос:

Я использую PyTest для тестирования кода на python. Поскольку я использую googletest для тестирования кода на C , мне нравится формат вывода googletest.

Мне интересно, можно ли сделать вывод pytest, как googletest? Строка вывода pytest слишком длинная, в то время как googletest короткий:

// пример pytest:

 (base) zz@home% pytest test_rle_v2.py
================================================================================== test session starts ===================================================================================
platform linux -- Python 3.8.1, pytest-6.0.1, py-1.9.0, pluggy-0.13.1
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/home/zz/work/test/learn-hp/.hypothesis/examples')
rootdir: /home/zz/work/test/learn-hp
plugins: env-0.6.2, hypothesis-4.38.0
collected 1 item                                                                                                                                                                         

test_rle_v2.py .                                                                                                                                                                   [100%]

=================================================================================== 1 passed in 0.46s ====================================================================================
 

// самый лучший пример googletest

 (base) zz@home% ./test_version 
[==========] Running 5 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 5 tests from VERSION
[ RUN      ] VERSION.str
[       OK ] VERSION.str (0 ms)
[ RUN      ] VERSION.parts
[       OK ] VERSION.parts (0 ms)
[ RUN      ] VERSION.metadata
[       OK ] VERSION.metadata (1 ms)
[ RUN      ] VERSION.atLeast
[       OK ] VERSION.atLeast (0 ms)
[ RUN      ] VERSION.hasFeature
[       OK ] VERSION.hasFeature (0 ms)
[----------] 5 tests from VERSION (1 ms total)

[----------] Global test environment tear-down
[==========] 5 tests from 1 test suite ran. (1 ms total)
[  PASSED  ] 5 tests.
 

Комментарии:

1. Вы можете, но это не односторонний подход и ничто не может вписаться в ответ. Вам нужно написать плагин, который заменит pytest стандартную TerminalReporter версию вашей пользовательской версией. Если вам нужен пример, pytest-sugar делает ли это IIRC.

Ответ №1:

После нескольких часов поисков и попыток я нашел conftest.py файл, необходимый для моей цели. В conftest.py, люди могут переопределить функцию pytest по умолчанию, т. Е. предоставив крючки.

Ниже приведен пример НЗП:

 # conftest.py

import os
import random

def pytest_runtest_call(item):
    item.add_report_section("call", "custom", " [ Run      ]  "   str(item))

def pytest_report_teststatus(report, config):
    #print(">>> outcome:", report.outcome)

    if report.when == 'call':
        # line = f' [ Run      ]  {report.nodeid}'
        # report.sections.append(('ChrisZZ', line))
        if (report.outcome == 'failed'):
            line = f' [   FAILED ]  {report.nodeid}'
            report.sections.append(('failed due to', line))

    if report.when == 'teardown':
        if (report.outcome == 'passed'):
            line = f' [       OK ]  {report.nodeid}'
            report.sections.append(('ChrisZZ', line))

def pytest_terminal_summary(terminalreporter, exitstatus, config):
    reports = terminalreporter.getreports('')
    content = os.linesep.join(text for report in reports for secname, text in report.sections)
    if content:
        terminalreporter.ensure_newline()
        #terminalreporter.section('', sep=' ', green=True, bold=True)
        #terminalreporter.section('My custom section2', sep='------]', green=True, bold=True, fullwidth=None)
        terminalreporter.line(content)