Pytest document 60 pytest Use of main()

preface

When running the use case of pytest, it is generally executed with the command line. Some little partners are not used to running the use case with the command line. They may be influenced by the unittest framework and used to writing a run under the root directory of the project_ all. Py file.
When running, run in python_ all. Py to execute test cases.

pytest.main()

Take a look at pytest The source code of main() and the content of main function

  • args passes a list object, which contains multiple command line parameters
  • plugins sends a list object, which is the plug-in to be registered during initialization
def main(args=None, plugins=None):
    """ return exit code, after performing an in-process test run.

    :arg args: list of command line arguments.

    :arg plugins: list of plugin objects to be auto-registered during
                  initialization.
    """
    from _pytest.main import EXIT_USAGEERROR

    try:
        try:
            config = _prepareconfig(args, plugins)
        except ConftestImportFailure as e:
            exc_info = ExceptionInfo(e.excinfo)
            tw = py.io.TerminalWriter(sys.stderr)
            tw.line(
                "ImportError while loading conftest '{e.path}'.".format(e=e), red=True
            )
            exc_info.traceback = exc_info.traceback.filter(filter_traceback)
            exc_repr = (
                exc_info.getrepr(style="short", chain=False)
                if exc_info.traceback
                else exc_info.exconly()
            )
            formatted_tb = safe_str(exc_repr)
            for line in formatted_tb.splitlines():
                tw.line(line.rstrip(), red=True)
            return 4
        else:
            try:
                return config.hook.pytest_cmdline_main(config=config)
            finally:
                config._ensure_unconfigure()
    except UsageError as e:
        tw = py.io.TerminalWriter(sys.stderr)
        for msg in e.args:
            tw.line("ERROR: {}\n".format(msg), red=True)
        return EXIT_USAGEERROR

Without any parameters, the execution effect is the same as that of running pytest command directly in cmd. By default, the test cases of all folders in the current directory and subdirectory are run

> pytest

run_all.py

Create a new run in the root directory of the project_ all. Py file

Just write a simple 2 lines of code

import pytest

# By default, the test cases of all folders in the current directory and subdirectory are run
pytest.main()

In this way, you can right-click in pycharm and run the test cases of all folders of the current directory and subdirectories by default without parameters

Operation with parameters

When running, you can also specify parameters to run

-s: Display the print/logging output in the program
-v: Enrich the information mode and output more detailed use case execution information
-k: Run a test case that contains a string. For example: pytest - K add XX Py means running XX Py contains the test case of add.
-q: Simple output mode, no environment information output
-x: Exit the test if a test case fails. It is very useful in the debugging phase. When the test case fails, you should debug it first rather than continue to execute the test case.

Run on the command line with the - s parameter

> pytest -s

So in pytest In main(), it is equivalent to

import pytest

# With - s parameter
pytest.main(["-s"])

When running with multiple parameters on the command line

> pytest -s -x

So in pytest In main(), it is equivalent to

import pytest

# With - s parameter
pytest.main(["-s", "-x"])

Specify a use case to run

Specify to run all the use cases under the cases/module1 folder. When the command line runs, first cd to the root directory of the project

>pytest cases/module1

So in pytest In main(), it is equivalent to

import pytest

# With - s parameter
pytest.main(["cases/module1"])

Run the specified cases / module1 / test_ x1. For all use cases under py, cd to the root directory of the project when running on the command line
'''

pytest cases/module1/test_x1.py
'''
So in pytest In main(), it is equivalent to

import pytest

# With - s parameter
pytest.main(["cases/module1/test_x1.py"])

Run the specified cases / module1 / test_x1. Test of a use case under PY_ x. When running from the command line, first cd to the root directory of the project
'''

pytest cases/module1/test_x1.py::test_x
'''
So in pytest In main(), it is equivalent to

import pytest

# With - s parameter
pytest.main(["cases/module1/test_x1.py::test_x"])

By comparing the above with the command line, pytest The use of main () is basically mastered

Use of plugins parameter

Generally, we write the code of the plug-in and put it in conf test Py will be found by pytest, if not written to conf test The plugin content of Py can be loaded through the plugins parameter

# run_all.py 
import pytest


# In run_ all. Custom plug-ins under PY
class MyPlugin(object):
    def pytest_sessionstart(self):
        print("*** test run start blog address https://www.cnblogs.com/yoyoketang/")


# plugins specifies to load the plug-in

pytest.main(["cases/module1"], plugins=[MyPlugin()])

After running, you will see the above content before the parameter use case starts

*** test run start blog address https://www.cnblogs.com/yoyoketang/
============================= test session starts =============================
platform win32 -- Python 3.6.6, pytest-4.5.0, py-1.9.0, pluggy-0.13.1
Test order randomisation NOT enabled. Enable with --random-order or --random-order-bucket=<bucket_type>
rootdir: D:\wangyiyun\web
plugins: repeat-0.8.0, rerunfailures-9.1, xdist-2.1.0
collected 5 items

cases\module1\test_x1.py .                                               [ 20%]
cases\module1\test_x2.py ....                                            [100%]

========================== 5 passed in 0.05 seconds ===========================

The plugins parameter is used to specify the plug-ins to be loaded, or you can specify multiple plug-ins.

Tags: pytest

Posted by echion on Fri, 06 May 2022 06:08:43 +0300