Debian Codegraph @

testing/web-platform/tests/tools/third_party/pytest/scripts/update-plugin-list.py

raw
1 # mypy: disallow-untyped-defs
2 import datetime
3 import pathlib
4 import re
5 from textwrap import dedent
6 from textwrap import indent
7 from typing import Any
8 from typing import Iterable
9 from typing import Iterator
10 from typing import TypedDict
11
12 import packaging.version
13 import platformdirs
14 from requests_cache import CachedResponse
15 from requests_cache import CachedSession
16 from requests_cache import OriginalResponse
17 from requests_cache import SQLiteCache
18 import tabulate
19 from tqdm import tqdm
20 import wcwidth
21
22
23 FILE_HEAD = r"""
24 .. Note this file is autogenerated by scripts/update-plugin-list.py - usually weekly via github action
25
26 .. _plugin-list:
27
28 Pytest Plugin List
29 ==================
30
31 Below is an automated compilation of ``pytest``` plugins available on `PyPI <https://pypi.org>`_.
32 It includes PyPI projects whose names begin with ``pytest-`` or ``pytest_`` and a handful of manually selected projects.
33 Packages classified as inactive are excluded.
34
35 For detailed insights into how this list is generated,
36 please refer to `the update script <https://github.com/pytest-dev/pytest/blob/main/scripts/update-plugin-list.py>`_.
37
38 .. warning::
39
40 Please be aware that this list is not a curated collection of projects
41 and does not undergo a systematic review process.
42 It serves purely as an informational resource to aid in the discovery of ``pytest`` plugins.
43
44 Do not presume any endorsement from the ``pytest`` project or its developers,
45 and always conduct your own quality assessment before incorporating any of these plugins into your own projects.
46
47
48 .. The following conditional uses a different format for this list when
49 creating a PDF, because otherwise the table gets far too wide for the
50 page.
51
52 """
53 DEVELOPMENT_STATUS_CLASSIFIERS = (
54 "Development Status :: 1 - Planning",
55 "Development Status :: 2 - Pre-Alpha",
56 "Development Status :: 3 - Alpha",
57 "Development Status :: 4 - Beta",
58 "Development Status :: 5 - Production/Stable",
59 "Development Status :: 6 - Mature",
60 "Development Status :: 7 - Inactive",
61 )
62 ADDITIONAL_PROJECTS = { # set of additional projects to consider as plugins
63 "logassert",
64 "logot",
65 "nuts",
66 "flask_fixture",
67 }
68
69
70 def escape_rst(text: str) -> str:
71 """Rudimentary attempt to escape special RST characters to appear as
72 plain text."""
73 text = (
74 text.replace("*", "\\*")
75 .replace("<", "\\<")
76 .replace(">", "\\>")
77 .replace("`", "\\`")
78 )
79 text = re.sub(r"_\b", "", text)
80 return text
81
82
83 def project_response_with_refresh(
84 session: CachedSession, name: str, last_serial: int
85 ) -> OriginalResponse | CachedResponse:
86 """Get a http cached pypi project
87
88 force refresh in case of last serial mismatch
89 """
90 response = session.get(f"https://pypi.org/pypi/{name}/json")
91 if int(response.headers.get("X-PyPI-Last-Serial", -1)) != last_serial:
92 response = session.get(f"https://pypi.org/pypi/{name}/json", refresh=True)
93 return response
94
95
96 def get_session() -> CachedSession:
97 """Configures the requests-cache session"""
98 cache_path = platformdirs.user_cache_path("pytest-plugin-list")
99 cache_path.mkdir(exist_ok=True, parents=True)
100 cache_file = cache_path.joinpath("http_cache.sqlite3")
101 return CachedSession(backend=SQLiteCache(cache_file))
102
103
104 def pytest_plugin_projects_from_pypi(session: CachedSession) -> dict[str, int]:
105 response = session.get(
106 "https://pypi.org/simple",
107 headers={"Accept": "application/vnd.pypi.simple.v1+json"},
108 refresh=True,
109 )
110 return {
111 name: p["_last-serial"]
112 for p in response.json()["projects"]
113 if (
114 (name := p["name"]).startswith(("pytest-", "pytest_"))
115 or name in ADDITIONAL_PROJECTS
116 )
117 }
118
119
120 class PluginInfo(TypedDict):
121 """Relevant information about a plugin to generate the summary."""
122
123 name: str
124 summary: str
125 last_release: str
126 status: str
127 requires: str
128
129
130 def iter_plugins() -> Iterator[PluginInfo]:
131 session = get_session()
132 name_2_serial = pytest_plugin_projects_from_pypi(session)
133
134 for name, last_serial in tqdm(name_2_serial.items(), smoothing=0):
135 response = project_response_with_refresh(session, name, last_serial)
136 if response.status_code == 404:
137 # Some packages, like pytest-azurepipelines42, are included in https://pypi.org/simple
138 # but return 404 on the JSON API. Skip.
139 continue
140 response.raise_for_status()
141 info = response.json()["info"]
142 if "Development Status :: 7 - Inactive" in info["classifiers"]:
143 continue
144 for classifier in DEVELOPMENT_STATUS_CLASSIFIERS:
145 if classifier in info["classifiers"]:
146 status = classifier[22:]
147 break
148 else:
149 status = "N/A"
150 requires = "N/A"
151 if info["requires_dist"]:
152 for requirement in info["requires_dist"]:
153 if re.match(r"pytest(?![-.\w])", requirement):
154 requires = requirement
155 break
156
157 def version_sort_key(version_string: str) -> Any:
158 """
159 Return the sort key for the given version string
160 returned by the API.
161 """
162 try:
163 return packaging.version.parse(version_string)
164 except packaging.version.InvalidVersion:
165 # Use a hard-coded pre-release version.
166 return packaging.version.Version("0.0.0alpha")
167
168 releases = response.json()["releases"]
169 for release in sorted(releases, key=version_sort_key, reverse=True):
170 if releases[release]:
171 release_date = datetime.date.fromisoformat(
172 releases[release][-1]["upload_time_iso_8601"].split("T")[0]
173 )
174 last_release = release_date.strftime("%b %d, %Y")
175 break
176 name = f':pypi:`{info["name"]}`'
177 summary = ""
178 if info["summary"]:
179 summary = escape_rst(info["summary"].replace("\n", ""))
180 yield {
181 "name": name,
182 "summary": summary.strip(),
183 "last_release": last_release,
184 "status": status,
185 "requires": requires,
186 }
187
188
189 def plugin_definitions(plugins: Iterable[PluginInfo]) -> Iterator[str]:
190 """Return RST for the plugin list that fits better on a vertical page."""
191 for plugin in plugins:
192 yield dedent(
193 f"""
194 {plugin['name']}
195 *last release*: {plugin["last_release"]},
196 *status*: {plugin["status"]},
197 *requires*: {plugin["requires"]}
198
199 {plugin["summary"]}
200 """
201 )
202
203
204 def main() -> None:
205 plugins = [*iter_plugins()]
206
207 reference_dir = pathlib.Path("doc", "en", "reference")
208
209 plugin_list = reference_dir / "plugin_list.rst"
210 with plugin_list.open("w", encoding="UTF-8") as f:
211 f.write(FILE_HEAD)
212 f.write(f"This list contains {len(plugins)} plugins.\n\n")
213 f.write(".. only:: not latex\n\n")
214
215 _ = wcwidth # reference library that must exist for tabulate to work
216 plugin_table = tabulate.tabulate(plugins, headers="keys", tablefmt="rst")
217 f.write(indent(plugin_table, " "))
218 f.write("\n\n")
219
220 f.write(".. only:: latex\n\n")
221 f.write(indent("".join(plugin_definitions(plugins)), " "))
222
223
224 if __name__ == "__main__":
225 main()