| 1 |
"""Module containing a parametrized tests testing cross-python serialization |
| 2 |
via the pickle module.""" |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import shutil |
| 7 |
import subprocess |
| 8 |
import textwrap |
| 9 |
|
| 10 |
import pytest |
| 11 |
|
| 12 |
|
| 13 |
pythonlist = ["python3.11", "python3.12", "python3.13"] |
| 14 |
|
| 15 |
|
| 16 |
@pytest.fixture(params=pythonlist) |
| 17 |
def python1(request, tmp_path): |
| 18 |
picklefile = tmp_path / "data.pickle" |
| 19 |
return Python(request.param, picklefile) |
| 20 |
|
| 21 |
|
| 22 |
@pytest.fixture(params=pythonlist) |
| 23 |
def python2(request, python1): |
| 24 |
return Python(request.param, python1.picklefile) |
| 25 |
|
| 26 |
|
| 27 |
class Python: |
| 28 |
def __init__(self, version, picklefile): |
| 29 |
self.pythonpath = shutil.which(version) |
| 30 |
if not self.pythonpath: |
| 31 |
pytest.skip(f"{version!r} not found") |
| 32 |
self.picklefile = picklefile |
| 33 |
|
| 34 |
def dumps(self, obj): |
| 35 |
dumpfile = self.picklefile.with_name("dump.py") |
| 36 |
dumpfile.write_text( |
| 37 |
textwrap.dedent( |
| 38 |
rf""" |
| 39 |
import pickle |
| 40 |
f = open({str(self.picklefile)!r}, 'wb') |
| 41 |
s = pickle.dump({obj!r}, f, protocol=2) |
| 42 |
f.close() |
| 43 |
""" |
| 44 |
) |
| 45 |
) |
| 46 |
subprocess.run((self.pythonpath, str(dumpfile)), check=True) |
| 47 |
|
| 48 |
def load_and_is_true(self, expression): |
| 49 |
loadfile = self.picklefile.with_name("load.py") |
| 50 |
loadfile.write_text( |
| 51 |
textwrap.dedent( |
| 52 |
rf""" |
| 53 |
import pickle |
| 54 |
f = open({str(self.picklefile)!r}, 'rb') |
| 55 |
obj = pickle.load(f) |
| 56 |
f.close() |
| 57 |
res = eval({expression!r}) |
| 58 |
if not res: |
| 59 |
raise SystemExit(1) |
| 60 |
""" |
| 61 |
) |
| 62 |
) |
| 63 |
print(loadfile) |
| 64 |
subprocess.run((self.pythonpath, str(loadfile)), check=True) |
| 65 |
|
| 66 |
|
| 67 |
@pytest.mark.parametrize("obj", [42, {}, {1: 3}]) |
| 68 |
def test_basic_objects(python1, python2, obj): |
| 69 |
python1.dumps(obj) |
| 70 |
python2.load_and_is_true(f"obj == {obj}") |