How to use pytest_collection method in Pytest

Best Python code snippet using pytest

Run Pytest automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

test_func.py

Source: test_func.py Github

copy
1from my_module import *
2import pytest
3
4#file chua ham test phai co ten bat dau hoac ket thuc la test/_test
5
6@pytest.mark.parametrize("k",[4,8,10,15])
7def test_not_prime(k):
8    assert not_prime(k)==True
9
10@pytest.mark.parametrize("k",[0,-2])
11def test_prime(k):
12    assert not_prime(k)==False
13
14@pytest.mark.parametrize("number",[11,12,13,8])
15def test_module(number):
16    assert larger_than_ten(number) == True
17
18
19
20
21
22"""
23cu phap
24
25$pytest <duong dan den file test>/<ten file test>.py::<ten ham test>
26
27T:\Programming_\python\vscodes\pytest_collection\tamt\collections\test_func.py
28root folder
29    T:\Programming_\python\vscodes\pytest_collection
30relative path:
31    tamt\collections\test_func.py
32T:\Programming_\python\vscodes\pytest_collection
33"""
Full Screen

conftest.py

Source: conftest.py Github

copy
1import pytest
2from service.common.login import LoginPage
3
4"""
5function:每一个函数或方法都会调用
6class:每一个类调用一次,一个类可以有多个方法
7module:每一个.py文件调用一次,该文件内又有多个function和class
8session:是多个文件调用一次,可以跨.py文件调用,每个.py文件就是module
9"""
10
11
12@pytest.fixture()
13def session(page):
14    return LoginPage(page).login(
15        username='18886885',
16        password='[email protected]',
17        base_url='http://172.23.16.13:8888/oauth/login',
18    )
19
20
21def pytest_sessionstart():
22    ...
23
24
25def pytest_sessionfinish(session):
26    ...
27
28
29@pytest.hookimpl(hookwrapper=True)
30def pytest_collection():
31    yield
32
Full Screen

plugin.py

Source: plugin.py Github

copy
1import time
2import typing
3from datetime import timedelta
4
5import pytest
6
7
8class PytestExecutionTimer:
9    """
10    A timer for the phases of Pytest's execution.
11    Distinctly different from `--durations=N`
12    in that this reports times spent **outside** tests.
13
14    Not every hook is instrumented yet,
15    only the ones that I've observed causing slowdown.
16    More hook contributions are welcome!
17    """
18
19    durations: typing.Dict[str, float] = dict()
20
21    # === Initialization Hooks ===
22    # https://docs.pytest.org/en/stable/reference.html#initialization-hooks
23    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
24    def pytest_sessionstart(self, session):
25        start = time.time()
26        yield
27        end = time.time()
28        self.durations["pytest_sessionstart"] = end - start
29
30    # === Collection Hooks ===
31    # https://docs.pytest.org/en/stable/reference.html#collection-hooks
32    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
33    def pytest_collection(self, session):
34        start = time.time()
35        yield
36        end = time.time()
37        self.durations["pytest_collection"] = end - start
38
39    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
40    def pytest_collect_file(self, path, parent):
41        start = time.time()
42        yield
43        end = time.time()
44        self.durations[f"pytest_collect_file:{path}"] = end - start
45
46    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
47    def pytest_itemcollected(self, item):
48        start = time.time()
49        yield
50        end = time.time()
51        self.durations[f"pytest_itemcollected\t{item.name}"] = end - start
52
53    # === Run Test Hooks ===
54    # https://docs.pytest.org/en/stable/reference.html#test-running-runtest-hooks
55    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
56    def pytest_runtestloop(self, session):
57        """Should mimic the output of the total test time reported by pytest.
58        May not be necessary."""
59        start = time.time()
60        yield
61        end = time.time()
62        self.durations["pytest_runtestloop"] = end - start
63
64    # === Reporting Hooks ===
65    # https://docs.pytest.org/en/stable/reference.html#reporting-hooks
66    @pytest.hookimpl(hookwrapper=True, tryfirst=True)
67    def pytest_make_collect_report(self, collector):
68        """Despite being a Reporting hook, this fires during the Collection phase
69        and can find `test_*.py` level import slowdowns."""
70        start = time.time()
71        yield
72        end = time.time()
73        self.durations[f"pytest_make_collect_report\t{collector.nodeid}"] = end - start
74
75    def pytest_terminal_summary(self, terminalreporter, exitstatus, config):
76        """Where we emit our report."""
77        min_duration = config.option.minimum_duration_in_ms
78
79        terminalreporter.section("pytest-execution-timer")
80        terminalreporter.write_line(
81            f"Durations of pytest phases in seconds (min {min_duration}ms):"
82        )
83
84        for key, value in self.durations.items():
85            # Only show items that took longer than the configured value
86            if value > timedelta(milliseconds=min_duration).total_seconds():
87                terminalreporter.write_line(f"{value:.3f}\t{key}")
88
89
90def pytest_addoption(parser):
91    group = parser.getgroup("execution_timer")
92    group.addoption(
93        "--execution-timer",
94        action="store_true",
95        dest="execution_timer",
96        help="Enable collection of pytest phase execution timing.",
97    )
98    group.addoption(
99        "--minimum-duration",
100        action="store",
101        dest="minimum_duration_in_ms",
102        type=int,
103        default=100,
104        help="Minimum duration in milliseconds to show in the report.",
105    )
106
107
108def pytest_configure(config):
109    if config.option.execution_timer:
110        config.pluginmanager.register(PytestExecutionTimer())
111
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Python Tests on LambdaTest Cloud Grid

Execute automation tests with Pytest on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)