test_ok2/doc/en/example/multipython.py

73 lines
2.0 KiB
Python
Raw Normal View History

"""
module containing a parametrized tests testing cross-python
serialization via the pickle module.
"""
import shutil
import subprocess
2018-08-23 09:30:42 +08:00
import textwrap
import pytest
2019-06-03 06:20:00 +08:00
pythonlist = ["python3.5", "python3.6", "python3.7"]
2018-05-23 22:48:46 +08:00
@pytest.fixture(params=pythonlist)
def python1(request, tmp_path):
picklefile = tmp_path / "data.pickle"
return Python(request.param, picklefile)
2018-05-23 22:48:46 +08:00
@pytest.fixture(params=pythonlist)
def python2(request, python1):
return Python(request.param, python1.picklefile)
2018-05-23 22:48:46 +08:00
2019-06-03 06:32:00 +08:00
class Python:
def __init__(self, version, picklefile):
self.pythonpath = shutil.which(version)
if not self.pythonpath:
2020-10-03 04:16:22 +08:00
pytest.skip(f"{version!r} not found")
self.picklefile = picklefile
2018-05-23 22:48:46 +08:00
def dumps(self, obj):
dumpfile = self.picklefile.with_name("dump.py")
dumpfile.write_text(
2018-08-23 09:30:42 +08:00
textwrap.dedent(
2018-11-03 21:48:10 +08:00
r"""
2018-08-23 09:30:42 +08:00
import pickle
f = open({!r}, 'wb')
s = pickle.dump({!r}, f, protocol=2)
f.close()
""".format(
str(self.picklefile), obj
)
2018-05-23 22:48:46 +08:00
)
)
subprocess.check_call((self.pythonpath, str(dumpfile)))
def load_and_is_true(self, expression):
loadfile = self.picklefile.with_name("load.py")
loadfile.write_text(
2018-08-23 09:30:42 +08:00
textwrap.dedent(
2018-11-03 21:48:10 +08:00
r"""
2018-08-23 09:30:42 +08:00
import pickle
f = open({!r}, 'rb')
obj = pickle.load(f)
f.close()
res = eval({!r})
if not res:
raise SystemExit(1)
""".format(
str(self.picklefile), expression
)
2018-05-23 22:48:46 +08:00
)
)
print(loadfile)
subprocess.check_call((self.pythonpath, str(loadfile)))
2018-05-23 22:48:46 +08:00
2018-05-23 22:48:46 +08:00
@pytest.mark.parametrize("obj", [42, {}, {1: 3}])
def test_basic_objects(python1, python2, obj):
python1.dumps(obj)
2020-10-03 04:16:22 +08:00
python2.load_and_is_true(f"obj == {obj}")