How to use pytest_assertion_pass 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.

__init__.py

Source: __init__.py Github

copy
1"""
2support for presenting detailed information in failing assertions.
3"""
4import sys
5
6from _pytest.assertion import rewrite
7from _pytest.assertion import truncate
8from _pytest.assertion import util
9
10
11def pytest_addoption(parser):
12    group = parser.getgroup("debugconfig")
13    group.addoption(
14        "--assert",
15        action="store",
16        dest="assertmode",
17        choices=("rewrite", "plain"),
18        default="rewrite",
19        metavar="MODE",
20        help="""Control assertion debugging tools.  'plain'
21                            performs no assertion debugging.  'rewrite'
22                            (the default) rewrites assert statements in
23                            test modules on import to provide assert
24                            expression information.""",
25    )
26    parser.addini(
27        "enable_assertion_pass_hook",
28        type="bool",
29        default=False,
30        help="Enables the pytest_assertion_pass hook."
31        "Make sure to delete any previously generated pyc cache files.",
32    )
33
34
35def register_assert_rewrite(*names):
36    """Register one or more module names to be rewritten on import.
37
38    This function will make sure that this module or all modules inside
39    the package will get their assert statements rewritten.
40    Thus you should make sure to call this before the module is
41    actually imported, usually in your __init__.py if you are a plugin
42    using a package.
43
44    :raise TypeError: if the given module names are not strings.
45    """
46    for name in names:
47        if not isinstance(name, str):
48            msg = "expected module names as *args, got {0} instead"
49            raise TypeError(msg.format(repr(names)))
50    for hook in sys.meta_path:
51        if isinstance(hook, rewrite.AssertionRewritingHook):
52            importhook = hook
53            break
54    else:
55        importhook = DummyRewriteHook()
56    importhook.mark_rewrite(*names)
57
58
59class DummyRewriteHook:
60    """A no-op import hook for when rewriting is disabled."""
61
62    def mark_rewrite(self, *names):
63        pass
64
65
66class AssertionState:
67    """State for the assertion plugin."""
68
69    def __init__(self, config, mode):
70        self.mode = mode
71        self.trace = config.trace.root.get("assertion")
72        self.hook = None
73
74
75def install_importhook(config):
76    """Try to install the rewrite hook, raise SystemError if it fails."""
77    config._assertstate = AssertionState(config, "rewrite")
78    config._assertstate.hook = hook = rewrite.AssertionRewritingHook(config)
79    sys.meta_path.insert(0, hook)
80    config._assertstate.trace("installed rewrite import hook")
81
82    def undo():
83        hook = config._assertstate.hook
84        if hook is not None and hook in sys.meta_path:
85            sys.meta_path.remove(hook)
86
87    config.add_cleanup(undo)
88    return hook
89
90
91def pytest_collection(session):
92    # this hook is only called when test modules are collected
93    # so for example not in the master process of pytest-xdist
94    # (which does not collect test modules)
95    assertstate = getattr(session.config, "_assertstate", None)
96    if assertstate:
97        if assertstate.hook is not None:
98            assertstate.hook.set_session(session)
99
100
101def pytest_runtest_setup(item):
102    """Setup the pytest_assertrepr_compare and pytest_assertion_pass hooks
103
104    The newinterpret and rewrite modules will use util._reprcompare if
105    it exists to use custom reporting via the
106    pytest_assertrepr_compare hook.  This sets up this custom
107    comparison for the test.
108    """
109
110    def callbinrepr(op, left, right):
111        """Call the pytest_assertrepr_compare hook and prepare the result
112
113        This uses the first result from the hook and then ensures the
114        following:
115        * Overly verbose explanations are truncated unless configured otherwise
116          (eg. if running in verbose mode).
117        * Embedded newlines are escaped to help util.format_explanation()
118          later.
119        * If the rewrite mode is used embedded %-characters are replaced
120          to protect later % formatting.
121
122        The result can be formatted by util.format_explanation() for
123        pretty printing.
124        """
125        hook_result = item.ihook.pytest_assertrepr_compare(
126            config=item.config, op=op, left=left, right=right
127        )
128        for new_expl in hook_result:
129            if new_expl:
130                new_expl = truncate.truncate_if_required(new_expl, item)
131                new_expl = [line.replace("\n", "\\n") for line in new_expl]
132                res = "\n~".join(new_expl)
133                if item.config.getvalue("assertmode") == "rewrite":
134                    res = res.replace("%", "%%")
135                return res
136
137    util._reprcompare = callbinrepr
138
139    if item.ihook.pytest_assertion_pass.get_hookimpls():
140
141        def call_assertion_pass_hook(lineno, expl, orig):
142            item.ihook.pytest_assertion_pass(
143                item=item, lineno=lineno, orig=orig, expl=expl
144            )
145
146        util._assertion_pass = call_assertion_pass_hook
147
148
149def pytest_runtest_teardown(item):
150    util._reprcompare = None
151    util._assertion_pass = None
152
153
154def pytest_sessionfinish(session):
155    assertstate = getattr(session.config, "_assertstate", None)
156    if assertstate:
157        if assertstate.hook is not None:
158            assertstate.hook.set_session(None)
159
160
161# Expose this plugin's implementation for the pytest_assertrepr_compare hook
162pytest_assertrepr_compare = util.assertrepr_compare
163
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)