简体   繁体   中英

Pytest: Getting addresses of all tests

When I run pytest --collect-only to get the list of my tests, I get them in a format like <Function: test_whatever> . However, when I use pytest -k ... to run a specific test, I need to input the "address" of the test in the format foo::test_whatever . Is it possible to get a list of all the addresses of all the tests in the same format that -k takes?

The usage isn't as you specify it. From the documentation: http://doc.pytest.org/en/latest/usage.html

pytest -k stringexpr  # only run tests with names that match the
                      # "string expression", e.g. "MyClass and not method"
                      # will select TestMyClass.test_something
                      # but not TestMyClass.test_method_simple

so what you need to pass to '-k' is a string contained in all the callable functions you want to check (you can use logical operator between these strings). For your example (assuming all defs are prefixed by a foo:: :

pytest -k "foo::"

In conftest.py, you can override the 'collection' hooks to print information about collected test 'items'.

You may introduce your own command line option (like --collect-only). If this option is specified, print the test items (in whichever way you like) and exit.

Sample conftest.py below (tested locally):

import pytest

def pytest_addoption(parser):
    parser.addoption("--my_test_dump", action="store", default=None,
        help="Print test items in my custom format")

def pytest_collection_finish(session):
    if session.config.option.my_test_dump is not None:
        for item in session.items:
            print('{}::{}'.format(item.fspath, item.name))
        pytest.exit('Done!')

For more information on pytest hooks, see:

http://doc.pytest.org/en/latest/_modules/_pytest/hookspec.html

If you are using -k switch, you don't need to specify the full path separated by colons. If the path is unique, you can use just part of the path. You need full path of tests only when you are not using -k switch.

eg

pytest -k "unique_part_of_path_name"

for pytest tests/a/b/c.py::test_x , you can use pytest -k "a and b and c and x" .

You can use boolean logic for -k switch.

BTW, pytest --collect-only does give the file name of the test in <Module line just above the test names of the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM