Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/src/_pytest/pastebin.py

raw
1 # mypy: allow-untyped-defs
2 """Submit failure or test session information to a pastebin service."""
3
4 from io import StringIO
5 import tempfile
6 from typing import IO
7 from typing import Union
8
9 from _pytest.config import Config
10 from _pytest.config import create_terminal_writer
11 from _pytest.config.argparsing import Parser
12 from _pytest.stash import StashKey
13 from _pytest.terminal import TerminalReporter
14 import pytest
15
16
17 pastebinfile_key = StashKey[IO[bytes]]()
18
19
20 def pytest_addoption(parser: Parser) -> None:
21 group = parser.getgroup("terminal reporting")
22 group._addoption(
23 "--pastebin",
24 metavar="mode",
25 action="store",
26 dest="pastebin",
27 default=None,
28 choices=["failed", "all"],
29 help="Send failed|all info to bpaste.net pastebin service",
30 )
31
32
33 @pytest.hookimpl(trylast=True)
34 def pytest_configure(config: Config) -> None:
35 if config.option.pastebin == "all":
36 tr = config.pluginmanager.getplugin("terminalreporter")
37 # If no terminal reporter plugin is present, nothing we can do here;
38 # this can happen when this function executes in a worker node
39 # when using pytest-xdist, for example.
40 if tr is not None:
41 # pastebin file will be UTF-8 encoded binary file.
42 config.stash[pastebinfile_key] = tempfile.TemporaryFile("w+b")
43 oldwrite = tr._tw.write
44
45 def tee_write(s, **kwargs):
46 oldwrite(s, **kwargs)
47 if isinstance(s, str):
48 s = s.encode("utf-8")
49 config.stash[pastebinfile_key].write(s)
50
51 tr._tw.write = tee_write
52
53
54 def pytest_unconfigure(config: Config) -> None:
55 if pastebinfile_key in config.stash:
56 pastebinfile = config.stash[pastebinfile_key]
57 # Get terminal contents and delete file.
58 pastebinfile.seek(0)
59 sessionlog = pastebinfile.read()
60 pastebinfile.close()
61 del config.stash[pastebinfile_key]
62 # Undo our patching in the terminal reporter.
63 tr = config.pluginmanager.getplugin("terminalreporter")
64 del tr._tw.__dict__["write"]
65 # Write summary.
66 tr.write_sep("=", "Sending information to Paste Service")
67 pastebinurl = create_new_paste(sessionlog)
68 tr.write_line("pastebin session-log: %s\n" % pastebinurl)
69
70
71 def create_new_paste(contents: Union[str, bytes]) -> str:
72 """Create a new paste using the bpaste.net service.
73
74 :contents: Paste contents string.
75 :returns: URL to the pasted contents, or an error message.
76 """
77 import re
78 from urllib.parse import urlencode
79 from urllib.request import urlopen
80
81 params = {"code": contents, "lexer": "text", "expiry": "1week"}
82 url = "https://bpa.st"
83 try:
84 response: str = (
85 urlopen(url, data=urlencode(params).encode("ascii")).read().decode("utf-8")
86 )
87 except OSError as exc_info: # urllib errors
88 return "bad response: %s" % exc_info
89 m = re.search(r'href="/raw/(\w+)"', response)
90 if m:
91 return f"{url}/show/{m.group(1)}"
92 else:
93 return "bad response: invalid format ('" + response + "')"
94
95
96 def pytest_terminal_summary(terminalreporter: TerminalReporter) -> None:
97 if terminalreporter.config.option.pastebin != "failed":
98 return
99 if "failed" in terminalreporter.stats:
100 terminalreporter.write_sep("=", "Sending information to Paste Service")
101 for rep in terminalreporter.stats["failed"]:
102 try:
103 msg = rep.longrepr.reprtraceback.reprentries[-1].reprfileloc
104 except AttributeError:
105 msg = terminalreporter._getfailureheadline(rep)
106 file = StringIO()
107 tw = create_terminal_writer(terminalreporter.config, file)
108 rep.toterminal(tw)
109 s = file.getvalue()
110 assert len(s)
111 pastebinurl = create_new_paste(s)
112 terminalreporter.write_line(f"{msg} --> {pastebinurl}")