How to use pytest_terminal_summary 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_plugin.py

Source: test_plugin.py Github

copy
1import warnings
2from unittest import mock
3
4from _pytest.config.argparsing import Parser
5from parameterized import parameterized
6from pytest import fixture
7
8from pytest_timer import plugin
9
10
11@fixture
12def tr_mock(mocker):
13    tr_mock = mocker.Mock()
14    tr_mock.config.option.timer_top_n = None
15    tr_mock.config.option.timer_filter = None
16    tr_mock.stats = {
17        "passed": [
18            mocker.Mock(when="call", nodeid="1", duration=3.01),
19            mocker.Mock(when="call", nodeid="2", duration=1.01),
20            mocker.Mock(when="call", nodeid="3", duration=0.99),
21        ],
22        "deselected": [
23            mocker.Mock(when="call", nodeid="4", duration=1.00),
24        ],
25    }
26    return tr_mock
27
28
29class TestPlugin:
30    @parameterized.expand(
31        [(1.000, "green"), (1.001, "yellow"), (3.000, "yellow"), (3.001, "red")]
32    )
33    def test_get_result_color(self, time_taken, color):
34        assert plugin._get_result_color(time_taken) == color
35
36    @parameterized.expand(
37        [
38            ("green", 1.000, False, "\x1b[32m1.0000s\x1b[0m"),
39            ("yellow", 1.001, False, "\x1b[33m1.0010s\x1b[0m"),
40            ("yellow", 3.000, False, "\x1b[33m3.0000s\x1b[0m"),
41            ("red", 3.001, False, "\x1b[31m3.0010s\x1b[0m"),
42            ("red", 3.001, True, "3.0010s"),
43        ]
44    )
45    def test_colored_time(self, color, time_taken, timer_no_color, expected_result):
46        assert (
47            plugin._colored_time(color, time_taken, timer_no_color) == expected_result
48        )
49
50    @parameterized.expand(
51        [
52            ("green", 1.000, False, "\x1b[32m1.0000s\x1b[0m"),
53            ("yellow", 1.001, False, "\x1b[33m1.0010s\x1b[0m"),
54            ("yellow", 3.000, False, "\x1b[33m3.0000s\x1b[0m"),
55            ("red", 3.001, False, "\x1b[31m3.0010s\x1b[0m"),
56            ("red", 3.001, True, "3.0010s"),
57        ]
58    )
59    def test_colored_time_colorama(
60        self, color, time_taken, timer_no_color, expected_result
61    ):
62        with mock.patch.object(plugin, "termcolor", None):
63            assert (
64                plugin._colored_time(color, time_taken, timer_no_color)
65                == expected_result
66            )
67
68    def test_pytest_addoption(self):
69        parser = Parser()
70
71        plugin.pytest_addoption(parser)
72
73        options = parser.getgroup("terminal reporting").options
74        assert options[0].names() == ["--timer-top-n"]
75        assert options[1].names() == ["--timer-no-color"]
76        assert options[2].names() == ["--timer-filter"]
77
78    def test_pytest_terminal_summary(self, mocker, tr_mock):
79        plugin.pytest_terminal_summary(terminalreporter=tr_mock)
80
81        tr_mock.write_line.assert_has_calls(
82            [
83                mocker.call("[success] 60.08% 1: 3.0100s"),
84                mocker.call("[success] 20.16% 2: 1.0100s"),
85                mocker.call("[success] 19.76% 3: 0.9900s"),
86            ]
87        )
88
89    def test_pytest_terminal_summary_with_timer_top_n(self, mocker, tr_mock):
90        tr_mock.config.option.timer_top_n = 1
91
92        plugin.pytest_terminal_summary(terminalreporter=tr_mock)
93
94        tr_mock.write_line.assert_has_calls(
95            [mocker.call("[success] 60.08% 1: 3.0100s")]
96        )
97
98    def test_pytest_terminal_summary_with_timer_filter_error(self, mocker, tr_mock):
99        tr_mock.config.option.timer_filter = "error"
100
101        plugin.pytest_terminal_summary(terminalreporter=tr_mock)
102
103        tr_mock.write_line.assert_has_calls(
104            [mocker.call("[success] 60.08% 1: 3.0100s")]
105        )
106
107    def test_pytest_terminal_summary_with_timer_filter_warning(self, mocker, tr_mock):
108        tr_mock.config.option.timer_filter = "warning"
109
110        plugin.pytest_terminal_summary(terminalreporter=tr_mock)
111
112        tr_mock.write_line.assert_has_calls(
113            [mocker.call("[success] 20.16% 2: 1.0100s")]
114        )
115
116    def test_pytest_terminal_summary_with_timer_filter_error_warning(
117        self, mocker, tr_mock
118    ):
119        tr_mock.config.option.timer_filter = "error,warning"
120
121        plugin.pytest_terminal_summary(terminalreporter=tr_mock)
122
123        tr_mock.write_line.assert_has_calls(
124            [
125                mocker.call("[success] 60.08% 1: 3.0100s"),
126                mocker.call("[success] 20.16% 2: 1.0100s"),
127            ]
128        )
129
130    def test_pytest_terminal_summary_with_user_warning(self, mocker, tr_mock):
131        warnings.warn("Test Warning to be used in tests")
132
133        plugin.pytest_terminal_summary(terminalreporter=tr_mock)
134
135        tr_mock.write_line.assert_has_calls(
136            [
137                mocker.call("[success] 60.08% 1: 3.0100s"),
138                mocker.call("[success] 20.16% 2: 1.0100s"),
139                mocker.call("[success] 19.76% 3: 0.9900s"),
140            ]
141        )
142
Full Screen

