Debian Codegraph @

tests/cloudpickle_test.py

raw
1 import _collections_abc
2 import abc
3 import collections
4 import base64
5 import dataclasses
6 import functools
7 import io
8 import itertools
9 import logging
10 import math
11 import multiprocessing
12 from operator import itemgetter, attrgetter
13 import pickletools
14 import platform
15 import random
16 import re
17 import shutil
18 import subprocess
19 import sys
20 import tempfile
21 import textwrap
22 import types
23 import unittest
24 import weakref
25 import os
26 import enum
27 import typing
28 from functools import wraps
29 import pickle
30
31 import pytest
32 from pathlib import Path
33
34 try:
35 # try importing numpy and scipy. These are not hard dependencies and
36 # tests should be skipped if these modules are not available
37 import numpy as np
38 import scipy.special as spp
39 except (ImportError, RuntimeError):
40 np = None
41 spp = None
42
43 import cloudpickle
44 from cloudpickle import register_pickle_by_value
45 from cloudpickle import unregister_pickle_by_value
46 from cloudpickle import list_registry_pickle_by_value
47 from cloudpickle.cloudpickle import _should_pickle_by_reference
48 from cloudpickle.cloudpickle import _make_empty_cell
49 from cloudpickle.cloudpickle import _extract_class_dict, _whichmodule
50 from cloudpickle.cloudpickle import _lookup_module_and_qualname
51
52 from .testutils import subprocess_worker
53 from .testutils import subprocess_pickle_echo
54 from .testutils import subprocess_pickle_string
55 from .testutils import assert_run_python_script
56 from .testutils import check_deterministic_pickle
57
58
59 _TEST_GLOBAL_VARIABLE = "default_value"
60 _TEST_GLOBAL_VARIABLE2 = "another_value"
61
62
63 class RaiserOnPickle:
64 def __init__(self, exc):
65 self.exc = exc
66
67 def __reduce__(self):
68 raise self.exc
69
70
71 def pickle_depickle(obj, protocol=cloudpickle.DEFAULT_PROTOCOL):
72 """Helper function to test whether object pickled with cloudpickle can be
73 depickled with pickle
74 """
75 return pickle.loads(cloudpickle.dumps(obj, protocol=protocol))
76
77
78 def _escape(raw_filepath):
79 # Ugly hack to embed filepaths in code templates for windows
80 return raw_filepath.replace("\\", r"\\\\")
81
82
83 def _maybe_remove(list_, item):
84 try:
85 list_.remove(item)
86 except ValueError:
87 pass
88 return list_
89
90
91 def test_extract_class_dict():
92 class A(int):
93 """A docstring"""
94
95 def method(self):
96 return "a"
97
98 class B:
99 """B docstring"""
100
101 B_CONSTANT = 42
102
103 def method(self):
104 return "b"
105
106 class C(A, B):
107 C_CONSTANT = 43
108
109 def method_c(self):
110 return "c"
111
112 clsdict = _extract_class_dict(C)
113 expected_keys = ["C_CONSTANT", "__doc__", "method_c"]
114 # New attribute in Python 3.13 beta 1
115 # https://github.com/python/cpython/pull/118475
116 if sys.version_info >= (3, 13):
117 expected_keys.insert(2, "__firstlineno__")
118 assert list(clsdict.keys()) == expected_keys
119 assert clsdict["C_CONSTANT"] == 43
120 assert clsdict["__doc__"] is None
121 assert clsdict["method_c"](C()) == C().method_c()
122
123
124 class CloudPickleTest(unittest.TestCase):
125 protocol = cloudpickle.DEFAULT_PROTOCOL
126
127 def setUp(self):
128 self.tmpdir = tempfile.mkdtemp(prefix="tmp_cloudpickle_test_")
129
130 def tearDown(self):
131 shutil.rmtree(self.tmpdir)
132
133 @pytest.mark.skipif(
134 platform.python_implementation() != "CPython" or sys.version_info < (3, 8, 2),
135 reason="Underlying bug fixed upstream starting Python 3.8.2",
136 )
137 def test_reducer_override_reference_cycle(self):
138 # Early versions of Python 3.8 introduced a reference cycle between a
139 # Pickler and it's reducer_override method. Because a Pickler
140 # object references every object it has pickled through its memo, this
141 # cycle prevented the garbage-collection of those external pickled
142 # objects. See #327 as well as https://bugs.python.org/issue39492
143 # This bug was fixed in Python 3.8.2, but is still present using
144 # cloudpickle and Python 3.8.0/1, hence the skipif directive.
145 class MyClass:
146 pass
147
148 my_object = MyClass()
149 wr = weakref.ref(my_object)
150
151 cloudpickle.dumps(my_object)
152 del my_object
153 assert wr() is None, "'del'-ed my_object has not been collected"
154
155 def test_itemgetter(self):
156 d = range(10)
157 getter = itemgetter(1)
158
159 getter2 = pickle_depickle(getter, protocol=self.protocol)
160 self.assertEqual(getter(d), getter2(d))
161
162 getter = itemgetter(0, 3)
163 getter2 = pickle_depickle(getter, protocol=self.protocol)
164 self.assertEqual(getter(d), getter2(d))
165
166 def test_attrgetter(self):
167 class C:
168 def __getattr__(self, item):
169 return item
170
171 d = C()
172 getter = attrgetter("a")
173 getter2 = pickle_depickle(getter, protocol=self.protocol)
174 self.assertEqual(getter(d), getter2(d))
175 getter = attrgetter("a", "b")
176 getter2 = pickle_depickle(getter, protocol=self.protocol)
177 self.assertEqual(getter(d), getter2(d))
178
179 d.e = C()
180 getter = attrgetter("e.a")
181 getter2 = pickle_depickle(getter, protocol=self.protocol)
182 self.assertEqual(getter(d), getter2(d))
183 getter = attrgetter("e.a", "e.b")
184 getter2 = pickle_depickle(getter, protocol=self.protocol)
185 self.assertEqual(getter(d), getter2(d))
186
187 # Regression test for SPARK-3415
188 def test_pickling_file_handles(self):
189 out1 = sys.stderr
190 out2 = pickle.loads(cloudpickle.dumps(out1, protocol=self.protocol))
191 self.assertEqual(out1, out2)
192
193 def test_func_globals(self):
194 class Unpicklable:
195 def __reduce__(self):
196 raise Exception("not picklable")
197
198 global exit
199 exit = Unpicklable()
200
201 self.assertRaises(
202 Exception, lambda: cloudpickle.dumps(exit, protocol=self.protocol)
203 )
204
205 def foo():
206 sys.exit(0)
207
208 self.assertTrue("exit" in foo.__code__.co_names)
209 cloudpickle.dumps(foo)
210
211 def test_memoryview(self):
212 buffer_obj = memoryview(b"Hello")
213 self.assertEqual(
214 pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()
215 )
216
217 def test_dict_keys(self):
218 keys = {"a": 1, "b": 2}.keys()
219 results = pickle_depickle(keys)
220 self.assertEqual(results, keys)
221 assert isinstance(results, _collections_abc.dict_keys)
222
223 def test_dict_values(self):
224 values = {"a": 1, "b": 2}.values()
225 results = pickle_depickle(values)
226 self.assertEqual(sorted(results), sorted(values))
227 assert isinstance(results, _collections_abc.dict_values)
228
229 def test_dict_items(self):
230 items = {"a": 1, "b": 2}.items()
231 results = pickle_depickle(items)
232 self.assertEqual(results, items)
233 assert isinstance(results, _collections_abc.dict_items)
234
235 def test_odict_keys(self):
236 keys = collections.OrderedDict([("a", 1), ("b", 2)]).keys()
237 results = pickle_depickle(keys)
238 self.assertEqual(results, keys)
239 assert type(keys) is type(results)
240
241 def test_odict_values(self):
242 values = collections.OrderedDict([("a", 1), ("b", 2)]).values()
243 results = pickle_depickle(values)
244 self.assertEqual(list(results), list(values))
245 assert type(values) is type(results)
246
247 def test_odict_items(self):
248 items = collections.OrderedDict([("a", 1), ("b", 2)]).items()
249 results = pickle_depickle(items)
250 self.assertEqual(results, items)
251 assert type(items) is type(results)
252
253 def test_sliced_and_non_contiguous_memoryview(self):
254 buffer_obj = memoryview(b"Hello!" * 3)[2:15:2]
255 self.assertEqual(
256 pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()
257 )
258
259 def test_large_memoryview(self):
260 buffer_obj = memoryview(b"Hello!" * int(1e7))
261 self.assertEqual(
262 pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()
263 )
264
265 def test_lambda(self):
266 self.assertEqual(pickle_depickle(lambda: 1, protocol=self.protocol)(), 1)
267
268 def test_nested_lambdas(self):
269 a, b = 1, 2
270 f1 = lambda x: x + a # noqa: E731
271 f2 = lambda x: f1(x) // b # noqa: E731
272 self.assertEqual(pickle_depickle(f2, protocol=self.protocol)(1), 1)
273
274 def test_recursive_closure(self):
275 def f1():
276 def g():
277 return g
278
279 return g
280
281 def f2(base):
282 def g(n):
283 return base if n <= 1 else n * g(n - 1)
284
285 return g
286
287 g1 = pickle_depickle(f1(), protocol=self.protocol)
288 self.assertEqual(g1(), g1)
289
290 g2 = pickle_depickle(f2(2), protocol=self.protocol)
291 self.assertEqual(g2(5), 240)
292
293 def test_closure_none_is_preserved(self):
294 def f():
295 """A function with no closure cells"""
296
297 self.assertTrue(
298 f.__closure__ is None,
299 msg="f actually has closure cells!",
300 )
301
302 g = pickle_depickle(f, protocol=self.protocol)
303
304 self.assertTrue(
305 g.__closure__ is None,
306 msg="g now has closure cells even though f does not",
307 )
308
309 def test_empty_cell_preserved(self):
310 def f():
311 if False: # pragma: no cover
312 cell = None
313
314 def g():
315 cell # NameError, unbound free variable
316
317 return g
318
319 g1 = f()
320 with pytest.raises(NameError):
321 g1()
322
323 g2 = pickle_depickle(g1, protocol=self.protocol)
324 with pytest.raises(NameError):
325 g2()
326
327 def test_unhashable_closure(self):
328 def f():
329 s = {1, 2} # mutable set is unhashable
330
331 def g():
332 return len(s)
333
334 return g
335
336 g = pickle_depickle(f(), protocol=self.protocol)
337 self.assertEqual(g(), 2)
338
339 def test_class_no_firstlineno_deletion_(self):
340 # `__firstlineno__` is a new attribute of classes introduced in Python 3.13.
341 # This attribute used to be automatically deleted when unpickling a class as a
342 # consequence of cloudpickle setting a class's `__module__` attribute at
343 # unpickling time (see https://github.com/python/cpython/blob/73c152b346a18ed8308e469bdd232698e6cd3a63/Objects/typeobject.c#L1353-L1356).
344 # This deletion would cause tests like
345 # `test_deterministic_dynamic_class_attr_ordering_for_chained_pickling` to fail.
346 # This test makes sure that the attribute `__firstlineno__` is preserved
347 # across a cloudpickle roundtrip.
348
349 class A:
350 pass
351
352 if hasattr(A, "__firstlineno__"):
353 A_roundtrip = pickle_depickle(A, protocol=self.protocol)
354 assert hasattr(A_roundtrip, "__firstlineno__")
355 assert A_roundtrip.__firstlineno__ == A.__firstlineno__
356
357
358 def test_dynamically_generated_class_that_uses_super(self):
359 class Base:
360 def method(self):
361 return 1
362
363 class Derived(Base):
364 "Derived Docstring"
365
366 def method(self):
367 return super().method() + 1
368
369 self.assertEqual(Derived().method(), 2)
370
371 # Pickle and unpickle the class.
372 UnpickledDerived = pickle_depickle(Derived, protocol=self.protocol)
373 self.assertEqual(UnpickledDerived().method(), 2)
374
375 # We have special logic for handling __doc__ because it's a readonly
376 # attribute on PyPy.
377 self.assertEqual(UnpickledDerived.__doc__, "Derived Docstring")
378
379 # Pickle and unpickle an instance.
380 orig_d = Derived()
381 d = pickle_depickle(orig_d, protocol=self.protocol)
382 self.assertEqual(d.method(), 2)
383
384 def test_cycle_in_classdict_globals(self):
385 class C:
386 def it_works(self):
387 return "woohoo!"
388
389 C.C_again = C
390 C.instance_of_C = C()
391
392 depickled_C = pickle_depickle(C, protocol=self.protocol)
393 depickled_instance = pickle_depickle(C())
394
395 # Test instance of depickled class.
396 self.assertEqual(depickled_C().it_works(), "woohoo!")
397 self.assertEqual(depickled_C.C_again().it_works(), "woohoo!")
398 self.assertEqual(depickled_C.instance_of_C.it_works(), "woohoo!")
399 self.assertEqual(depickled_instance.it_works(), "woohoo!")
400
401 def test_locally_defined_function_and_class(self):
402 LOCAL_CONSTANT = 42
403
404 def some_function(x, y):
405 # Make sure the __builtins__ are not broken (see #211)
406 sum(range(10))
407 return (x + y) / LOCAL_CONSTANT
408
409 # pickle the function definition
410 result = pickle_depickle(some_function, protocol=self.protocol)(41, 1)
411 assert result == 1
412 result = pickle_depickle(some_function, protocol=self.protocol)(81, 3)
413 assert result == 2
414
415 hidden_constant = lambda: LOCAL_CONSTANT # noqa: E731
416
417 class SomeClass:
418 """Overly complicated class with nested references to symbols"""
419
420 def __init__(self, value):
421 self.value = value
422
423 def one(self):
424 return LOCAL_CONSTANT / hidden_constant()
425
426 def some_method(self, x):
427 return self.one() + some_function(x, 1) + self.value
428
429 # pickle the class definition
430 clone_class = pickle_depickle(SomeClass, protocol=self.protocol)
431 self.assertEqual(clone_class(1).one(), 1)
432 self.assertEqual(clone_class(5).some_method(41), 7)
433 clone_class = subprocess_pickle_echo(SomeClass, protocol=self.protocol)
434 self.assertEqual(clone_class(5).some_method(41), 7)
435
436 # pickle the class instances
437 self.assertEqual(pickle_depickle(SomeClass(1)).one(), 1)
438 self.assertEqual(pickle_depickle(SomeClass(5)).some_method(41), 7)
439 new_instance = subprocess_pickle_echo(SomeClass(5), protocol=self.protocol)
440 self.assertEqual(new_instance.some_method(41), 7)
441
442 # pickle the method instances
443 self.assertEqual(pickle_depickle(SomeClass(1).one)(), 1)
444 self.assertEqual(pickle_depickle(SomeClass(5).some_method)(41), 7)
445 new_method = subprocess_pickle_echo(
446 SomeClass(5).some_method, protocol=self.protocol
447 )
448 self.assertEqual(new_method(41), 7)
449
450 def test_partial(self):
451 partial_obj = functools.partial(min, 1)
452 partial_clone = pickle_depickle(partial_obj, protocol=self.protocol)
453 self.assertEqual(partial_clone(4), 1)
454
455 @pytest.mark.skipif(
456 platform.python_implementation() == "PyPy",
457 reason="Skip numpy and scipy tests on PyPy",
458 )
459 def test_ufunc(self):
460 # test a numpy ufunc (universal function), which is a C-based function
461 # that is applied on a numpy array
462
463 if np:
464 # simple ufunc: np.add
465 self.assertEqual(pickle_depickle(np.add, protocol=self.protocol), np.add)
466 else: # skip if numpy is not available
467 pass
468
469 if spp:
470 # custom ufunc: scipy.special.iv
471 self.assertEqual(pickle_depickle(spp.iv, protocol=self.protocol), spp.iv)
472 else: # skip if scipy is not available
473 pass
474
475 def test_loads_namespace(self):
476 obj = 1, 2, 3, 4
477 returned_obj = cloudpickle.loads(cloudpickle.dumps(obj, protocol=self.protocol))
478 self.assertEqual(obj, returned_obj)
479
480 def test_load_namespace(self):
481 obj = 1, 2, 3, 4
482 bio = io.BytesIO()
483 cloudpickle.dump(obj, bio)
484 bio.seek(0)
485 returned_obj = cloudpickle.load(bio)
486 self.assertEqual(obj, returned_obj)
487
488 def test_generator(self):
489 def some_generator(cnt):
490 yield from range(cnt)
491
492 gen2 = pickle_depickle(some_generator, protocol=self.protocol)
493
494 assert isinstance(gen2(3), type(some_generator(3)))
495 assert list(gen2(3)) == list(range(3))
496
497 def test_classmethod(self):
498 class A:
499 @staticmethod
500 def test_sm():
501 return "sm"
502
503 @classmethod
504 def test_cm(cls):
505 return "cm"
506
507 sm = A.__dict__["test_sm"]
508 cm = A.__dict__["test_cm"]
509
510 A.test_sm = pickle_depickle(sm, protocol=self.protocol)
511 A.test_cm = pickle_depickle(cm, protocol=self.protocol)
512
513 self.assertEqual(A.test_sm(), "sm")
514 self.assertEqual(A.test_cm(), "cm")
515
516 def test_bound_classmethod(self):
517 class A:
518 @classmethod
519 def test_cm(cls):
520 return "cm"
521
522 A.test_cm = pickle_depickle(A.test_cm, protocol=self.protocol)
523 self.assertEqual(A.test_cm(), "cm")
524
525 def test_method_descriptors(self):
526 f = pickle_depickle(str.upper)
527 self.assertEqual(f("abc"), "ABC")
528
529 def test_instancemethods_without_self(self):
530 class F:
531 def f(self, x):
532 return x + 1
533
534 g = pickle_depickle(F.f, protocol=self.protocol)
535 self.assertEqual(g.__name__, F.f.__name__)
536 # self.assertEqual(g(F(), 1), 2) # still fails
537
538 def test_module(self):
539 pickle_clone = pickle_depickle(pickle, protocol=self.protocol)
540 self.assertEqual(pickle, pickle_clone)
541
542 def _check_dynamic_module(self, mod):
543 mod = types.ModuleType("mod")
544 code = """
545 x = 1
546 def f(y):
547 return x + y
548
549 class Foo:
550 def method(self, x):
551 return f(x)
552 """
553 exec(textwrap.dedent(code), mod.__dict__)
554 mod2 = pickle_depickle(mod, protocol=self.protocol)
555 self.assertEqual(mod.x, mod2.x)
556 self.assertEqual(mod.f(5), mod2.f(5))
557 self.assertEqual(mod.Foo().method(5), mod2.Foo().method(5))
558
559 if platform.python_implementation() != "PyPy":
560 # XXX: this fails with excessive recursion on PyPy.
561 mod3 = subprocess_pickle_echo(mod, protocol=self.protocol)
562 self.assertEqual(mod.x, mod3.x)
563 self.assertEqual(mod.f(5), mod3.f(5))
564 self.assertEqual(mod.Foo().method(5), mod3.Foo().method(5))
565
566 # Test dynamic modules when imported back are singletons
567 mod1, mod2 = pickle_depickle([mod, mod])
568 self.assertEqual(id(mod1), id(mod2))
569
570 # Ensure proper pickling of mod's functions when module "looks" like a
571 # file-backed module even though it is not:
572 try:
573 sys.modules["mod"] = mod
574 depickled_f = pickle_depickle(mod.f, protocol=self.protocol)
575 self.assertEqual(mod.f(5), depickled_f(5))
576 finally:
577 sys.modules.pop("mod", None)
578
579 def test_dynamic_module(self):
580 mod = types.ModuleType("mod")
581 assert mod.__package__ is None
582 self._check_dynamic_module(mod)
583
584 def test_dynamic_module_no_package(self):
585 # non-regression test for #116
586 mod = types.ModuleType("mod")
587 del mod.__package__
588 assert not hasattr(mod, "__package__")
589 self._check_dynamic_module(mod)
590
591 def test_module_locals_behavior(self):
592 # Makes sure that a local function defined in another module is
593 # correctly serialized. This notably checks that the globals are
594 # accessible and that there is no issue with the builtins (see #211)
595
596 pickled_func_path = os.path.join(self.tmpdir, "local_func_g.pkl")
597
598 child_process_script = """
599 import pickle
600 import gc
601 with open("{pickled_func_path}", 'rb') as f:
602 func = pickle.load(f)
603
604 assert func(range(10)) == 45
605 """
606
607 child_process_script = child_process_script.format(
608 pickled_func_path=_escape(pickled_func_path)
609 )
610
611 try:
612 from .testutils import make_local_function
613
614 g = make_local_function()
615 with open(pickled_func_path, "wb") as f:
616 cloudpickle.dump(g, f, protocol=self.protocol)
617
618 assert_run_python_script(textwrap.dedent(child_process_script))
619
620 finally:
621 os.unlink(pickled_func_path)
622
623 def test_dynamic_module_with_unpicklable_builtin(self):
624 # Reproducer of https://github.com/cloudpipe/cloudpickle/issues/316
625 # Some modules such as scipy inject some unpicklable objects into the
626 # __builtins__ module, which appears in every module's __dict__ under
627 # the '__builtins__' key. In such cases, cloudpickle used to fail
628 # when pickling dynamic modules.
629 class UnpickleableObject:
630 def __reduce__(self):
631 raise ValueError("Unpicklable object")
632
633 mod = types.ModuleType("mod")
634
635 exec("f = lambda x: abs(x)", mod.__dict__)
636 assert mod.f(-1) == 1
637 assert "__builtins__" in mod.__dict__
638
639 unpicklable_obj = UnpickleableObject()
640 with pytest.raises(ValueError):
641 cloudpickle.dumps(unpicklable_obj)
642
643 # Emulate the behavior of scipy by injecting an unpickleable object
644 # into mod's builtins.
645 # The __builtins__ entry of mod's __dict__ can either be the
646 # __builtins__ module, or the __builtins__ module's __dict__. #316
647 # happens only in the latter case.
648 if isinstance(mod.__dict__["__builtins__"], dict):
649 mod.__dict__["__builtins__"]["unpickleable_obj"] = unpicklable_obj
650 elif isinstance(mod.__dict__["__builtins__"], types.ModuleType):
651 mod.__dict__["__builtins__"].unpickleable_obj = unpicklable_obj
652
653 depickled_mod = pickle_depickle(mod, protocol=self.protocol)
654 assert "__builtins__" in depickled_mod.__dict__
655
656 if isinstance(depickled_mod.__dict__["__builtins__"], dict):
657 assert "abs" in depickled_mod.__builtins__
658 elif isinstance(depickled_mod.__dict__["__builtins__"], types.ModuleType):
659 assert hasattr(depickled_mod.__builtins__, "abs")
660 assert depickled_mod.f(-1) == 1
661
662 # Additional check testing that the issue #425 is fixed: without the
663 # fix for #425, `mod.f` would not have access to `__builtins__`, and
664 # thus calling `mod.f(-1)` (which relies on the `abs` builtin) would
665 # fail.
666 assert mod.f(-1) == 1
667
668 def test_load_dynamic_module_in_grandchild_process(self):
669 # Make sure that when loaded, a dynamic module preserves its dynamic
670 # property. Otherwise, this will lead to an ImportError if pickled in
671 # the child process and reloaded in another one.
672
673 # We create a new dynamic module
674 mod = types.ModuleType("mod")
675 code = """
676 x = 1
677 """
678 exec(textwrap.dedent(code), mod.__dict__)
679
680 # This script will be ran in a separate child process. It will import
681 # the pickled dynamic module, and then re-pickle it under a new name.
682 # Finally, it will create a child process that will load the re-pickled
683 # dynamic module.
684 parent_process_module_file = os.path.join(
685 self.tmpdir, "dynamic_module_from_parent_process.pkl"
686 )
687 child_process_module_file = os.path.join(
688 self.tmpdir, "dynamic_module_from_child_process.pkl"
689 )
690 child_process_script = """
691 import pickle
692 import textwrap
693
694 import cloudpickle
695 from testutils import assert_run_python_script
696
697
698 child_of_child_process_script = {child_of_child_process_script}
699
700 with open('{parent_process_module_file}', 'rb') as f:
701 mod = pickle.load(f)
702
703 with open('{child_process_module_file}', 'wb') as f:
704 cloudpickle.dump(mod, f, protocol={protocol})
705
706 assert_run_python_script(textwrap.dedent(child_of_child_process_script))
707 """
708
709 # The script ran by the process created by the child process
710 child_of_child_process_script = """ '''
711 import pickle
712 with open('{child_process_module_file}','rb') as fid:
713 mod = pickle.load(fid)
714 ''' """
715
716 # Filling the two scripts with the pickled modules filepaths and,
717 # for the first child process, the script to be executed by its
718 # own child process.
719 child_of_child_process_script = child_of_child_process_script.format(
720 child_process_module_file=child_process_module_file
721 )
722
723 child_process_script = child_process_script.format(
724 parent_process_module_file=_escape(parent_process_module_file),
725 child_process_module_file=_escape(child_process_module_file),
726 child_of_child_process_script=_escape(child_of_child_process_script),
727 protocol=self.protocol,
728 )
729
730 try:
731 with open(parent_process_module_file, "wb") as fid:
732 cloudpickle.dump(mod, fid, protocol=self.protocol)
733
734 assert_run_python_script(textwrap.dedent(child_process_script))
735
736 finally:
737 # Remove temporary created files
738 if os.path.exists(parent_process_module_file):
739 os.unlink(parent_process_module_file)
740 if os.path.exists(child_process_module_file):
741 os.unlink(child_process_module_file)
742
743 def test_correct_globals_import(self):
744 def nested_function(x):
745 return x + 1
746
747 def unwanted_function(x):
748 return math.exp(x)
749
750 def my_small_function(x, y):
751 return nested_function(x) + y
752
753 b = cloudpickle.dumps(my_small_function, protocol=self.protocol)
754
755 # Make sure that the pickle byte string only includes the definition
756 # of my_small_function and its dependency nested_function while
757 # extra functions and modules such as unwanted_function and the math
758 # module are not included so as to keep the pickle payload as
759 # lightweight as possible.
760
761 assert b"my_small_function" in b
762 assert b"nested_function" in b
763
764 assert b"unwanted_function" not in b
765 assert b"math" not in b
766
767 def test_module_importability(self):
768 import pickle
769 import os.path
770 import collections
771 import collections.abc
772
773 assert _should_pickle_by_reference(pickle)
774 assert _should_pickle_by_reference(os.path) # fake (aliased) module
775 assert _should_pickle_by_reference(collections) # package
776 assert _should_pickle_by_reference(collections.abc) # module in package
777
778 dynamic_module = types.ModuleType("dynamic_module")
779 assert not _should_pickle_by_reference(dynamic_module)
780
781 if platform.python_implementation() == "PyPy":
782 import _codecs
783
784 assert _should_pickle_by_reference(_codecs)
785
786 # #354: Check that modules created dynamically during the import of
787 # their parent modules are considered importable by cloudpickle.
788 # See the mod_with_dynamic_submodule documentation for more
789 # details of this use case.
790 m = pytest.importorskip(
791 "_cloudpickle_testpkg.mod.dynamic_submodule"
792 ) # noqa F841
793 assert _should_pickle_by_reference(m)
794 assert pickle_depickle(m, protocol=self.protocol) is m
795
796 # Check for similar behavior for a module that cannot be imported by
797 # attribute lookup.
798 from _cloudpickle_testpkg.mod import dynamic_submodule_two as m2
799
800 assert _should_pickle_by_reference(m2)
801 assert pickle_depickle(m2, protocol=self.protocol) is m2
802
803 # Submodule_three is a dynamic module only importable via module lookup
804 with pytest.raises(ImportError):
805 import _cloudpickle_testpkg.mod.submodule_three # noqa
806 from _cloudpickle_testpkg.mod import submodule_three as m3
807
808 assert not _should_pickle_by_reference(m3)
809
810 # This module cannot be pickled using attribute lookup (as it does not
811 # have a `__module__` attribute like classes and functions.
812 assert not hasattr(m3, "__module__")
813 depickled_m3 = pickle_depickle(m3, protocol=self.protocol)
814 assert depickled_m3 is not m3
815 assert m3.f(1) == depickled_m3.f(1)
816
817 # Do the same for an importable dynamic submodule inside a dynamic
818 # module inside a file-backed module.
819 import _cloudpickle_testpkg.mod.dynamic_submodule.dynamic_subsubmodule as sm # noqa
820
821 assert _should_pickle_by_reference(sm)
822 assert pickle_depickle(sm, protocol=self.protocol) is sm
823
824 expected = "cannot check importability of object instances"
825 with pytest.raises(TypeError, match=expected):
826 _should_pickle_by_reference(object())
827
828 def test_Ellipsis(self):
829 self.assertEqual(Ellipsis, pickle_depickle(Ellipsis, protocol=self.protocol))
830
831 def test_NotImplemented(self):
832 ExcClone = pickle_depickle(NotImplemented, protocol=self.protocol)
833 self.assertEqual(NotImplemented, ExcClone)
834
835 def test_NoneType(self):
836 res = pickle_depickle(type(None), protocol=self.protocol)
837 self.assertEqual(type(None), res)
838
839 def test_EllipsisType(self):
840 res = pickle_depickle(type(Ellipsis), protocol=self.protocol)
841 self.assertEqual(type(Ellipsis), res)
842
843 def test_NotImplementedType(self):
844 res = pickle_depickle(type(NotImplemented), protocol=self.protocol)
845 self.assertEqual(type(NotImplemented), res)
846
847 def test_builtin_function(self):
848 # Note that builtin_function_or_method are special-cased by cloudpickle
849 # only in python2.
850
851 # builtin function from the __builtin__ module
852 assert pickle_depickle(zip, protocol=self.protocol) is zip
853
854 from os import mkdir
855
856 # builtin function from a "regular" module
857 assert pickle_depickle(mkdir, protocol=self.protocol) is mkdir
858
859 def test_builtin_type_constructor(self):
860 # This test makes sure that cloudpickling builtin-type
861 # constructors works for all python versions/implementation.
862
863 # pickle_depickle some builtin methods of the __builtin__ module
864 for t in list, tuple, set, frozenset, dict, object:
865 cloned_new = pickle_depickle(t.__new__, protocol=self.protocol)
866 assert isinstance(cloned_new(t), t)
867
868 # The next 4 tests cover all cases into which builtin python methods can
869 # appear.
870 # There are 4 kinds of method: 'classic' methods, classmethods,
871 # staticmethods and slotmethods. They will appear under different types
872 # depending on whether they are called from the __dict__ of their
873 # class, their class itself, or an instance of their class. This makes
874 # 12 total combinations.
875 # This discussion and the following tests are relevant for the CPython
876 # implementation only. In PyPy, there is no builtin method or builtin
877 # function types/flavours. The only way into which a builtin method can be
878 # identified is with it's builtin-code __code__ attribute.
879
880 def test_builtin_classicmethod(self):
881 obj = 1.5 # float object
882
883 bound_classicmethod = obj.hex # builtin_function_or_method
884 unbound_classicmethod = type(obj).hex # method_descriptor
885 clsdict_classicmethod = type(obj).__dict__["hex"] # method_descriptor
886
887 assert unbound_classicmethod is clsdict_classicmethod
888
889 depickled_bound_meth = pickle_depickle(
890 bound_classicmethod, protocol=self.protocol
891 )
892 depickled_unbound_meth = pickle_depickle(
893 unbound_classicmethod, protocol=self.protocol
894 )
895 depickled_clsdict_meth = pickle_depickle(
896 clsdict_classicmethod, protocol=self.protocol
897 )
898
899 # No identity on the bound methods they are bound to different float
900 # instances
901 assert depickled_bound_meth() == bound_classicmethod()
902 assert depickled_unbound_meth is unbound_classicmethod
903 assert depickled_clsdict_meth is clsdict_classicmethod
904
905 def test_builtin_classmethod(self):
906 obj = 1.5 # float object
907
908 bound_clsmethod = obj.fromhex # builtin_function_or_method
909 unbound_clsmethod = type(obj).fromhex # builtin_function_or_method
910
911 depickled_bound_meth = pickle_depickle(bound_clsmethod, protocol=self.protocol)
912 depickled_unbound_meth = pickle_depickle(
913 unbound_clsmethod, protocol=self.protocol
914 )
915
916 # float.fromhex takes a string as input.
917 arg = "0x1"
918
919 # Identity on both the bound and the unbound methods cannot be
920 # tested: the bound methods are bound to different objects, and the
921 # unbound methods are actually recreated at each call.
922 assert depickled_bound_meth(arg) == bound_clsmethod(arg)
923 assert depickled_unbound_meth(arg) == unbound_clsmethod(arg)
924
925 @pytest.mark.skipif(
926 (
927 sys.version_info >= (3, 10, 8)
928 and platform.python_implementation() == "CPython"
929 ),
930 reason=(
931 "CPython dropped support for pickling classmethod_descriptor,"
932 "https://github.com/python/cpython/issues/95196"
933 ),
934 )
935 def test_builtin_classmethod_descriptor(self):
936 # `classmethod_descriptor` is the analogue `classmethod` (used for
937 # pure Python classes) for builtin types. Until CPython 3.10.8,
938 # `classmethod_descriptor` implemented an (incorrect) reducer. After
939 # https://github.com/python/cpython/issues/95196 revealed its
940 # incorrectness, this reducer was dropped (and not fixed), on the
941 # ground that pickling its Pythonic equivalent, `classmethod`,
942 # was never supported in the first place.
943 # Note that cloudpickle supports pickling `classmethod` objects,
944 # but never patched pickle's incorrect `classmethod_descriptor`
945 # reducer: pickling `classmethod_descriptor` objects using cloudpickle
946 # has always been broken.
947 obj = 1.5 # float object
948
949 clsdict_clsmethod = type(obj).__dict__["fromhex"] # classmethod_descriptor
950
951 depickled_clsdict_meth = pickle_depickle(
952 clsdict_clsmethod, protocol=self.protocol
953 )
954
955 # float.fromhex takes a string as input.
956 arg = "0x1"
957 if platform.python_implementation() == "CPython":
958 # Roundtripping a classmethod_descriptor results in a
959 # builtin_function_or_method (CPython upstream issue).
960 assert depickled_clsdict_meth(arg) == clsdict_clsmethod(float, arg)
961 if platform.python_implementation() == "PyPy":
962 # builtin-classmethods are simple classmethod in PyPy (not
963 # callable). We test equality of types and the functionality of the
964 # __func__ attribute instead. We do not test the the identity of
965 # the functions as __func__ attributes of classmethods are not
966 # pickleable and must be reconstructed at depickling time.
967 assert type(depickled_clsdict_meth) is type(clsdict_clsmethod)
968 assert depickled_clsdict_meth.__func__(
969 float, arg
970 ) == clsdict_clsmethod.__func__(float, arg)
971
972 def test_builtin_slotmethod(self):
973 obj = 1.5 # float object
974
975 bound_slotmethod = obj.__repr__ # method-wrapper
976 unbound_slotmethod = type(obj).__repr__ # wrapper_descriptor
977 clsdict_slotmethod = type(obj).__dict__["__repr__"] # ditto
978
979 depickled_bound_meth = pickle_depickle(bound_slotmethod, protocol=self.protocol)
980 depickled_unbound_meth = pickle_depickle(
981 unbound_slotmethod, protocol=self.protocol
982 )
983 depickled_clsdict_meth = pickle_depickle(
984 clsdict_slotmethod, protocol=self.protocol
985 )
986
987 # No identity tests on the bound slotmethod are they are bound to
988 # different float instances
989 assert depickled_bound_meth() == bound_slotmethod()
990 assert depickled_unbound_meth is unbound_slotmethod
991 assert depickled_clsdict_meth is clsdict_slotmethod
992
993 @pytest.mark.skipif(
994 platform.python_implementation() == "PyPy",
995 reason="No known staticmethod example in the pypy stdlib",
996 )
997 def test_builtin_staticmethod(self):
998 obj = "foo" # str object
999
1000 bound_staticmethod = obj.maketrans # builtin_function_or_method
1001 unbound_staticmethod = type(obj).maketrans # ditto
1002 clsdict_staticmethod = type(obj).__dict__["maketrans"] # staticmethod
1003
1004 assert bound_staticmethod is unbound_staticmethod
1005
1006 depickled_bound_meth = pickle_depickle(
1007 bound_staticmethod, protocol=self.protocol
1008 )
1009 depickled_unbound_meth = pickle_depickle(
1010 unbound_staticmethod, protocol=self.protocol
1011 )
1012 depickled_clsdict_meth = pickle_depickle(
1013 clsdict_staticmethod, protocol=self.protocol
1014 )
1015
1016 assert depickled_bound_meth is bound_staticmethod
1017 assert depickled_unbound_meth is unbound_staticmethod
1018
1019 # staticmethod objects are recreated at depickling time, but the
1020 # underlying __func__ object is pickled by attribute.
1021 assert depickled_clsdict_meth.__func__ is clsdict_staticmethod.__func__
1022 type(depickled_clsdict_meth) is type(clsdict_staticmethod)
1023
1024 def test_tornado_coroutine(self):
1025 # Pickling a locally defined coroutine function
1026 gen = pytest.importorskip("tornado.gen")
1027 ioloop = pytest.importorskip("tornado.ioloop")
1028
1029 @gen.coroutine
1030 def f(x, y):
1031 yield gen.sleep(x)
1032 raise gen.Return(y + 1)
1033
1034 @gen.coroutine
1035 def g(y):
1036 res = yield f(0.01, y) # noqa: F821
1037 raise gen.Return(res + 1)
1038
1039 with pytest.warns(DeprecationWarning):
1040 assert cloudpickle.is_tornado_coroutine(g)
1041
1042 data = cloudpickle.dumps([g, g], protocol=self.protocol)
1043 del f, g
1044 g2, g3 = pickle.loads(data)
1045 assert g2 is g3
1046 loop = ioloop.IOLoop(make_current=False)
1047 res = loop.run_sync(functools.partial(g2, 5))
1048 assert res == 7
1049
1050 @pytest.mark.skipif(
1051 (3, 11, 0, "beta") <= sys.version_info < (3, 11, 0, "beta", 4),
1052 reason="https://github.com/python/cpython/issues/92932",
1053 )
1054 def test_extended_arg(self):
1055 # Functions with more than 65535 global vars prefix some global
1056 # variable references with the EXTENDED_ARG opcode.
1057 nvars = 65537 + 258
1058 names = ["g%d" % i for i in range(1, nvars)]
1059 r = random.Random(42)
1060 d = {name: r.randrange(100) for name in names}
1061 # def f(x):
1062 # x = g1, g2, ...
1063 # return zlib.crc32(bytes(bytearray(x)))
1064 code = """
1065 import zlib
1066
1067 def f():
1068 x = {tup}
1069 return zlib.crc32(bytes(bytearray(x)))
1070 """.format(tup=", ".join(names))
1071 exec(textwrap.dedent(code), d, d)
1072 f = d["f"]
1073 res = f()
1074 data = cloudpickle.dumps([f, f], protocol=self.protocol)
1075 d = f = None
1076 f2, f3 = pickle.loads(data)
1077 self.assertTrue(f2 is f3)
1078 self.assertEqual(f2(), res)
1079
1080 def test_submodule(self):
1081 # Function that refers (by attribute) to a sub-module of a package.
1082
1083 # Choose any module NOT imported by __init__ of its parent package
1084 # examples in standard library include:
1085 # http.cookies, unittest.mock, curses.textpad, xml.etree.ElementTree
1086 import xml
1087 import xml.etree.ElementTree
1088
1089 def example():
1090 _ = xml.etree.ElementTree.Comment # noqa: F821
1091
1092 example() # smoke test
1093
1094 s = cloudpickle.dumps(example, protocol=self.protocol)
1095
1096 # refresh the environment, i.e., unimport the dependency
1097 del xml
1098 for item in list(sys.modules):
1099 if item.split(".")[0] == "xml":
1100 del sys.modules[item]
1101
1102 # deserialise
1103 f = pickle.loads(s)
1104 f() # smoke test
1105
1106 def test_submodule_closure(self):
1107 # Same as test_submodule except the xml package has not been imported
1108 def scope():
1109 import xml.etree.ElementTree
1110
1111 def example():
1112 _ = xml.etree.ElementTree.Comment # potential AttributeError
1113
1114 return example
1115
1116 example = scope()
1117 example() # smoke test
1118
1119 s = cloudpickle.dumps(example, protocol=self.protocol)
1120
1121 # refresh the environment (unimport dependency)
1122 for item in list(sys.modules):
1123 if item.split(".")[0] == "xml":
1124 del sys.modules[item]
1125
1126 f = cloudpickle.loads(s)
1127 f() # smoke test
1128
1129 def test_multiprocess(self):
1130 # running a function pickled by another process (a la dask.distributed)
1131 def scope():
1132 def example():
1133 _ = xml.etree.ElementTree.Comment
1134
1135 return example
1136
1137 global xml
1138 import xml.etree.ElementTree
1139
1140 example = scope()
1141
1142 s = cloudpickle.dumps(example, protocol=self.protocol)
1143
1144 # choose "subprocess" rather than "multiprocessing" because the latter
1145 # library uses fork to preserve the parent environment.
1146 command = (
1147 "import base64; import pickle; pickle.loads(base64.b32decode('"
1148 + base64.b32encode(s).decode("ascii")
1149 + "'))()"
1150 )
1151 assert not subprocess.call([sys.executable, "-c", command])
1152
1153 def test_import(self):
1154 # like test_multiprocess except subpackage modules referenced directly
1155 # (unlike test_submodule)
1156 global etree
1157
1158 def scope():
1159 import xml.etree as foobar
1160
1161 def example():
1162 _ = etree.Comment
1163 _ = foobar.ElementTree
1164
1165 return example
1166
1167 example = scope()
1168 import xml.etree.ElementTree as etree
1169
1170 s = cloudpickle.dumps(example, protocol=self.protocol)
1171
1172 command = (
1173 "import base64; from pickle import loads; loads(base64.b32decode('"
1174 + base64.b32encode(s).decode("ascii")
1175 + "'))()"
1176 )
1177 assert not subprocess.call([sys.executable, "-c", command])
1178
1179 def test_multiprocessing_lock_raises(self):
1180 lock = multiprocessing.Lock()
1181 with pytest.raises(
1182 RuntimeError, match="only be shared between processes through inheritance"
1183 ):
1184 cloudpickle.dumps(lock)
1185
1186 def test_cell_manipulation(self):
1187 cell = _make_empty_cell()
1188
1189 with pytest.raises(ValueError):
1190 cell.cell_contents
1191
1192 ob = object()
1193 cell.cell_contents = ob
1194 assert cell.cell_contents is ob
1195
1196 def check_logger(self, name):
1197 logger = logging.getLogger(name)
1198 pickled = pickle_depickle(logger, protocol=self.protocol)
1199 self.assertTrue(pickled is logger, (pickled, logger))
1200
1201 dumped = cloudpickle.dumps(logger)
1202
1203 code = """if 1:
1204 import base64, cloudpickle, logging
1205
1206 logging.basicConfig(level=logging.INFO)
1207 logger = cloudpickle.loads(base64.b32decode(b'{}'))
1208 logger.info('hello')
1209 """.format(base64.b32encode(dumped).decode("ascii"))
1210 proc = subprocess.Popen(
1211 [sys.executable, "-W ignore", "-c", code],
1212 stdout=subprocess.PIPE,
1213 stderr=subprocess.STDOUT,
1214 )
1215 out, _ = proc.communicate()
1216 self.assertEqual(proc.wait(), 0)
1217 self.assertEqual(out.strip().decode(), f"INFO:{logger.name}:hello")
1218
1219 def test_logger(self):
1220 # logging.RootLogger object
1221 self.check_logger(None)
1222 # logging.Logger object
1223 self.check_logger("cloudpickle.dummy_test_logger")
1224
1225 def test_getset_descriptor(self):
1226 assert isinstance(float.real, types.GetSetDescriptorType)
1227 depickled_descriptor = pickle_depickle(float.real)
1228 self.assertIs(depickled_descriptor, float.real)
1229
1230 def test_abc_cache_not_pickled(self):
1231 # cloudpickle issue #302: make sure that cloudpickle does not pickle
1232 # the caches populated during instance/subclass checks of abc.ABCMeta
1233 # instances.
1234 MyClass = abc.ABCMeta("MyClass", (), {})
1235
1236 class MyUnrelatedClass:
1237 pass
1238
1239 class MyRelatedClass:
1240 pass
1241
1242 MyClass.register(MyRelatedClass)
1243
1244 assert not issubclass(MyUnrelatedClass, MyClass)
1245 assert issubclass(MyRelatedClass, MyClass)
1246
1247 s = cloudpickle.dumps(MyClass)
1248
1249 assert b"MyUnrelatedClass" not in s
1250 assert b"MyRelatedClass" in s
1251
1252 depickled_class = cloudpickle.loads(s)
1253 assert not issubclass(MyUnrelatedClass, depickled_class)
1254 assert issubclass(MyRelatedClass, depickled_class)
1255
1256 def test_abc(self):
1257 class AbstractClass(abc.ABC):
1258 @abc.abstractmethod
1259 def some_method(self):
1260 """A method"""
1261
1262 @classmethod
1263 @abc.abstractmethod
1264 def some_classmethod(cls):
1265 """A classmethod"""
1266
1267 @staticmethod
1268 @abc.abstractmethod
1269 def some_staticmethod():
1270 """A staticmethod"""
1271
1272 @property
1273 @abc.abstractmethod
1274 def some_property():
1275 """A property"""
1276
1277 class ConcreteClass(AbstractClass):
1278 def some_method(self):
1279 return "it works!"
1280
1281 @classmethod
1282 def some_classmethod(cls):
1283 assert cls == ConcreteClass
1284 return "it works!"
1285
1286 @staticmethod
1287 def some_staticmethod():
1288 return "it works!"
1289
1290 @property
1291 def some_property(self):
1292 return "it works!"
1293
1294 # This abstract class is locally defined so we can safely register
1295 # tuple in it to verify the unpickled class also register tuple.
1296 AbstractClass.register(tuple)
1297
1298 concrete_instance = ConcreteClass()
1299 depickled_base = pickle_depickle(AbstractClass, protocol=self.protocol)
1300 depickled_class = pickle_depickle(ConcreteClass, protocol=self.protocol)
1301 depickled_instance = pickle_depickle(concrete_instance)
1302
1303 assert issubclass(tuple, AbstractClass)
1304 assert issubclass(tuple, depickled_base)
1305
1306 self.assertEqual(depickled_class().some_method(), "it works!")
1307 self.assertEqual(depickled_instance.some_method(), "it works!")
1308
1309 self.assertEqual(depickled_class.some_classmethod(), "it works!")
1310 self.assertEqual(depickled_instance.some_classmethod(), "it works!")
1311
1312 self.assertEqual(depickled_class().some_staticmethod(), "it works!")
1313 self.assertEqual(depickled_instance.some_staticmethod(), "it works!")
1314
1315 self.assertEqual(depickled_class().some_property, "it works!")
1316 self.assertEqual(depickled_instance.some_property, "it works!")
1317 self.assertRaises(TypeError, depickled_base)
1318
1319 class DepickledBaseSubclass(depickled_base):
1320 def some_method(self):
1321 return "it works for realz!"
1322
1323 @classmethod
1324 def some_classmethod(cls):
1325 assert cls == DepickledBaseSubclass
1326 return "it works for realz!"
1327
1328 @staticmethod
1329 def some_staticmethod():
1330 return "it works for realz!"
1331
1332 @property
1333 def some_property():
1334 return "it works for realz!"
1335
1336 self.assertEqual(DepickledBaseSubclass().some_method(), "it works for realz!")
1337
1338 class IncompleteBaseSubclass(depickled_base):
1339 def some_method(self):
1340 return "this class lacks some concrete methods"
1341
1342 self.assertRaises(TypeError, IncompleteBaseSubclass)
1343
1344 def test_abstracts(self):
1345 # Same as `test_abc` but using deprecated `abc.abstract*` methods.
1346 # See https://github.com/cloudpipe/cloudpickle/issues/367
1347
1348 class AbstractClass(abc.ABC):
1349 @abc.abstractmethod
1350 def some_method(self):
1351 """A method"""
1352
1353 @abc.abstractclassmethod
1354 def some_classmethod(cls):
1355 """A classmethod"""
1356
1357 @abc.abstractstaticmethod
1358 def some_staticmethod():
1359 """A staticmethod"""
1360
1361 @abc.abstractproperty
1362 def some_property(self):
1363 """A property"""
1364
1365 class ConcreteClass(AbstractClass):
1366 def some_method(self):
1367 return "it works!"
1368
1369 @classmethod
1370 def some_classmethod(cls):
1371 assert cls == ConcreteClass
1372 return "it works!"
1373
1374 @staticmethod
1375 def some_staticmethod():
1376 return "it works!"
1377
1378 @property
1379 def some_property(self):
1380 return "it works!"
1381
1382 # This abstract class is locally defined so we can safely register
1383 # tuple in it to verify the unpickled class also register tuple.
1384 AbstractClass.register(tuple)
1385
1386 concrete_instance = ConcreteClass()
1387 depickled_base = pickle_depickle(AbstractClass, protocol=self.protocol)
1388 depickled_class = pickle_depickle(ConcreteClass, protocol=self.protocol)
1389 depickled_instance = pickle_depickle(concrete_instance)
1390
1391 assert issubclass(tuple, AbstractClass)
1392 assert issubclass(tuple, depickled_base)
1393
1394 self.assertEqual(depickled_class().some_method(), "it works!")
1395 self.assertEqual(depickled_instance.some_method(), "it works!")
1396
1397 self.assertEqual(depickled_class.some_classmethod(), "it works!")
1398 self.assertEqual(depickled_instance.some_classmethod(), "it works!")
1399
1400 self.assertEqual(depickled_class().some_staticmethod(), "it works!")
1401 self.assertEqual(depickled_instance.some_staticmethod(), "it works!")
1402
1403 self.assertEqual(depickled_class().some_property, "it works!")
1404 self.assertEqual(depickled_instance.some_property, "it works!")
1405 self.assertRaises(TypeError, depickled_base)
1406
1407 class DepickledBaseSubclass(depickled_base):
1408 def some_method(self):
1409 return "it works for realz!"
1410
1411 @classmethod
1412 def some_classmethod(cls):
1413 assert cls == DepickledBaseSubclass
1414 return "it works for realz!"
1415
1416 @staticmethod
1417 def some_staticmethod():
1418 return "it works for realz!"
1419
1420 @property
1421 def some_property(self):
1422 return "it works for realz!"
1423
1424 self.assertEqual(DepickledBaseSubclass().some_method(), "it works for realz!")
1425
1426 class IncompleteBaseSubclass(depickled_base):
1427 def some_method(self):
1428 return "this class lacks some concrete methods"
1429
1430 self.assertRaises(TypeError, IncompleteBaseSubclass)
1431
1432 def test_weakset_identity_preservation(self):
1433 # Test that weaksets don't lose all their inhabitants if they're
1434 # pickled in a larger data structure that includes other references to
1435 # their inhabitants.
1436
1437 class SomeClass:
1438 def __init__(self, x):
1439 self.x = x
1440
1441 obj1, obj2, obj3 = SomeClass(1), SomeClass(2), SomeClass(3)
1442
1443 things = [weakref.WeakSet([obj1, obj2]), obj1, obj2, obj3]
1444 result = pickle_depickle(things, protocol=self.protocol)
1445
1446 weakset, depickled1, depickled2, depickled3 = result
1447
1448 self.assertEqual(depickled1.x, 1)
1449 self.assertEqual(depickled2.x, 2)
1450 self.assertEqual(depickled3.x, 3)
1451 self.assertEqual(len(weakset), 2)
1452
1453 self.assertEqual(set(weakset), {depickled1, depickled2})
1454
1455 def test_non_module_object_passing_whichmodule_test(self):
1456 # https://github.com/cloudpipe/cloudpickle/pull/326: cloudpickle should
1457 # not try to instrospect non-modules object when trying to discover the
1458 # module of a function/class. This happenened because codecov injects
1459 # tuples (and not modules) into sys.modules, but type-checks were not
1460 # carried out on the entries of sys.modules, causing cloupdickle to
1461 # then error in unexpected ways
1462 def func(x):
1463 return x**2
1464
1465 # Trigger a loop during the execution of whichmodule(func) by
1466 # explicitly setting the function's module to None
1467 func.__module__ = None
1468
1469 class NonModuleObject:
1470 def __ini__(self):
1471 self.some_attr = None
1472
1473 def __getattr__(self, name):
1474 # We whitelist func so that a _whichmodule(func, None) call
1475 # returns the NonModuleObject instance if a type check on the
1476 # entries of sys.modules is not carried out, but manipulating
1477 # this instance thinking it really is a module later on in the
1478 # pickling process of func errors out
1479 if name == "func":
1480 return func
1481 else:
1482 raise AttributeError
1483
1484 non_module_object = NonModuleObject()
1485
1486 assert func(2) == 4
1487 assert func is non_module_object.func
1488
1489 # Any manipulation of non_module_object relying on attribute access
1490 # will raise an Exception
1491 with pytest.raises(AttributeError):
1492 _ = non_module_object.some_attr
1493
1494 try:
1495 sys.modules["NonModuleObject"] = non_module_object
1496
1497 func_module_name = _whichmodule(func, "func")
1498 assert func_module_name != "NonModuleObject"
1499 assert func_module_name is None
1500
1501 depickled_func = pickle_depickle(func, protocol=self.protocol)
1502 assert depickled_func(2) == 4
1503
1504 finally:
1505 sys.modules.pop("NonModuleObject")
1506
1507 def test_importing_multiprocessing_does_not_impact_whichmodule(self):
1508 # non-regression test for #528
1509 script = textwrap.dedent("""
1510 import multiprocessing
1511 import cloudpickle
1512 from cloudpickle.cloudpickle import dumps
1513
1514 # Trigger a loop during the execution of whichmodule() by
1515 # explicitly setting the function's module to None
1516 dumps.__module__ = None
1517
1518 print(cloudpickle.cloudpickle._whichmodule(dumps, dumps.__name__))
1519 """)
1520 script_path = Path(self.tmpdir) / "whichmodule_and_multiprocessing.py"
1521 with open(script_path, mode="w") as f:
1522 f.write(script)
1523
1524 proc = subprocess.Popen(
1525 [sys.executable, str(script_path)],
1526 stdout=subprocess.PIPE,
1527 stderr=subprocess.STDOUT,
1528 )
1529 out, _ = proc.communicate()
1530 self.assertEqual(proc.wait(), 0, msg="Stdout: " + str(out))
1531 self.assertEqual(out.strip(), b"cloudpickle.cloudpickle")
1532
1533
1534 def test_unrelated_faulty_module(self):
1535 # Check that pickling a dynamically defined function or class does not
1536 # fail when introspecting the currently loaded modules in sys.modules
1537 # as long as those faulty modules are unrelated to the class or
1538 # function we are currently pickling.
1539 for base_class in (object, types.ModuleType):
1540 for module_name in ["_missing_module", None]:
1541
1542 class FaultyModule(base_class):
1543 def __getattr__(self, name):
1544 # This throws an exception while looking up within
1545 # pickle.whichmodule or getattr(module, name, None)
1546 raise Exception()
1547
1548 class Foo:
1549 __module__ = module_name
1550
1551 def foo(self):
1552 return "it works!"
1553
1554 def foo():
1555 return "it works!"
1556
1557 foo.__module__ = module_name
1558
1559 if base_class is types.ModuleType: # noqa
1560 faulty_module = FaultyModule("_faulty_module")
1561 else:
1562 faulty_module = FaultyModule()
1563 sys.modules["_faulty_module"] = faulty_module
1564
1565 try:
1566 # Test whichmodule in save_global.
1567 self.assertEqual(pickle_depickle(Foo()).foo(), "it works!")
1568
1569 # Test whichmodule in save_function.
1570 cloned = pickle_depickle(foo, protocol=self.protocol)
1571 self.assertEqual(cloned(), "it works!")
1572 finally:
1573 sys.modules.pop("_faulty_module", None)
1574
1575 def test_function_module_name(self):
1576 def local_func(x):
1577 return x
1578
1579 for func in [local_func, lambda x: x]:
1580 cloned = pickle_depickle(func, protocol=self.protocol)
1581 self.assertEqual(cloned.__module__, func.__module__)
1582
1583 def test_function_qualname(self):
1584 def func(x):
1585 return x
1586
1587 # Default __qualname__ attribute (Python 3 only)
1588 if hasattr(func, "__qualname__"):
1589 cloned = pickle_depickle(func, protocol=self.protocol)
1590 self.assertEqual(cloned.__qualname__, func.__qualname__)
1591
1592 # Mutated __qualname__ attribute
1593 func.__qualname__ = "<modifiedlambda>"
1594 cloned = pickle_depickle(func, protocol=self.protocol)
1595 self.assertEqual(cloned.__qualname__, func.__qualname__)
1596
1597 def test_property(self):
1598 # Note that the @property decorator only has an effect on new-style
1599 # classes.
1600 class MyObject:
1601 _read_only_value = 1
1602 _read_write_value = 1
1603
1604 @property
1605 def read_only_value(self):
1606 "A read-only attribute"
1607 return self._read_only_value
1608
1609 @property
1610 def read_write_value(self):
1611 return self._read_write_value
1612
1613 @read_write_value.setter
1614 def read_write_value(self, value):
1615 self._read_write_value = value
1616
1617 my_object = MyObject()
1618
1619 assert my_object.read_only_value == 1
1620 assert MyObject.read_only_value.__doc__ == "A read-only attribute"
1621
1622 with pytest.raises(AttributeError):
1623 my_object.read_only_value = 2
1624 my_object.read_write_value = 2
1625
1626 depickled_obj = pickle_depickle(my_object)
1627
1628 assert depickled_obj.read_only_value == 1
1629 assert depickled_obj.read_write_value == 2
1630
1631 # make sure the depickled read_only_value attribute is still read-only
1632 with pytest.raises(AttributeError):
1633 my_object.read_only_value = 2
1634
1635 # make sure the depickled read_write_value attribute is writeable
1636 depickled_obj.read_write_value = 3
1637 assert depickled_obj.read_write_value == 3
1638 type(depickled_obj).read_only_value.__doc__ == "A read-only attribute"
1639
1640 def test_namedtuple(self):
1641 MyTuple = collections.namedtuple("MyTuple", ["a", "b", "c"])
1642 t1 = MyTuple(1, 2, 3)
1643 t2 = MyTuple(3, 2, 1)
1644
1645 depickled_t1, depickled_MyTuple, depickled_t2 = pickle_depickle(
1646 [t1, MyTuple, t2], protocol=self.protocol
1647 )
1648
1649 assert isinstance(depickled_t1, MyTuple)
1650 assert depickled_t1 == t1
1651 assert depickled_MyTuple is MyTuple
1652 assert isinstance(depickled_t2, MyTuple)
1653 assert depickled_t2 == t2
1654
1655 def test_NamedTuple(self):
1656 class MyTuple(typing.NamedTuple):
1657 a: int
1658 b: int
1659 c: int
1660
1661 t1 = MyTuple(1, 2, 3)
1662 t2 = MyTuple(3, 2, 1)
1663
1664 depickled_t1, depickled_MyTuple, depickled_t2 = pickle_depickle(
1665 [t1, MyTuple, t2], protocol=self.protocol
1666 )
1667
1668 assert isinstance(depickled_t1, MyTuple)
1669 assert depickled_t1 == t1
1670 assert depickled_MyTuple is MyTuple
1671 assert isinstance(depickled_t2, MyTuple)
1672 assert depickled_t2 == t2
1673
1674 def test_interactively_defined_function(self):
1675 # Check that callables defined in the __main__ module of a Python
1676 # script (or jupyter kernel) can be pickled / unpickled / executed.
1677 code = """\
1678 from testutils import subprocess_pickle_echo
1679
1680 CONSTANT = 42
1681
1682 class Foo(object):
1683
1684 def method(self, x):
1685 return x
1686
1687 foo = Foo()
1688
1689 def f0(x):
1690 return x ** 2
1691
1692 def f1():
1693 return Foo
1694
1695 def f2(x):
1696 return Foo().method(x)
1697
1698 def f3():
1699 return Foo().method(CONSTANT)
1700
1701 def f4(x):
1702 return foo.method(x)
1703
1704 def f5(x):
1705 # Recursive call to a dynamically defined function.
1706 if x <= 0:
1707 return f4(x)
1708 return f5(x - 1) + 1
1709
1710 cloned = subprocess_pickle_echo(lambda x: x**2, protocol={protocol})
1711 assert cloned(3) == 9
1712
1713 cloned = subprocess_pickle_echo(f0, protocol={protocol})
1714 assert cloned(3) == 9
1715
1716 cloned = subprocess_pickle_echo(Foo, protocol={protocol})
1717 assert cloned().method(2) == Foo().method(2)
1718
1719 cloned = subprocess_pickle_echo(Foo(), protocol={protocol})
1720 assert cloned.method(2) == Foo().method(2)
1721
1722 cloned = subprocess_pickle_echo(f1, protocol={protocol})
1723 assert cloned()().method('a') == f1()().method('a')
1724
1725 cloned = subprocess_pickle_echo(f2, protocol={protocol})
1726 assert cloned(2) == f2(2)
1727
1728 cloned = subprocess_pickle_echo(f3, protocol={protocol})
1729 assert cloned() == f3()
1730
1731 cloned = subprocess_pickle_echo(f4, protocol={protocol})
1732 assert cloned(2) == f4(2)
1733
1734 cloned = subprocess_pickle_echo(f5, protocol={protocol})
1735 assert cloned(7) == f5(7) == 7
1736 """.format(protocol=self.protocol)
1737 assert_run_python_script(textwrap.dedent(code))
1738
1739 def test_interactively_defined_global_variable(self):
1740 # Check that callables defined in the __main__ module of a Python
1741 # script (or jupyter kernel) correctly retrieve global variables.
1742 code_template = """\
1743 from testutils import subprocess_pickle_echo
1744 from cloudpickle import dumps, loads
1745
1746 def local_clone(obj, protocol=None):
1747 return loads(dumps(obj, protocol=protocol))
1748
1749 VARIABLE = "default_value"
1750
1751 def f0():
1752 global VARIABLE
1753 VARIABLE = "changed_by_f0"
1754
1755 def f1():
1756 return VARIABLE
1757
1758 assert f0.__globals__ is f1.__globals__
1759
1760 # pickle f0 and f1 inside the same pickle_string
1761 cloned_f0, cloned_f1 = {clone_func}([f0, f1], protocol={protocol})
1762
1763 # cloned_f0 and cloned_f1 now share a global namespace that is isolated
1764 # from any previously existing namespace
1765 assert cloned_f0.__globals__ is cloned_f1.__globals__
1766 assert cloned_f0.__globals__ is not f0.__globals__
1767
1768 # pickle f1 another time, but in a new pickle string
1769 pickled_f1 = dumps(f1, protocol={protocol})
1770
1771 # Change the value of the global variable in f0's new global namespace
1772 cloned_f0()
1773
1774 # thanks to cloudpickle isolation, depickling and calling f0 and f1
1775 # should not affect the globals of already existing modules
1776 assert VARIABLE == "default_value", VARIABLE
1777
1778 # Ensure that cloned_f1 and cloned_f0 share the same globals, as f1 and
1779 # f0 shared the same globals at pickling time, and cloned_f1 was
1780 # depickled from the same pickle string as cloned_f0
1781 shared_global_var = cloned_f1()
1782 assert shared_global_var == "changed_by_f0", shared_global_var
1783
1784 # f1 is unpickled another time, but because it comes from another
1785 # pickle string than pickled_f1 and pickled_f0, it will not share the
1786 # same globals as the latter two.
1787 new_cloned_f1 = loads(pickled_f1)
1788 assert new_cloned_f1.__globals__ is not cloned_f1.__globals__
1789 assert new_cloned_f1.__globals__ is not f1.__globals__
1790
1791 # get the value of new_cloned_f1's VARIABLE
1792 new_global_var = new_cloned_f1()
1793 assert new_global_var == "default_value", new_global_var
1794 """
1795 for clone_func in ["local_clone", "subprocess_pickle_echo"]:
1796 code = code_template.format(protocol=self.protocol, clone_func=clone_func)
1797 assert_run_python_script(textwrap.dedent(code))
1798
1799 def test_closure_interacting_with_a_global_variable(self):
1800 global _TEST_GLOBAL_VARIABLE
1801 assert _TEST_GLOBAL_VARIABLE == "default_value"
1802 orig_value = _TEST_GLOBAL_VARIABLE
1803 try:
1804
1805 def f0():
1806 global _TEST_GLOBAL_VARIABLE
1807 _TEST_GLOBAL_VARIABLE = "changed_by_f0"
1808
1809 def f1():
1810 return _TEST_GLOBAL_VARIABLE
1811
1812 # pickle f0 and f1 inside the same pickle_string
1813 cloned_f0, cloned_f1 = pickle_depickle([f0, f1], protocol=self.protocol)
1814
1815 # cloned_f0 and cloned_f1 now share a global namespace that is
1816 # isolated from any previously existing namespace
1817 assert cloned_f0.__globals__ is cloned_f1.__globals__
1818 assert cloned_f0.__globals__ is not f0.__globals__
1819
1820 # pickle f1 another time, but in a new pickle string
1821 pickled_f1 = cloudpickle.dumps(f1, protocol=self.protocol)
1822
1823 # Change the global variable's value in f0's new global namespace
1824 cloned_f0()
1825
1826 # depickling f0 and f1 should not affect the globals of already
1827 # existing modules
1828 assert _TEST_GLOBAL_VARIABLE == "default_value"
1829
1830 # Ensure that cloned_f1 and cloned_f0 share the same globals, as f1
1831 # and f0 shared the same globals at pickling time, and cloned_f1
1832 # was depickled from the same pickle string as cloned_f0
1833 shared_global_var = cloned_f1()
1834 assert shared_global_var == "changed_by_f0", shared_global_var
1835
1836 # f1 is unpickled another time, but because it comes from another
1837 # pickle string than pickled_f1 and pickled_f0, it will not share
1838 # the same globals as the latter two.
1839 new_cloned_f1 = pickle.loads(pickled_f1)
1840 assert new_cloned_f1.__globals__ is not cloned_f1.__globals__
1841 assert new_cloned_f1.__globals__ is not f1.__globals__
1842
1843 # get the value of new_cloned_f1's VARIABLE
1844 new_global_var = new_cloned_f1()
1845 assert new_global_var == "default_value", new_global_var
1846 finally:
1847 _TEST_GLOBAL_VARIABLE = orig_value
1848
1849 def test_interactive_remote_function_calls(self):
1850 code = """if __name__ == "__main__":
1851 from testutils import subprocess_worker
1852
1853 def interactive_function(x):
1854 return x + 1
1855
1856 with subprocess_worker(protocol={protocol}) as w:
1857
1858 assert w.run(interactive_function, 41) == 42
1859
1860 # Define a new function that will call an updated version of
1861 # the previously called function:
1862
1863 def wrapper_func(x):
1864 return interactive_function(x)
1865
1866 def interactive_function(x):
1867 return x - 1
1868
1869 # The change in the definition of interactive_function in the main
1870 # module of the main process should be reflected transparently
1871 # in the worker process: the worker process does not recall the
1872 # previous definition of `interactive_function`:
1873
1874 assert w.run(wrapper_func, 41) == 40
1875 """.format(protocol=self.protocol)
1876 assert_run_python_script(code)
1877
1878 def test_interactive_remote_function_calls_no_side_effect(self):
1879 code = """if __name__ == "__main__":
1880 from testutils import subprocess_worker
1881 import sys
1882
1883 with subprocess_worker(protocol={protocol}) as w:
1884
1885 GLOBAL_VARIABLE = 0
1886
1887 class CustomClass(object):
1888
1889 def mutate_globals(self):
1890 global GLOBAL_VARIABLE
1891 GLOBAL_VARIABLE += 1
1892 return GLOBAL_VARIABLE
1893
1894 custom_object = CustomClass()
1895 assert w.run(custom_object.mutate_globals) == 1
1896
1897 # The caller global variable is unchanged in the main process.
1898
1899 assert GLOBAL_VARIABLE == 0
1900
1901 # Calling the same function again starts again from zero. The
1902 # worker process is stateless: it has no memory of the past call:
1903
1904 assert w.run(custom_object.mutate_globals) == 1
1905
1906 # The symbols defined in the main process __main__ module are
1907 # not set in the worker process main module to leave the worker
1908 # as stateless as possible:
1909
1910 def is_in_main(name):
1911 return hasattr(sys.modules["__main__"], name)
1912
1913 assert is_in_main("CustomClass")
1914 assert not w.run(is_in_main, "CustomClass")
1915
1916 assert is_in_main("GLOBAL_VARIABLE")
1917 assert not w.run(is_in_main, "GLOBAL_VARIABLE")
1918
1919 """.format(protocol=self.protocol)
1920 assert_run_python_script(code)
1921
1922 def test_interactive_dynamic_type_and_remote_instances(self):
1923 code = """if __name__ == "__main__":
1924 from testutils import subprocess_worker
1925
1926 with subprocess_worker(protocol={protocol}) as w:
1927
1928 class CustomCounter:
1929 def __init__(self):
1930 self.count = 0
1931 def increment(self):
1932 self.count += 1
1933 return self
1934
1935 counter = CustomCounter().increment()
1936 assert counter.count == 1
1937
1938 returned_counter = w.run(counter.increment)
1939 assert returned_counter.count == 2, returned_counter.count
1940
1941 # Check that the class definition of the returned instance was
1942 # matched back to the original class definition living in __main__.
1943
1944 assert isinstance(returned_counter, CustomCounter)
1945
1946 # Check that memoization does not break provenance tracking:
1947
1948 def echo(*args):
1949 return args
1950
1951 C1, C2, c1, c2 = w.run(echo, CustomCounter, CustomCounter,
1952 CustomCounter(), returned_counter)
1953 assert C1 is CustomCounter
1954 assert C2 is CustomCounter
1955 assert isinstance(c1, CustomCounter)
1956 assert isinstance(c2, CustomCounter)
1957
1958 """.format(protocol=self.protocol)
1959 assert_run_python_script(code)
1960
1961 def test_interactive_dynamic_type_and_stored_remote_instances(self):
1962 """Simulate objects stored on workers to check isinstance semantics
1963
1964 Such instances stored in the memory of running worker processes are
1965 similar to dask-distributed futures for instance.
1966 """
1967 code = """if __name__ == "__main__":
1968 import cloudpickle, uuid
1969 from testutils import subprocess_worker
1970
1971 with subprocess_worker(protocol={protocol}) as w:
1972
1973 class A:
1974 '''Original class definition'''
1975 pass
1976
1977 def store(x):
1978 storage = getattr(cloudpickle, "_test_storage", None)
1979 if storage is None:
1980 storage = cloudpickle._test_storage = dict()
1981 obj_id = uuid.uuid4().hex
1982 storage[obj_id] = x
1983 return obj_id
1984
1985 def lookup(obj_id):
1986 return cloudpickle._test_storage[obj_id]
1987
1988 id1 = w.run(store, A())
1989
1990 # The stored object on the worker is matched to a singleton class
1991 # definition thanks to provenance tracking:
1992 assert w.run(lambda obj_id: isinstance(lookup(obj_id), A), id1)
1993
1994 # Retrieving the object from the worker yields a local copy that
1995 # is matched back the local class definition this instance
1996 # originally stems from.
1997 assert isinstance(w.run(lookup, id1), A)
1998
1999 # Changing the local class definition should be taken into account
2000 # in all subsequent calls. In particular the old instances on the
2001 # worker do not map back to the new class definition, neither on
2002 # the worker itself, nor locally on the main program when the old
2003 # instance is retrieved:
2004
2005 class A:
2006 '''Updated class definition'''
2007
2008 assert not w.run(lambda obj_id: isinstance(lookup(obj_id), A), id1)
2009 retrieved1 = w.run(lookup, id1)
2010 assert not isinstance(retrieved1, A)
2011 assert retrieved1.__class__ is not A
2012 assert retrieved1.__class__.__doc__ == "Original class definition"
2013
2014 # New instances on the other hand are proper instances of the new
2015 # class definition everywhere:
2016
2017 a = A()
2018 id2 = w.run(store, a)
2019 assert w.run(lambda obj_id: isinstance(lookup(obj_id), A), id2)
2020 assert isinstance(w.run(lookup, id2), A)
2021
2022 # Monkeypatch the class defintion in the main process to a new
2023 # class method:
2024 A.echo = lambda cls, x: x
2025
2026 # Calling this method on an instance will automatically update
2027 # the remote class definition on the worker to propagate the monkey
2028 # patch dynamically.
2029 assert w.run(a.echo, 42) == 42
2030
2031 # The stored instance can therefore also access the new class
2032 # method:
2033 assert w.run(lambda obj_id: lookup(obj_id).echo(43), id2) == 43
2034
2035 """.format(protocol=self.protocol)
2036 assert_run_python_script(code)
2037
2038 def test_dynamic_func_deterministic_roundtrip(self):
2039 # Check that the pickle serialization for a dynamic func is the same
2040 # in two processes.
2041
2042 def get_dynamic_func_pickle():
2043 def test_method(arg_1, arg_2):
2044 pass
2045
2046 return cloudpickle.dumps(test_method)
2047
2048 with subprocess_worker(protocol=self.protocol) as w:
2049 A_dump = w.run(get_dynamic_func_pickle)
2050 check_deterministic_pickle(A_dump, get_dynamic_func_pickle())
2051
2052 def test_dynamic_class_deterministic_roundtrip(self):
2053 # Check that the pickle serialization for a dynamic class is the same
2054 # in two processes.
2055 pytest.xfail("This test fails due to different tracker_id.")
2056
2057 def get_dynamic_class_pickle():
2058 class A:
2059 """Class with potential string interning issues."""
2060
2061 arg_1 = "class_value"
2062
2063 def join(self):
2064 pass
2065
2066 def test_method(self, arg_1, join):
2067 pass
2068
2069 return cloudpickle.dumps(A)
2070
2071 with subprocess_worker(protocol=self.protocol) as w:
2072 A_dump = w.run(get_dynamic_class_pickle)
2073 check_deterministic_pickle(A_dump, get_dynamic_class_pickle())
2074
2075 def test_deterministic_dynamic_class_attr_ordering_for_chained_pickling(self):
2076 # Check that the pickle produced by pickling a reconstructed class definition
2077 # in a remote process matches the pickle produced by pickling the original
2078 # class definition.
2079 # In particular, this test checks that the order of the class attributes is
2080 # deterministic.
2081
2082 with subprocess_worker(protocol=self.protocol) as w:
2083
2084 class A:
2085 """Simple class definition"""
2086
2087 pass
2088
2089 A_dump = w.run(cloudpickle.dumps, A)
2090 check_deterministic_pickle(A_dump, cloudpickle.dumps(A))
2091
2092 # If the `__doc__` attribute is defined after some other class
2093 # attribute, this can cause class attribute ordering changes due to
2094 # the way we reconstruct the class definition in
2095 # `_make_skeleton_class`, which creates the class and thus its
2096 # `__doc__` attribute before populating the class attributes.
2097 class A:
2098 name = "A"
2099 __doc__ = "Updated class definition"
2100
2101 A_dump = w.run(cloudpickle.dumps, A)
2102 check_deterministic_pickle(A_dump, cloudpickle.dumps(A))
2103
2104 # If a `__doc__` is defined on the `__init__` method, this can
2105 # cause ordering changes due to the way we reconstruct the class
2106 # with `_make_skeleton_class`.
2107 class A:
2108 def __init__(self):
2109 """Class definition with explicit __init__"""
2110 pass
2111
2112 A_dump = w.run(cloudpickle.dumps, A)
2113 check_deterministic_pickle(A_dump, cloudpickle.dumps(A))
2114
2115 def test_deterministic_str_interning_for_chained_dynamic_class_pickling(self):
2116 # Check that the pickle produced by the unpickled instance is the same.
2117 # This checks that there is no issue related to the string interning of
2118 # the names of attributes of class definitions and names of attributes
2119 # of the `__code__` objects of the methods.
2120
2121 with subprocess_worker(protocol=self.protocol) as w:
2122 # Due to interning of class attributes, check that this does not
2123 # create issues with dynamic function definition.
2124 class A:
2125 """Class with potential string interning issues."""
2126
2127 arg_1 = "class_value"
2128
2129 def join(self):
2130 pass
2131
2132 def test_method(self, arg_1, join):
2133 pass
2134
2135 A_dump = w.run(cloudpickle.dumps, A)
2136 check_deterministic_pickle(A_dump, cloudpickle.dumps(A))
2137
2138 # Also check that memoization of string value inside the class does
2139 # not cause non-deterministic pickle with interned method names.
2140 class A:
2141 """Class with potential string interning issues."""
2142
2143 arg_1 = "join"
2144
2145 def join(self, arg_1):
2146 pass
2147
2148 # Set a custom method attribute that can potentially trigger
2149 # undeterministic memoization depending on the interning state of
2150 # the string used for the attribute name.
2151 A.join.arg_1 = "join"
2152
2153 A_dump = w.run(cloudpickle.dumps, A)
2154 check_deterministic_pickle(A_dump, cloudpickle.dumps(A))
2155
2156 def test_dynamic_class_determinist_subworker_tuple_memoization(self):
2157 # Check that the pickle produced by the unpickled instance is the same.
2158 # This highlights some issues with tuple memoization.
2159
2160 with subprocess_worker(protocol=self.protocol) as w:
2161 # Arguments' tuple is memoized in the main process but not in the
2162 # subprocess as the tuples do not share the same id in the loaded
2163 # class.
2164 class A:
2165 """Class with potential tuple memoization issues."""
2166
2167 def func1(self):
2168 pass
2169
2170 def func2(self):
2171 pass
2172
2173 A_dump = w.run(cloudpickle.dumps, A)
2174 check_deterministic_pickle(A_dump, cloudpickle.dumps(A))
2175
2176 @pytest.mark.skipif(
2177 platform.python_implementation() == "PyPy",
2178 reason="Skip PyPy because memory grows too much",
2179 )
2180 def test_interactive_remote_function_calls_no_memory_leak(self):
2181 code = """if __name__ == "__main__":
2182 from testutils import subprocess_worker
2183 import struct
2184
2185 with subprocess_worker(protocol={protocol}) as w:
2186
2187 reference_size = w.memsize()
2188 assert reference_size > 0
2189
2190
2191 def make_big_closure(i):
2192 # Generate a byte string of size 1MB
2193 itemsize = len(struct.pack("l", 1))
2194 data = struct.pack("l", i) * (int(1e6) // itemsize)
2195 def process_data():
2196 return len(data)
2197 return process_data
2198
2199 for i in range(100):
2200 func = make_big_closure(i)
2201 result = w.run(func)
2202 assert result == int(1e6), result
2203
2204 import gc
2205 w.run(gc.collect)
2206
2207 # By this time the worker process has processed 100MB worth of data
2208 # passed in the closures. The worker memory size should not have
2209 # grown by more than a few MB as closures are garbage collected at
2210 # the end of each remote function call.
2211 growth = w.memsize() - reference_size
2212
2213 # For some reason, the memory growth after processing 100MB of
2214 # data is ~50MB on MacOS, and ~1MB on Linux, so the upper bound on
2215 # memory growth we use is only tight for MacOS. However,
2216 # - 50MB is still 2x lower than the expected memory growth in case
2217 # of a leak (which would be the total size of the processed data,
2218 # 100MB)
2219 # - the memory usage growth does not increase if using 10000
2220 # iterations instead of 100 as used now (100x more data)
2221 assert growth < 5e7, growth
2222
2223 """.format(protocol=self.protocol)
2224 assert_run_python_script(code)
2225
2226 def test_pickle_reraise(self):
2227 for exc_type in [Exception, ValueError, TypeError, RuntimeError]:
2228 obj = RaiserOnPickle(exc_type("foo"))
2229 with pytest.raises((exc_type, pickle.PicklingError)):
2230 cloudpickle.dumps(obj, protocol=self.protocol)
2231
2232 def test_unhashable_function(self):
2233 d = {"a": 1}
2234 depickled_method = pickle_depickle(d.get, protocol=self.protocol)
2235 self.assertEqual(depickled_method("a"), 1)
2236 self.assertEqual(depickled_method("b"), None)
2237
2238 @unittest.skipIf(
2239 sys.version_info >= (3, 14),
2240 "itertools.count() doesn't support pickle on Python 3.14+",
2241 )
2242 def test_itertools_count(self):
2243 counter = itertools.count(1, step=2)
2244
2245 # advance the counter a bit
2246 next(counter)
2247 next(counter)
2248
2249 new_counter = pickle_depickle(counter, protocol=self.protocol)
2250
2251 self.assertTrue(counter is not new_counter)
2252
2253 for _ in range(10):
2254 self.assertEqual(next(counter), next(new_counter))
2255
2256 def test_wraps_preserves_function_name(self):
2257 from functools import wraps
2258
2259 def f():
2260 pass
2261
2262 @wraps(f)
2263 def g():
2264 f()
2265
2266 f2 = pickle_depickle(g, protocol=self.protocol)
2267
2268 self.assertEqual(f2.__name__, f.__name__)
2269
2270 def test_wraps_preserves_function_doc(self):
2271 from functools import wraps
2272
2273 def f():
2274 """42"""
2275 pass
2276
2277 @wraps(f)
2278 def g():
2279 f()
2280
2281 f2 = pickle_depickle(g, protocol=self.protocol)
2282
2283 self.assertEqual(f2.__doc__, f.__doc__)
2284
2285 def test_wraps_preserves_function_annotations(self):
2286 def f(x: int) -> float:
2287 pass
2288
2289 @wraps(f)
2290 def g(x):
2291 f(x)
2292
2293 f2 = pickle_depickle(g, protocol=self.protocol)
2294
2295 self.assertEqual(f2.__annotations__, f.__annotations__)
2296
2297 def test_type_hint(self):
2298 t = typing.Union[list, int]
2299 assert pickle_depickle(t) == t
2300
2301 def test_instance_with_slots(self):
2302 for slots in [["registered_attribute"], "registered_attribute"]:
2303
2304 class ClassWithSlots:
2305 __slots__ = slots
2306
2307 def __init__(self):
2308 self.registered_attribute = 42
2309
2310 initial_obj = ClassWithSlots()
2311 depickled_obj = pickle_depickle(initial_obj, protocol=self.protocol)
2312
2313 assert depickled_obj.__class__.__slots__ == slots
2314
2315 for obj in [initial_obj, depickled_obj]:
2316 self.assertEqual(obj.registered_attribute, 42)
2317 with pytest.raises(AttributeError):
2318 obj.non_registered_attribute = 1
2319
2320 class SubclassWithSlots(ClassWithSlots):
2321 def __init__(self):
2322 self.unregistered_attribute = 1
2323
2324 obj = SubclassWithSlots()
2325 s = cloudpickle.dumps(obj, protocol=self.protocol)
2326 del SubclassWithSlots
2327 depickled_obj = cloudpickle.loads(s)
2328 assert depickled_obj.unregistered_attribute == 1
2329
2330 @unittest.skipIf(
2331 not hasattr(types, "MappingProxyType"),
2332 "Old versions of Python do not have this type.",
2333 )
2334 def test_mappingproxy(self):
2335 mp = types.MappingProxyType({"some_key": "some value"})
2336 assert mp == pickle_depickle(mp, protocol=self.protocol)
2337
2338 def test_dataclass(self):
2339 dataclasses = pytest.importorskip("dataclasses")
2340
2341 DataClass = dataclasses.make_dataclass("DataClass", [("x", int)])
2342 data = DataClass(x=42)
2343
2344 pickle_depickle(DataClass, protocol=self.protocol)
2345 assert data.x == pickle_depickle(data, protocol=self.protocol).x == 42
2346
2347 def test_locally_defined_enum(self):
2348 class StringEnum(str, enum.Enum):
2349 """Enum when all members are also (and must be) strings"""
2350
2351 class Color(StringEnum):
2352 """3-element color space"""
2353
2354 RED = "1"
2355 GREEN = "2"
2356 BLUE = "3"
2357
2358 def is_green(self):
2359 return self is Color.GREEN
2360
2361 green1, green2, ClonedColor = pickle_depickle(
2362 [Color.GREEN, Color.GREEN, Color], protocol=self.protocol
2363 )
2364 assert green1 is green2
2365 assert green1 is ClonedColor.GREEN
2366 assert green1 is not ClonedColor.BLUE
2367 assert isinstance(green1, str)
2368 assert green1.is_green()
2369
2370 # cloudpickle systematically tracks provenance of class definitions
2371 # and ensure reconciliation in case of round trips:
2372 assert green1 is Color.GREEN
2373 assert ClonedColor is Color
2374
2375 green3 = pickle_depickle(Color.GREEN, protocol=self.protocol)
2376 assert green3 is Color.GREEN
2377
2378 def test_locally_defined_intenum(self):
2379 # Try again with a IntEnum defined with the functional API
2380 DynamicColor = enum.IntEnum("Color", {"RED": 1, "GREEN": 2, "BLUE": 3})
2381
2382 green1, green2, ClonedDynamicColor = pickle_depickle(
2383 [DynamicColor.GREEN, DynamicColor.GREEN, DynamicColor],
2384 protocol=self.protocol,
2385 )
2386
2387 assert green1 is green2
2388 assert green1 is ClonedDynamicColor.GREEN
2389 assert green1 is not ClonedDynamicColor.BLUE
2390 assert ClonedDynamicColor is DynamicColor
2391
2392 def test_interactively_defined_enum(self):
2393 code = """if __name__ == "__main__":
2394 from enum import Enum
2395 from testutils import subprocess_worker
2396
2397 with subprocess_worker(protocol={protocol}) as w:
2398
2399 class Color(Enum):
2400 RED = 1
2401 GREEN = 2
2402
2403 def check_positive(x):
2404 return Color.GREEN if x >= 0 else Color.RED
2405
2406 result = w.run(check_positive, 1)
2407
2408 # Check that the returned enum instance is reconciled with the
2409 # locally defined Color enum type definition:
2410
2411 assert result is Color.GREEN
2412
2413 # Check that changing the definition of the Enum class is taken
2414 # into account on the worker for subsequent calls:
2415
2416 class Color(Enum):
2417 RED = 1
2418 BLUE = 2
2419
2420 def check_positive(x):
2421 return Color.BLUE if x >= 0 else Color.RED
2422
2423 result = w.run(check_positive, 1)
2424 assert result is Color.BLUE
2425 """.format(protocol=self.protocol)
2426 assert_run_python_script(code)
2427
2428 def test_relative_import_inside_function(self):
2429 # Make sure relative imports inside round-tripped functions is not
2430 # broken. This was a bug in cloudpickle versions <= 0.5.3 and was
2431 # re-introduced in 0.8.0.
2432 _cloudpickle_testpkg = pytest.importorskip("_cloudpickle_testpkg")
2433 relative_imports_factory = _cloudpickle_testpkg.relative_imports_factory
2434 f, g = relative_imports_factory()
2435 for func, source in zip([f, g], ["module", "package"]):
2436 # Make sure relative imports are initially working
2437 assert func() == f"hello from a {source}!"
2438
2439 # Make sure relative imports still work after round-tripping
2440 cloned_func = pickle_depickle(func, protocol=self.protocol)
2441 assert cloned_func() == f"hello from a {source}!"
2442
2443 def test_interactively_defined_func_with_keyword_only_argument(self):
2444 # fixes https://github.com/cloudpipe/cloudpickle/issues/263
2445 def f(a, *, b=1):
2446 return a + b
2447
2448 depickled_f = pickle_depickle(f, protocol=self.protocol)
2449
2450 for func in (f, depickled_f):
2451 assert func(2) == 3
2452 assert func.__kwdefaults__ == {"b": 1}
2453
2454 @pytest.mark.skipif(
2455 not hasattr(types.CodeType, "co_posonlyargcount"),
2456 reason="Requires positional-only argument syntax",
2457 )
2458 def test_interactively_defined_func_with_positional_only_argument(self):
2459 # Fixes https://github.com/cloudpipe/cloudpickle/issues/266
2460 # The source code of this test is bundled in a string and is ran from
2461 # the __main__ module of a subprocess in order to avoid a SyntaxError
2462 # in versions of python that do not support positional-only argument
2463 # syntax.
2464 code = """
2465 import pytest
2466 from cloudpickle import loads, dumps
2467
2468 def f(a, /, b=1):
2469 return a + b
2470
2471 depickled_f = loads(dumps(f, protocol={protocol}))
2472
2473 for func in (f, depickled_f):
2474 assert func(2) == 3
2475 assert func.__code__.co_posonlyargcount == 1
2476 with pytest.raises(TypeError):
2477 func(a=2)
2478
2479 """.format(protocol=self.protocol)
2480 assert_run_python_script(textwrap.dedent(code))
2481
2482 def test___reduce___returns_string(self):
2483 # Non regression test for objects with a __reduce__ method returning a
2484 # string, meaning "save by attribute using save_global"
2485 _cloudpickle_testpkg = pytest.importorskip("_cloudpickle_testpkg")
2486 some_singleton = _cloudpickle_testpkg.some_singleton
2487 assert some_singleton.__reduce__() == "some_singleton"
2488 depickled_singleton = pickle_depickle(some_singleton, protocol=self.protocol)
2489 assert depickled_singleton is some_singleton
2490
2491 def test_cloudpickle_extract_nested_globals(self):
2492 def function_factory():
2493 def inner_function():
2494 global _TEST_GLOBAL_VARIABLE
2495 return _TEST_GLOBAL_VARIABLE
2496
2497 return inner_function
2498
2499 globals_ = set(
2500 cloudpickle.cloudpickle._extract_code_globals(
2501 function_factory.__code__
2502 ).keys()
2503 )
2504 assert globals_ == {"_TEST_GLOBAL_VARIABLE"}
2505
2506 depickled_factory = pickle_depickle(function_factory, protocol=self.protocol)
2507 inner_func = depickled_factory()
2508 assert inner_func() == _TEST_GLOBAL_VARIABLE
2509
2510 # TODO: remove this xfail when we drop support for Python 3.8. We don't
2511 # plan to fix it because Python 3.8 is EOL.
2512 @pytest.mark.skipif(
2513 sys.version_info < (3, 9),
2514 reason="Can cause CPython 3.8 to segfault",
2515 )
2516 def test_recursion_during_pickling(self):
2517 class A:
2518 def __getattribute__(self, name):
2519 return getattr(self, name)
2520
2521 a = A()
2522 with pytest.raises(pickle.PicklingError, match="deep recursion"):
2523 cloudpickle.dumps(a)
2524
2525 def test_out_of_band_buffers(self):
2526 if self.protocol < 5:
2527 pytest.skip("Need Pickle Protocol 5 or later")
2528 np = pytest.importorskip("numpy")
2529
2530 class LocallyDefinedClass:
2531 data = np.zeros(10)
2532
2533 data_instance = LocallyDefinedClass()
2534 buffers = []
2535 pickle_bytes = cloudpickle.dumps(
2536 data_instance, protocol=self.protocol, buffer_callback=buffers.append
2537 )
2538 assert len(buffers) == 1
2539 reconstructed = pickle.loads(pickle_bytes, buffers=buffers)
2540 np.testing.assert_allclose(reconstructed.data, data_instance.data)
2541
2542 def test_pickle_dynamic_typevar(self):
2543 T = typing.TypeVar("T")
2544 depickled_T = pickle_depickle(T, protocol=self.protocol)
2545 attr_list = [
2546 "__name__",
2547 "__bound__",
2548 "__constraints__",
2549 "__covariant__",
2550 "__contravariant__",
2551 ]
2552 for attr in attr_list:
2553 assert getattr(T, attr) == getattr(depickled_T, attr)
2554
2555 def test_pickle_dynamic_typevar_tracking(self):
2556 T = typing.TypeVar("T")
2557 T2 = subprocess_pickle_echo(T, protocol=self.protocol)
2558 assert T is T2
2559
2560 def test_pickle_dynamic_typevar_memoization(self):
2561 T = typing.TypeVar("T")
2562 depickled_T1, depickled_T2 = pickle_depickle((T, T), protocol=self.protocol)
2563 assert depickled_T1 is depickled_T2
2564
2565 def test_pickle_importable_typevar(self):
2566 _cloudpickle_testpkg = pytest.importorskip("_cloudpickle_testpkg")
2567 T1 = pickle_depickle(_cloudpickle_testpkg.T, protocol=self.protocol)
2568 assert T1 is _cloudpickle_testpkg.T
2569
2570 # Standard Library TypeVar
2571 from typing import AnyStr
2572
2573 assert AnyStr is pickle_depickle(AnyStr, protocol=self.protocol)
2574
2575 def test_generic_type(self):
2576 T = typing.TypeVar("T")
2577
2578 class C(typing.Generic[T]):
2579 pass
2580
2581 assert pickle_depickle(C, protocol=self.protocol) is C
2582
2583 # Identity is not part of the typing contract: only test for
2584 # equality instead.
2585 assert pickle_depickle(C[int], protocol=self.protocol) == C[int]
2586
2587 with subprocess_worker(protocol=self.protocol) as worker:
2588
2589 def check_generic(generic, origin, type_value):
2590 assert generic.__origin__ is origin
2591
2592 assert len(origin.__orig_bases__) == 1
2593 ob = origin.__orig_bases__[0]
2594 assert ob.__origin__ is typing.Generic
2595
2596 assert len(generic.__args__) == 1
2597 assert generic.__args__[0] is type_value
2598 assert len(ob.__parameters__) == 1
2599
2600 return "ok"
2601
2602 assert check_generic(C[int], C, int) == "ok"
2603 assert worker.run(check_generic, C[int], C, int) == "ok"
2604
2605 def test_generic_subclass(self):
2606 T = typing.TypeVar("T")
2607
2608 class Base(typing.Generic[T]):
2609 pass
2610
2611 class DerivedAny(Base):
2612 pass
2613
2614 class LeafAny(DerivedAny):
2615 pass
2616
2617 class DerivedInt(Base[int]):
2618 pass
2619
2620 class LeafInt(DerivedInt):
2621 pass
2622
2623 class DerivedT(Base[T]):
2624 pass
2625
2626 class LeafT(DerivedT[T]):
2627 pass
2628
2629 klasses = [Base, DerivedAny, LeafAny, DerivedInt, LeafInt, DerivedT, LeafT]
2630 for klass in klasses:
2631 assert pickle_depickle(klass, protocol=self.protocol) is klass
2632
2633 with subprocess_worker(protocol=self.protocol) as worker:
2634
2635 def check_mro(klass, expected_mro):
2636 assert klass.mro() == expected_mro
2637 return "ok"
2638
2639 for klass in klasses:
2640 mro = klass.mro()
2641 assert check_mro(klass, mro)
2642 assert worker.run(check_mro, klass, mro) == "ok"
2643
2644 def test_locally_defined_class_with_type_hints(self):
2645 with subprocess_worker(protocol=self.protocol) as worker:
2646 for type_ in _all_types_to_test():
2647
2648 class MyClass:
2649 def method(self, arg: type_) -> type_:
2650 return arg
2651
2652 MyClass.__annotations__ = {"attribute": type_}
2653
2654 def check_annotations(obj, expected_type, expected_type_str):
2655 # On Python 3.14, it's no longer possible to access class
2656 # annotations from an instance, so use type().
2657 assert type(obj).__annotations__["attribute"] == expected_type
2658 assert obj.method.__annotations__["arg"] == expected_type
2659 assert obj.method.__annotations__["return"] == expected_type
2660 return "ok"
2661
2662 obj = MyClass()
2663 assert check_annotations(obj, type_, "type_") == "ok"
2664 assert worker.run(check_annotations, obj, type_, "type_") == "ok"
2665
2666 def test_class_annotations(self):
2667 class C:
2668 pass
2669
2670 C.__annotations__ = {"a": int}
2671
2672 C1 = pickle_depickle(C, protocol=self.protocol)
2673 assert C1.__annotations__ == C.__annotations__
2674
2675 def test_class_annotations_abstractclass(self):
2676 # see https://github.com/cloudpipe/cloudpickle/issues/572
2677
2678 class C(abc.ABC):
2679 a: int
2680
2681 C1 = pickle_depickle(C, protocol=self.protocol)
2682 assert C1.__annotations__ == C.__annotations__
2683 C2 = pickle_depickle(C1, protocol=self.protocol)
2684 if sys.version_info >= (3, 14):
2685 # check that __annotate_func__ is created by Python
2686 assert hasattr(C2, "__annotate_func__")
2687 assert C2.__annotations__ == C1.__annotations__
2688 c2 = C2()
2689 assert isinstance(c2, C2)
2690
2691 def test_function_annotations(self):
2692 def f(a: int) -> str:
2693 pass
2694
2695 f1 = pickle_depickle(f, protocol=self.protocol)
2696 assert f1.__annotations__ == f.__annotations__
2697
2698 def test_always_use_up_to_date_copyreg(self):
2699 # test that updates of copyreg.dispatch_table are taken in account by
2700 # cloudpickle
2701 import copyreg
2702
2703 try:
2704
2705 class MyClass:
2706 pass
2707
2708 def reduce_myclass(x):
2709 return MyClass, (), {"custom_reduce": True}
2710
2711 copyreg.dispatch_table[MyClass] = reduce_myclass
2712 my_obj = MyClass()
2713 depickled_myobj = pickle_depickle(my_obj, protocol=self.protocol)
2714 assert hasattr(depickled_myobj, "custom_reduce")
2715 finally:
2716 copyreg.dispatch_table.pop(MyClass)
2717
2718 def test_literal_misdetection(self):
2719 # see https://github.com/cloudpipe/cloudpickle/issues/403
2720 class MyClass:
2721 @property
2722 def __values__(self):
2723 return ()
2724
2725 o = MyClass()
2726 pickle_depickle(o, protocol=self.protocol)
2727
2728 def test_final_or_classvar_misdetection(self):
2729 # see https://github.com/cloudpipe/cloudpickle/issues/403
2730 class MyClass:
2731 @property
2732 def __type__(self):
2733 return int
2734
2735 o = MyClass()
2736 pickle_depickle(o, protocol=self.protocol)
2737
2738 def test_pickle_constructs_from_module_registered_for_pickling_by_value(
2739 self,
2740 ): # noqa
2741 _prev_sys_path = sys.path.copy()
2742 try:
2743 # We simulate an interactive session that:
2744 # - we start from the /path/to/cloudpickle/tests directory, where a
2745 # local .py file (mock_local_file) is located.
2746 # - uses constructs from mock_local_file in remote workers that do
2747 # not have access to this file. This situation is
2748 # the justification behind the
2749 # (un)register_pickle_by_value(module) api that cloudpickle
2750 # exposes.
2751 _mock_interactive_session_cwd = os.path.dirname(__file__)
2752
2753 # First, remove sys.path entries that could point to
2754 # /path/to/cloudpickle/tests and be in inherited by the worker
2755 _maybe_remove(sys.path, "")
2756 _maybe_remove(sys.path, _mock_interactive_session_cwd)
2757
2758 # Add the desired session working directory
2759 sys.path.insert(0, _mock_interactive_session_cwd)
2760
2761 with subprocess_worker(protocol=self.protocol) as w:
2762 # Make the module unavailable in the remote worker
2763 w.run(lambda p: sys.path.remove(p), _mock_interactive_session_cwd)
2764 # Import the actual file after starting the module since the
2765 # worker is started using fork on Linux, which will inherits
2766 # the parent sys.modules. On Python>3.6, the worker can be
2767 # started using spawn using mp_context in ProcessPoolExectutor.
2768 # TODO Once Python 3.6 reaches end of life, rely on mp_context
2769 # instead.
2770 import mock_local_folder.mod as mod
2771
2772 # The constructs whose pickling mechanism is changed using
2773 # register_pickle_by_value are functions, classes, TypeVar and
2774 # modules.
2775 from mock_local_folder.mod import local_function, LocalT, LocalClass
2776
2777 # Make sure the module/constructs are unimportable in the
2778 # worker.
2779 with pytest.raises(ImportError):
2780 w.run(lambda: __import__("mock_local_folder.mod"))
2781 with pytest.raises(ImportError):
2782 w.run(lambda: __import__("mock_local_folder.subfolder.mod"))
2783
2784 for o in [mod, local_function, LocalT, LocalClass]:
2785 with pytest.raises(ImportError):
2786 w.run(lambda: o)
2787
2788 register_pickle_by_value(mod)
2789 # function
2790 assert w.run(lambda: local_function()) == local_function()
2791 # typevar
2792 assert w.run(lambda: LocalT.__name__) == LocalT.__name__
2793 # classes
2794 assert w.run(lambda: LocalClass().method()) == LocalClass().method()
2795 # modules
2796 assert w.run(lambda: mod.local_function()) == local_function()
2797
2798 # Constructs from modules inside subfolders should be pickled
2799 # by value if a namespace module pointing to some parent folder
2800 # was registered for pickling by value. A "mock_local_folder"
2801 # namespace module falls into that category, but a
2802 # "mock_local_folder.mod" one does not.
2803 from mock_local_folder.subfolder.submod import (
2804 LocalSubmodClass,
2805 LocalSubmodT,
2806 local_submod_function,
2807 )
2808
2809 # Shorter aliases to comply with line-length limits
2810 _t, _func, _class = (
2811 LocalSubmodT,
2812 local_submod_function,
2813 LocalSubmodClass,
2814 )
2815 with pytest.raises(ImportError):
2816 w.run(lambda: __import__("mock_local_folder.subfolder.mod"))
2817 with pytest.raises(ImportError):
2818 w.run(lambda: local_submod_function)
2819
2820 unregister_pickle_by_value(mod)
2821
2822 with pytest.raises(ImportError):
2823 w.run(lambda: local_function)
2824
2825 with pytest.raises(ImportError):
2826 w.run(lambda: __import__("mock_local_folder.mod"))
2827
2828 # Test the namespace folder case
2829 import mock_local_folder
2830
2831 register_pickle_by_value(mock_local_folder)
2832 assert w.run(lambda: local_function()) == local_function()
2833 assert w.run(lambda: _func()) == _func()
2834 unregister_pickle_by_value(mock_local_folder)
2835
2836 with pytest.raises(ImportError):
2837 w.run(lambda: local_function)
2838 with pytest.raises(ImportError):
2839 w.run(lambda: local_submod_function)
2840
2841 # Test the case of registering a single module inside a
2842 # subfolder.
2843 import mock_local_folder.subfolder.submod
2844
2845 register_pickle_by_value(mock_local_folder.subfolder.submod)
2846 assert w.run(lambda: _func()) == _func()
2847 assert w.run(lambda: _t.__name__) == _t.__name__
2848 assert w.run(lambda: _class().method()) == _class().method()
2849
2850 # Registering a module from a subfolder for pickling by value
2851 # should not make constructs from modules from the parent
2852 # folder pickleable
2853 with pytest.raises(ImportError):
2854 w.run(lambda: local_function)
2855 with pytest.raises(ImportError):
2856 w.run(lambda: __import__("mock_local_folder.mod"))
2857
2858 unregister_pickle_by_value(mock_local_folder.subfolder.submod)
2859 with pytest.raises(ImportError):
2860 w.run(lambda: local_submod_function)
2861
2862 # Test the subfolder namespace module case
2863 import mock_local_folder.subfolder
2864
2865 register_pickle_by_value(mock_local_folder.subfolder)
2866 assert w.run(lambda: _func()) == _func()
2867 assert w.run(lambda: _t.__name__) == _t.__name__
2868 assert w.run(lambda: _class().method()) == _class().method()
2869
2870 unregister_pickle_by_value(mock_local_folder.subfolder)
2871 finally:
2872 _fname = "mock_local_folder"
2873 sys.path = _prev_sys_path
2874 for m in [
2875 _fname,
2876 f"{_fname}.mod",
2877 f"{_fname}.subfolder",
2878 f"{_fname}.subfolder.submod",
2879 ]:
2880 mod = sys.modules.pop(m, None)
2881 if mod and mod.__name__ in list_registry_pickle_by_value():
2882 unregister_pickle_by_value(mod)
2883
2884 def test_pickle_constructs_from_installed_packages_registered_for_pickling_by_value( # noqa
2885 self,
2886 ):
2887 for package_or_module in ["package", "module"]:
2888 if package_or_module == "package":
2889 m = pytest.importorskip("_cloudpickle_testpkg")
2890 f = m.package_function_with_global
2891 _original_global = m.global_variable
2892 elif package_or_module == "module":
2893 m = pytest.importorskip("_cloudpickle_testpkg.mod")
2894 f = m.module_function_with_global
2895 _original_global = m.global_variable
2896 try:
2897 with subprocess_worker(protocol=self.protocol) as w:
2898 assert w.run(lambda: f()) == _original_global
2899
2900 # Test that f is pickled by value by modifying a global
2901 # variable that f uses, and making sure that this
2902 # modification shows up when calling the function remotely
2903 register_pickle_by_value(m)
2904 assert w.run(lambda: f()) == _original_global
2905 m.global_variable = "modified global"
2906 assert m.global_variable != _original_global
2907 assert w.run(lambda: f()) == "modified global"
2908 unregister_pickle_by_value(m)
2909 finally:
2910 m.global_variable = _original_global
2911 if m.__name__ in list_registry_pickle_by_value():
2912 unregister_pickle_by_value(m)
2913
2914 def test_pickle_various_versions_of_the_same_function_with_different_pickling_method( # noqa
2915 self,
2916 ):
2917 # Make sure that different versions of the same function (possibly
2918 # pickled in a different way - by value and/or by reference) can
2919 # peacefully co-exist (e.g. without globals interaction) in a remote
2920 # worker.
2921 _cloudpickle_testpkg = pytest.importorskip("_cloudpickle_testpkg")
2922 f = _cloudpickle_testpkg.package_function_with_global
2923 _original_global = _cloudpickle_testpkg.global_variable
2924
2925 def _create_registry():
2926 _main = __import__("sys").modules["__main__"]
2927 _main._cloudpickle_registry = {}
2928 # global _cloudpickle_registry
2929
2930 def _add_to_registry(v, k):
2931 _main = __import__("sys").modules["__main__"]
2932 _main._cloudpickle_registry[k] = v
2933
2934 def _call_from_registry(k):
2935 _main = __import__("sys").modules["__main__"]
2936 return _main._cloudpickle_registry[k]()
2937
2938 try:
2939 with subprocess_worker(protocol=self.protocol) as w:
2940 w.run(_create_registry)
2941 w.run(_add_to_registry, f, "f_by_ref")
2942
2943 register_pickle_by_value(_cloudpickle_testpkg)
2944 _cloudpickle_testpkg.global_variable = "modified global"
2945 w.run(_add_to_registry, f, "f_by_val")
2946 assert w.run(_call_from_registry, "f_by_ref") == _original_global
2947 assert w.run(_call_from_registry, "f_by_val") == "modified global"
2948
2949 finally:
2950 _cloudpickle_testpkg.global_variable = _original_global
2951
2952 if "_cloudpickle_testpkg" in list_registry_pickle_by_value():
2953 unregister_pickle_by_value(_cloudpickle_testpkg)
2954
2955 def test_deterministic_pickle_bytes_for_function(self):
2956 # Ensure that functions with references to several global names are
2957 # pickled to fixed bytes that do not depend on the PYTHONHASHSEED of
2958 # the Python process.
2959 vals = set()
2960
2961 def func_with_globals():
2962 return _TEST_GLOBAL_VARIABLE + _TEST_GLOBAL_VARIABLE2
2963
2964 for i in range(5):
2965 vals.add(
2966 subprocess_pickle_string(
2967 func_with_globals,
2968 protocol=self.protocol,
2969 add_env={"PYTHONHASHSEED": str(i)},
2970 )
2971 )
2972 if len(vals) > 1:
2973 # Print additional debug info on stdout with dis:
2974 for val in vals:
2975 pickletools.dis(val)
2976 pytest.fail("Expected a single deterministic payload, got %d/5" % len(vals))
2977
2978 def test_dataclass_fields_are_preserved(self):
2979 @dataclasses.dataclass
2980 class SampleDataclass:
2981 x: int
2982 y: dataclasses.InitVar[int]
2983 z: typing.ClassVar[int]
2984
2985 PickledSampleDataclass = pickle_depickle(
2986 SampleDataclass, protocol=self.protocol
2987 )
2988
2989 found_fields = list(PickledSampleDataclass.__dataclass_fields__.values())
2990 assert set(f.name for f in found_fields) == {"x", "y", "z"}
2991
2992 expected_ftypes = {
2993 "x": dataclasses._FIELD,
2994 "y": dataclasses._FIELD_INITVAR,
2995 "z": dataclasses._FIELD_CLASSVAR,
2996 }
2997
2998 for f in found_fields:
2999 assert f._field_type is expected_ftypes[f.name]
3000
3001 def test_interactively_defined_dataclass_with_initvar_and_classvar(self):
3002 code = """if __name__ == "__main__":
3003 import dataclasses
3004 from testutils import subprocess_worker
3005 import typing
3006
3007 with subprocess_worker(protocol={protocol}) as w:
3008
3009 @dataclasses.dataclass
3010 class SampleDataclass:
3011 x: int
3012 y: dataclasses.InitVar[int] = None
3013 z: typing.ClassVar[int] = 42
3014
3015 def __post_init__(self, y=0):
3016 self.x += y
3017
3018 def large_enough(self):
3019 return self.x > self.z
3020
3021 value = SampleDataclass(2, y=2)
3022
3023 def check_dataclass_instance(value):
3024 assert isinstance(value, SampleDataclass)
3025 assert value.x == 4
3026 assert value.z == 42
3027 expected_dict = dict(x=4)
3028 assert dataclasses.asdict(value) == expected_dict
3029 assert not value.large_enough()
3030 try:
3031 SampleDataclass.z = 0
3032 assert value.z == 0
3033 assert value.large_enough()
3034 finally:
3035 SampleDataclass.z = 42
3036 return "ok"
3037
3038 assert check_dataclass_instance(value) == "ok"
3039
3040 # Check that this instance of an interactively defined dataclass
3041 # behavesconsistently in a remote worker process:
3042 assert w.run(check_dataclass_instance, value) == "ok"
3043
3044 # Check class provenance tracking is not impacted by the
3045 # @dataclass decorator:
3046 def echo(*args):
3047 return args
3048
3049 cloned_value, cloned_type = w.run(echo, value, SampleDataclass)
3050 assert cloned_type is SampleDataclass
3051 assert isinstance(cloned_value, SampleDataclass)
3052 """.format(protocol=self.protocol)
3053 assert_run_python_script(code)
3054
3055
3056 class Protocol2CloudPickleTest(CloudPickleTest):
3057 protocol = 2
3058
3059
3060 def test_lookup_module_and_qualname_dynamic_typevar():
3061 T = typing.TypeVar("T")
3062 module_and_name = _lookup_module_and_qualname(T, name=T.__name__)
3063 assert module_and_name is None
3064
3065
3066 def test_lookup_module_and_qualname_importable_typevar():
3067 _cloudpickle_testpkg = pytest.importorskip("_cloudpickle_testpkg")
3068 T = _cloudpickle_testpkg.T
3069 module_and_name = _lookup_module_and_qualname(T, name=T.__name__)
3070 assert module_and_name is not None
3071 module, name = module_and_name
3072 assert module is _cloudpickle_testpkg
3073 assert name == "T"
3074
3075
3076 def test_lookup_module_and_qualname_stdlib_typevar():
3077 module_and_name = _lookup_module_and_qualname(
3078 typing.AnyStr, name=typing.AnyStr.__name__
3079 )
3080 assert module_and_name is not None
3081 module, name = module_and_name
3082 assert module is typing
3083 assert name == "AnyStr"
3084
3085
3086 def test_register_pickle_by_value():
3087 pkg = pytest.importorskip("_cloudpickle_testpkg")
3088 mod = pytest.importorskip("_cloudpickle_testpkg.mod")
3089
3090 assert list_registry_pickle_by_value() == set()
3091
3092 register_pickle_by_value(pkg)
3093 assert list_registry_pickle_by_value() == {pkg.__name__}
3094
3095 register_pickle_by_value(mod)
3096 assert list_registry_pickle_by_value() == {pkg.__name__, mod.__name__}
3097
3098 unregister_pickle_by_value(mod)
3099 assert list_registry_pickle_by_value() == {pkg.__name__}
3100
3101 msg = f"Input should be a module object, got {pkg.__name__} instead"
3102 with pytest.raises(ValueError, match=msg):
3103 unregister_pickle_by_value(pkg.__name__)
3104
3105 unregister_pickle_by_value(pkg)
3106 assert list_registry_pickle_by_value() == set()
3107
3108 msg = f"{pkg} is not registered for pickle by value"
3109 with pytest.raises(ValueError, match=re.escape(msg)):
3110 unregister_pickle_by_value(pkg)
3111
3112 msg = f"Input should be a module object, got {pkg.__name__} instead"
3113 with pytest.raises(ValueError, match=msg):
3114 register_pickle_by_value(pkg.__name__)
3115
3116 dynamic_mod = types.ModuleType("dynamic_mod")
3117 msg = (
3118 f"{dynamic_mod} was not imported correctly, have you used an "
3119 "`import` statement to access it?"
3120 )
3121 with pytest.raises(ValueError, match=re.escape(msg)):
3122 register_pickle_by_value(dynamic_mod)
3123
3124
3125 def _all_types_to_test():
3126 T = typing.TypeVar("T")
3127
3128 class C(typing.Generic[T]):
3129 pass
3130
3131 types_to_test = [
3132 C,
3133 C[int],
3134 T,
3135 typing.Any,
3136 typing.Optional,
3137 typing.Generic,
3138 typing.Union,
3139 typing.Optional[int],
3140 typing.Generic[T],
3141 typing.Callable[[int], typing.Any],
3142 typing.Callable[..., typing.Any],
3143 typing.Callable[[], typing.Any],
3144 typing.Tuple[int, ...],
3145 typing.Tuple[int, C[int]],
3146 typing.List[int],
3147 typing.Dict[int, str],
3148 typing.ClassVar,
3149 typing.ClassVar[C[int]],
3150 typing.NoReturn,
3151 ]
3152 return types_to_test
3153
3154
3155 def test_module_level_pickler():
3156 # #366: cloudpickle should expose its pickle.Pickler subclass as
3157 # cloudpickle.Pickler
3158 assert hasattr(cloudpickle, "Pickler")
3159 assert cloudpickle.Pickler is cloudpickle.CloudPickler
3160
3161
3162 if __name__ == "__main__":
3163 unittest.main()