Debian Codegraph @

src/_pytest/pastebin.py

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