How to get test name and test result during run time in pytest

非 Y 不嫁゛ 提交于 2019-12-06 01:06:47

问题


I want to get the test name and test result during runtime.

I have setup and tearDown methods in my script. In setup, I need to get the test name, and in tearDown I need to get the test result and test execution time.

Is there a way I can do this?


回答1:


You can, using a hook.

I have these files in my test directory:

./rest/
├── conftest.py
├── __init__.py
└── test_rest_author.py

In test_rest_author.py I have three functions, startup, teardown and test_tc15, but I only want to show the result and name for test_tc15.

Create a conftest.py file if you don't have one yet and add this:

import pytest
from _pytest.runner import runtestprotocol

def pytest_runtest_protocol(item, nextitem):
    reports = runtestprotocol(item, nextitem=nextitem)
    for report in reports:
        if report.when == 'call':
            print '\n%s --- %s' % (item.name, report.outcome)
    return True

The hook pytest_runtest_protocol implements the runtest_setup/call/teardown protocol for the given test item, including capturing exceptions and calling reporting hooks. It is called when any test finishes (like startup or teardown or your test).

If you run your script you can see the result and name of the test:

$ py.test ./rest/test_rest_author.py
====== test session starts ======
/test_rest_author.py::TestREST::test_tc15 PASSED
test_tc15 --- passed
======== 1 passed in 1.47 seconds =======

See also the docs on pytest hooks and conftest.py.




回答2:


unittest.TestCase.id() this will return the complete Details including class name , method name . From this we can extract test method name. Getting the results during can be achieved by checking if there any exceptions in executing the test. If the test fails then there wil be an exception if sys.exc_info() returns None then test is pass else test will be fail.



来源:https://stackoverflow.com/questions/14121657/how-to-get-test-name-and-test-result-during-run-time-in-pytest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!