Debian Codegraph @

tests/test_backward_compat.py

raw
1 """Limited, best-effort test suite regarding cloudpickle backward-compat.
2
3 Cloudpickle does not officially support reading pickles files
4 generated with an older version of cloudpickle than the one used to read the
5 said pickles. However, this policy is not widely known among users that use
6 libraries that rely on cloudpickle such as mlflow, and is subject to confusion.
7
8 As a compromise, this script make sure cloudpickle is backward compatible for a
9 few canonical use cases. Cloudpicke backward-compatitibility support remains a
10 best-effort initiative.
11 """
12
13 import pickle
14
15 import pytest
16
17 from .generate_old_pickles import PICKLE_DIRECTORY
18
19
20 def load_obj(filename, check_deprecation_warning="auto"):
21 if check_deprecation_warning == "auto":
22 check_deprecation_warning = False
23 pickle_filepath = PICKLE_DIRECTORY / filename
24 if not pickle_filepath.exists():
25 pytest.skip(f"Could not find {str(pickle_filepath)}")
26 with open(str(pickle_filepath), "rb") as f:
27 if check_deprecation_warning:
28 msg = "A pickle file created using an old"
29 with pytest.warns(UserWarning, match=msg):
30 obj = pickle.load(f)
31 else:
32 obj = pickle.load(f)
33 return obj
34
35
36 def test_simple_func():
37 f = load_obj("simple_func.pkl")
38 assert f(1) == 2
39 assert f(1, 1) == 2
40 assert f(2, 2) == 4
41
42
43 def test_simple_class():
44 SimpleClass = load_obj("simple_class.pkl")
45 c = SimpleClass(1)
46 assert hasattr(c, "attribute")
47 assert c.attribute == 1
48
49 # test class tracking feature
50 assert SimpleClass is load_obj("simple_class.pkl")
51
52
53 def test_dynamic_module():
54 mod = load_obj("simple_module.pkl")
55 assert hasattr(mod, "f")
56 assert mod.f(1) == 2
57 assert mod.f(1, 1) == 2
58 assert mod.f(2, 2) == 4
59
60
61 def test_simple_enum():
62 enum = load_obj("simple_enum.pkl", check_deprecation_warning=False)
63 assert hasattr(enum, "RED")
64 assert enum.RED == 1
65 assert enum.BLUE == 2
66
67 # test enum tracking feature
68 new_enum = load_obj("simple_enum.pkl", check_deprecation_warning=False)
69 assert new_enum is enum
70
71
72 def test_complex_class():
73 SimpleClass = load_obj("class_with_type_hints.pkl")
74 c = SimpleClass(1)
75 assert hasattr(c, "attribute")
76 assert c.attribute == 1
77
78 # test class tracking feature
79 assert SimpleClass is load_obj("class_with_type_hints.pkl")
80
81
82 def test_complex_function():
83 MyClass, f = load_obj("function_with_type_hints.pkl")
84 assert len(f.__annotations__) > 0
85
86 a = MyClass(1)
87 b = MyClass(2)
88
89 c = f(a, b)
90 assert c.attribute == 3
91
92
93 def test_nested_function():
94 f = load_obj("nested_function.pkl")
95 assert f(41) == 42