Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

pytest

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?

like image 525
user1822881 Avatar asked Jan 02 '13 11:01

user1822881


People also ask

How does pytest know what tests to run?

With no arguments, pytest looks at the current working directory (or some other preconfigured directory) and all subdirectories for test files and runs the test code it finds.

How do I get a pytest report?

To generate HTML reports with the Pytest framework we have to install a plugin. For the installation, we shall execute the command pip install pytest-html. Next to generate the report we shall run the command pytest –html=report. html.

How do you run the same test multiple times in pytest?

Repeating a test Each test collected by pytest will be run count times. If you want to override default tests executions order, you can use --repeat-scope command line option with one of the next values: session , module , class or function (default). It behaves like a scope of the pytest fixture.

Which command will execute tests of the selected module pytest?

In general, pytest is invoked with the command pytest (see below for other ways to invoke pytest). This will execute all tests in all files whose names follow the form test_*. py or \*_test.py in the current directory and its subdirectories.


1 Answers

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.

like image 83
Сергей Богомаз Avatar answered Sep 22 '22 15:09

Сергей Богомаз