|
| 1 | +# This file is dual licensed under the terms of the Apache License, Version |
| 2 | +# 2.0, and the BSD License. See the LICENSE file in the root of this repository |
| 3 | +# for complete details. |
| 4 | + |
| 5 | +"""Generate or verify pickle files with packaging objects for cross-version testing. |
| 6 | +
|
| 7 | +Usage: |
| 8 | + python tasks/pickle_compat.py write <version> <output_dir> |
| 9 | + python tasks/pickle_compat.py verify [--version <version>] <pickle_file> |
| 10 | +
|
| 11 | +The ``write`` command generates a pickle file using the *currently installed* |
| 12 | +release of ``packaging``. ``<version>`` is recorded as metadata in the file |
| 13 | +(e.g. ``25.0``) so that ``verify`` can report what release created the pickle. |
| 14 | +
|
| 15 | +The ``verify`` command loads a pickle and checks that every object: |
| 16 | +
|
| 17 | +* has the expected type, |
| 18 | +* compares equal to a freshly constructed counterpart, and |
| 19 | +* round-trips through ``pickle.dumps`` / ``pickle.loads``. |
| 20 | +
|
| 21 | +When ``--version`` is supplied, ``verify`` also checks that the pickle was |
| 22 | +generated with that release of ``packaging``. |
| 23 | +""" |
| 24 | + |
| 25 | +from __future__ import annotations |
| 26 | + |
| 27 | +import argparse |
| 28 | +import importlib.metadata |
| 29 | +import pathlib |
| 30 | +import pickle |
| 31 | +import sys |
| 32 | +from typing import Any |
| 33 | + |
| 34 | +from packaging.markers import Marker |
| 35 | +from packaging.specifiers import Specifier, SpecifierSet |
| 36 | +from packaging.tags import Tag |
| 37 | +from packaging.version import Version |
| 38 | + |
| 39 | +_OBJECTS = { |
| 40 | + "version": [ |
| 41 | + Version("1.2.3"), |
| 42 | + Version("1!2.3.4a5.post6.dev7+zzz"), |
| 43 | + Version("0.1.0"), |
| 44 | + Version("2.0a1"), |
| 45 | + Version("1.0.post1"), |
| 46 | + Version("1.0.dev3"), |
| 47 | + ], |
| 48 | + "marker": [ |
| 49 | + Marker('python_version >= "3.8"'), |
| 50 | + Marker('os_name == "posix" and python_version >= "3.9"'), |
| 51 | + Marker('extra == "test"'), |
| 52 | + ], |
| 53 | + "specifier": [ |
| 54 | + Specifier(">=1.0.0"), |
| 55 | + Specifier("~=2.3"), |
| 56 | + Specifier("==1.2.*"), |
| 57 | + Specifier("!=2.0.0"), |
| 58 | + Specifier("<3.0"), |
| 59 | + Specifier(">1.0"), |
| 60 | + Specifier("<=2.0"), |
| 61 | + ], |
| 62 | + "specifierset": [ |
| 63 | + SpecifierSet(">=1.0.0,<2.0.0"), |
| 64 | + SpecifierSet("~=1.0,!=1.0.1"), |
| 65 | + SpecifierSet(">=3.0"), |
| 66 | + ], |
| 67 | + "tag": [ |
| 68 | + Tag("cp39", "cp39", "linux_x86_64"), |
| 69 | + Tag("py3", "none", "any"), |
| 70 | + Tag("cp310", "abi3", "manylinux_2_17_x86_64"), |
| 71 | + ], |
| 72 | +} |
| 73 | + |
| 74 | +_TYPE_CHECKS: dict[str, type[object]] = { |
| 75 | + "version": Version, |
| 76 | + "marker": Marker, |
| 77 | + "specifier": Specifier, |
| 78 | + "specifierset": SpecifierSet, |
| 79 | + "tag": Tag, |
| 80 | +} |
| 81 | + |
| 82 | + |
| 83 | +def write(version: str, output_dir: pathlib.Path) -> pathlib.Path: |
| 84 | + """Pickle a representative set of objects and write them to disk.""" |
| 85 | + installed = importlib.metadata.version("packaging") |
| 86 | + if version != installed: |
| 87 | + raise SystemExit( |
| 88 | + f"Requested packaging=={version} but the installed version is {installed}" |
| 89 | + ) |
| 90 | + |
| 91 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 92 | + path = output_dir / f"packaging_{version}_pickles.pkl" |
| 93 | + |
| 94 | + with open(path, "wb") as f: |
| 95 | + pickle.dump({"generated_with": version, "objects": _OBJECTS}, f) |
| 96 | + |
| 97 | + return path |
| 98 | + |
| 99 | + |
| 100 | +def verify(path: pathlib.Path, expected_version: str | None = None) -> int: |
| 101 | + """Load a pickle file and verify its contents. |
| 102 | +
|
| 103 | + Returns 0 on success, 1 on failure. |
| 104 | + """ |
| 105 | + with open(path, "rb") as f: |
| 106 | + data: dict[str, Any] = pickle.load(f) # noqa: S301 |
| 107 | + |
| 108 | + generated_with = data["generated_with"] |
| 109 | + objects: dict[str, list[Any]] = data["objects"] |
| 110 | + print(f"Verifying pickles generated with packaging=={generated_with}") |
| 111 | + |
| 112 | + if expected_version is not None and generated_with != expected_version: |
| 113 | + print( |
| 114 | + f"FAIL: generated_with ({generated_with}) != expected version " |
| 115 | + f"({expected_version})", |
| 116 | + file=sys.stderr, |
| 117 | + ) |
| 118 | + return 1 |
| 119 | + |
| 120 | + for kind, expected_cls in _TYPE_CHECKS.items(): |
| 121 | + loaded_list = objects[kind] |
| 122 | + expected_list = _OBJECTS[kind] |
| 123 | + |
| 124 | + if len(loaded_list) != len(expected_list): # type: ignore[arg-type] |
| 125 | + print( |
| 126 | + f"FAIL: {kind} list length mismatch " |
| 127 | + f"({len(loaded_list)} vs {len(expected_list)})", # type: ignore[arg-type] |
| 128 | + file=sys.stderr, |
| 129 | + ) |
| 130 | + return 1 |
| 131 | + |
| 132 | + for i, (loaded, expected) in enumerate( |
| 133 | + zip(loaded_list, expected_list) # type: ignore[call-overload] |
| 134 | + ): |
| 135 | + if type(loaded) is not expected_cls: |
| 136 | + print( |
| 137 | + f"FAIL: {kind}[{i}] is {type(loaded).__name__}, " |
| 138 | + f"expected {expected_cls.__name__}", |
| 139 | + file=sys.stderr, |
| 140 | + ) |
| 141 | + return 1 |
| 142 | + |
| 143 | + if loaded != expected: |
| 144 | + print( |
| 145 | + f"FAIL: {kind}[{i}] {loaded!r} != {expected!r}", |
| 146 | + file=sys.stderr, |
| 147 | + ) |
| 148 | + return 1 |
| 149 | + |
| 150 | + reloaded = pickle.loads(pickle.dumps(loaded)) # noqa: S301 |
| 151 | + if reloaded != expected: |
| 152 | + print( |
| 153 | + f"FAIL: {kind}[{i}] does not round-trip correctly", |
| 154 | + file=sys.stderr, |
| 155 | + ) |
| 156 | + return 1 |
| 157 | + |
| 158 | + print("All pickle verifications passed!") |
| 159 | + return 0 |
| 160 | + |
| 161 | + |
| 162 | +def main() -> int: |
| 163 | + parser = argparse.ArgumentParser(description=__doc__) |
| 164 | + subparsers = parser.add_subparsers(dest="command", required=True) |
| 165 | + |
| 166 | + write_parser = subparsers.add_parser("write", help="Generate a pickle file") |
| 167 | + write_parser.add_argument( |
| 168 | + "version", help="packaging version generating the pickles" |
| 169 | + ) |
| 170 | + write_parser.add_argument( |
| 171 | + "output_dir", |
| 172 | + type=pathlib.Path, |
| 173 | + default=pathlib.Path("."), |
| 174 | + nargs="?", |
| 175 | + ) |
| 176 | + |
| 177 | + verify_parser = subparsers.add_parser("verify", help="Verify a pickle file") |
| 178 | + verify_parser.add_argument( |
| 179 | + "pickle_file", type=pathlib.Path, help="path to the pickle file" |
| 180 | + ) |
| 181 | + verify_parser.add_argument( |
| 182 | + "--version", dest="expected_version", help="expected packaging version" |
| 183 | + ) |
| 184 | + |
| 185 | + args = parser.parse_args() |
| 186 | + |
| 187 | + if args.command == "write": |
| 188 | + path = write(args.version, args.output_dir) |
| 189 | + print(f"Wrote {path}") |
| 190 | + return 0 |
| 191 | + |
| 192 | + if args.command == "verify": |
| 193 | + return verify(args.pickle_file, args.expected_version) |
| 194 | + |
| 195 | + return 1 |
| 196 | + |
| 197 | + |
| 198 | +if __name__ == "__main__": |
| 199 | + sys.exit(main()) |
0 commit comments