plugin_github_group.py

Source: plugin_github_group.py Github

copy
1#!/usr/bin/env python
2#
3# A library that provides a Python interface to the Telegram Bot API
4# Copyright (C) 2015-2021
5# Leandro Toledo de Souza <[email protected]>
6#
7# This program is free software: you can redistribute it and/or modify
8# it under the terms of the GNU Lesser Public License as published by
9# the Free Software Foundation, either version 3 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU Lesser Public License for more details.
16#
17# You should have received a copy of the GNU Lesser Public License
18# along with this program.  If not, see [http://www.gnu.org/licenses/].
19import _pytest.config
20import pytest
21
22fold_plugins = {'_cov': 'Coverage report', 'flaky': 'Flaky report'}
23
24
25def terminal_summary_wrapper(original, plugin_name):
26    text = fold_plugins[plugin_name]
27
28    def pytest_terminal_summary(terminalreporter):
29        terminalreporter.write(f'##[group] {text}\n')
30        original(terminalreporter)
31        terminalreporter.write('##[endgroup]')
32
33    return pytest_terminal_summary
34
35
36@pytest.mark.trylast
37def pytest_configure(config):
38    for hookimpl in config.pluginmanager.hook.pytest_terminal_summary._nonwrappers:
39        if hookimpl.plugin_name in fold_plugins.keys():
40            hookimpl.function = terminal_summary_wrapper(hookimpl.function, hookimpl.plugin_name)
41
42
43terminal = None
44previous_name = None
45
46
47def _get_name(location):
48    if location[0].startswith('tests/'):
49        return location[0][6:]
50    return location[0]
51
52
53@pytest.mark.trylast
54def pytest_itemcollected(item):
55    item._nodeid = item._nodeid.split('::', 1)[1]
56
57
58@pytest.hookimpl(hookwrapper=True, tryfirst=True)
59def pytest_runtest_protocol(item, nextitem):
60    # This is naughty but pytests' own plugins does something similar too, so who cares
61    global terminal
62    if terminal is None:
63        terminal = _pytest.config.create_terminal_writer(item.config)
64
65    global previous_name
66
67    name = _get_name(item.location)
68
69    if previous_name is None or previous_name != name:
70        previous_name = name
71        terminal.write(f'\n##[group] {name}')
72
73    yield
74
75    if nextitem is None or _get_name(nextitem.location) != name:
76        terminal.write('\n##[endgroup]')
77
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)