-
Notifications
You must be signed in to change notification settings - Fork 176
/
Copy pathcloudpickle_test.py
3151 lines (2439 loc) · 112 KB
/
cloudpickle_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import _collections_abc
import abc
import collections
import base64
import dataclasses
import functools
import io
import itertools
import logging
import math
import multiprocessing
from operator import itemgetter, attrgetter
import pickletools
import platform
import random
import re
import shutil
import subprocess
import sys
import tempfile
import textwrap
import types
import unittest
import weakref
import os
import enum
import typing
from functools import wraps
import pickle
import pytest
from pathlib import Path
try:
# try importing numpy and scipy. These are not hard dependencies and
# tests should be skipped if these modules are not available
import numpy as np
import scipy.special as spp
except (ImportError, RuntimeError):
np = None
spp = None
import cloudpickle
from cloudpickle import register_pickle_by_value
from cloudpickle import unregister_pickle_by_value
from cloudpickle import list_registry_pickle_by_value
from cloudpickle.cloudpickle import _should_pickle_by_reference
from cloudpickle.cloudpickle import _make_empty_cell
from cloudpickle.cloudpickle import _extract_class_dict, _whichmodule
from cloudpickle.cloudpickle import _lookup_module_and_qualname
from .testutils import subprocess_worker
from .testutils import subprocess_pickle_echo
from .testutils import subprocess_pickle_string
from .testutils import assert_run_python_script
from .testutils import check_deterministic_pickle
_TEST_GLOBAL_VARIABLE = "default_value"
_TEST_GLOBAL_VARIABLE2 = "another_value"
class RaiserOnPickle:
def __init__(self, exc):
self.exc = exc
def __reduce__(self):
raise self.exc
def pickle_depickle(obj, protocol=cloudpickle.DEFAULT_PROTOCOL):
"""Helper function to test whether object pickled with cloudpickle can be
depickled with pickle
"""
return pickle.loads(cloudpickle.dumps(obj, protocol=protocol))
def _escape(raw_filepath):
# Ugly hack to embed filepaths in code templates for windows
return raw_filepath.replace("\\", r"\\\\")
def _maybe_remove(list_, item):
try:
list_.remove(item)
except ValueError:
pass
return list_
def test_extract_class_dict():
class A(int):
"""A docstring"""
def method(self):
return "a"
class B:
"""B docstring"""
B_CONSTANT = 42
def method(self):
return "b"
class C(A, B):
C_CONSTANT = 43
def method_c(self):
return "c"
clsdict = _extract_class_dict(C)
expected_keys = ["C_CONSTANT", "__doc__", "method_c"]
# New attribute in Python 3.13 beta 1
# https://github.com/python/cpython/pull/118475
if sys.version_info >= (3, 13):
expected_keys.insert(2, "__firstlineno__")
assert list(clsdict.keys()) == expected_keys
assert clsdict["C_CONSTANT"] == 43
assert clsdict["__doc__"] is None
assert clsdict["method_c"](C()) == C().method_c()
class CloudPickleTest(unittest.TestCase):
protocol = cloudpickle.DEFAULT_PROTOCOL
def setUp(self):
self.tmpdir = tempfile.mkdtemp(prefix="tmp_cloudpickle_test_")
def tearDown(self):
shutil.rmtree(self.tmpdir)
@pytest.mark.skipif(
platform.python_implementation() != "CPython" or sys.version_info < (3, 8, 2),
reason="Underlying bug fixed upstream starting Python 3.8.2",
)
def test_reducer_override_reference_cycle(self):
# Early versions of Python 3.8 introduced a reference cycle between a
# Pickler and it's reducer_override method. Because a Pickler
# object references every object it has pickled through its memo, this
# cycle prevented the garbage-collection of those external pickled
# objects. See #327 as well as https://bugs.python.org/issue39492
# This bug was fixed in Python 3.8.2, but is still present using
# cloudpickle and Python 3.8.0/1, hence the skipif directive.
class MyClass:
pass
my_object = MyClass()
wr = weakref.ref(my_object)
cloudpickle.dumps(my_object)
del my_object
assert wr() is None, "'del'-ed my_object has not been collected"
def test_itemgetter(self):
d = range(10)
getter = itemgetter(1)
getter2 = pickle_depickle(getter, protocol=self.protocol)
self.assertEqual(getter(d), getter2(d))
getter = itemgetter(0, 3)
getter2 = pickle_depickle(getter, protocol=self.protocol)
self.assertEqual(getter(d), getter2(d))
def test_attrgetter(self):
class C:
def __getattr__(self, item):
return item
d = C()
getter = attrgetter("a")
getter2 = pickle_depickle(getter, protocol=self.protocol)
self.assertEqual(getter(d), getter2(d))
getter = attrgetter("a", "b")
getter2 = pickle_depickle(getter, protocol=self.protocol)
self.assertEqual(getter(d), getter2(d))
d.e = C()
getter = attrgetter("e.a")
getter2 = pickle_depickle(getter, protocol=self.protocol)
self.assertEqual(getter(d), getter2(d))
getter = attrgetter("e.a", "e.b")
getter2 = pickle_depickle(getter, protocol=self.protocol)
self.assertEqual(getter(d), getter2(d))
# Regression test for SPARK-3415
def test_pickling_file_handles(self):
out1 = sys.stderr
out2 = pickle.loads(cloudpickle.dumps(out1, protocol=self.protocol))
self.assertEqual(out1, out2)
def test_func_globals(self):
class Unpicklable:
def __reduce__(self):
raise Exception("not picklable")
global exit
exit = Unpicklable()
self.assertRaises(
Exception, lambda: cloudpickle.dumps(exit, protocol=self.protocol)
)
def foo():
sys.exit(0)
self.assertTrue("exit" in foo.__code__.co_names)
cloudpickle.dumps(foo)
def test_memoryview(self):
buffer_obj = memoryview(b"Hello")
self.assertEqual(
pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()
)
def test_dict_keys(self):
keys = {"a": 1, "b": 2}.keys()
results = pickle_depickle(keys)
self.assertEqual(results, keys)
assert isinstance(results, _collections_abc.dict_keys)
def test_dict_values(self):
values = {"a": 1, "b": 2}.values()
results = pickle_depickle(values)
self.assertEqual(sorted(results), sorted(values))
assert isinstance(results, _collections_abc.dict_values)
def test_dict_items(self):
items = {"a": 1, "b": 2}.items()
results = pickle_depickle(items)
self.assertEqual(results, items)
assert isinstance(results, _collections_abc.dict_items)
def test_odict_keys(self):
keys = collections.OrderedDict([("a", 1), ("b", 2)]).keys()
results = pickle_depickle(keys)
self.assertEqual(results, keys)
assert type(keys) is type(results)
def test_odict_values(self):
values = collections.OrderedDict([("a", 1), ("b", 2)]).values()
results = pickle_depickle(values)
self.assertEqual(list(results), list(values))
assert type(values) is type(results)
def test_odict_items(self):
items = collections.OrderedDict([("a", 1), ("b", 2)]).items()
results = pickle_depickle(items)
self.assertEqual(results, items)
assert type(items) is type(results)
def test_sliced_and_non_contiguous_memoryview(self):
buffer_obj = memoryview(b"Hello!" * 3)[2:15:2]
self.assertEqual(
pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()
)
def test_large_memoryview(self):
buffer_obj = memoryview(b"Hello!" * int(1e7))
self.assertEqual(
pickle_depickle(buffer_obj, protocol=self.protocol), buffer_obj.tobytes()
)
def test_lambda(self):
self.assertEqual(pickle_depickle(lambda: 1, protocol=self.protocol)(), 1)
def test_nested_lambdas(self):
a, b = 1, 2
f1 = lambda x: x + a # noqa: E731
f2 = lambda x: f1(x) // b # noqa: E731
self.assertEqual(pickle_depickle(f2, protocol=self.protocol)(1), 1)
def test_recursive_closure(self):
def f1():
def g():
return g
return g
def f2(base):
def g(n):
return base if n <= 1 else n * g(n - 1)
return g
g1 = pickle_depickle(f1(), protocol=self.protocol)
self.assertEqual(g1(), g1)
g2 = pickle_depickle(f2(2), protocol=self.protocol)
self.assertEqual(g2(5), 240)
def test_closure_none_is_preserved(self):
def f():
"""A function with no closure cells"""
self.assertTrue(
f.__closure__ is None,
msg="f actually has closure cells!",
)
g = pickle_depickle(f, protocol=self.protocol)
self.assertTrue(
g.__closure__ is None,
msg="g now has closure cells even though f does not",
)
def test_empty_cell_preserved(self):
def f():
if False: # pragma: no cover
cell = None
def g():
cell # NameError, unbound free variable
return g
g1 = f()
with pytest.raises(NameError):
g1()
g2 = pickle_depickle(g1, protocol=self.protocol)
with pytest.raises(NameError):
g2()
def test_unhashable_closure(self):
def f():
s = {1, 2} # mutable set is unhashable
def g():
return len(s)
return g
g = pickle_depickle(f(), protocol=self.protocol)
self.assertEqual(g(), 2)
def test_class_no_firstlineno_deletion_(self):
# `__firstlineno__` is a new attribute of classes introduced in Python 3.13.
# This attribute used to be automatically deleted when unpickling a class as a
# consequence of cloudpickle setting a class's `__module__` attribute at
# unpickling time (see https://github.com/python/cpython/blob/73c152b346a18ed8308e469bdd232698e6cd3a63/Objects/typeobject.c#L1353-L1356).
# This deletion would cause tests like
# `test_deterministic_dynamic_class_attr_ordering_for_chained_pickling` to fail.
# This test makes sure that the attribute `__firstlineno__` is preserved
# across a cloudpickle roundtrip.
class A:
pass
if hasattr(A, "__firstlineno__"):
A_roundtrip = pickle_depickle(A, protocol=self.protocol)
assert hasattr(A_roundtrip, "__firstlineno__")
assert A_roundtrip.__firstlineno__ == A.__firstlineno__
def test_dynamically_generated_class_that_uses_super(self):
class Base:
def method(self):
return 1
class Derived(Base):
"Derived Docstring"
def method(self):
return super().method() + 1
self.assertEqual(Derived().method(), 2)
# Pickle and unpickle the class.
UnpickledDerived = pickle_depickle(Derived, protocol=self.protocol)
self.assertEqual(UnpickledDerived().method(), 2)
# We have special logic for handling __doc__ because it's a readonly
# attribute on PyPy.
self.assertEqual(UnpickledDerived.__doc__, "Derived Docstring")
# Pickle and unpickle an instance.
orig_d = Derived()
d = pickle_depickle(orig_d, protocol=self.protocol)
self.assertEqual(d.method(), 2)
def test_cycle_in_classdict_globals(self):
class C:
def it_works(self):
return "woohoo!"
C.C_again = C
C.instance_of_C = C()
depickled_C = pickle_depickle(C, protocol=self.protocol)
depickled_instance = pickle_depickle(C())
# Test instance of depickled class.
self.assertEqual(depickled_C().it_works(), "woohoo!")
self.assertEqual(depickled_C.C_again().it_works(), "woohoo!")
self.assertEqual(depickled_C.instance_of_C.it_works(), "woohoo!")
self.assertEqual(depickled_instance.it_works(), "woohoo!")
def test_locally_defined_function_and_class(self):
LOCAL_CONSTANT = 42
def some_function(x, y):
# Make sure the __builtins__ are not broken (see #211)
sum(range(10))
return (x + y) / LOCAL_CONSTANT
# pickle the function definition
result = pickle_depickle(some_function, protocol=self.protocol)(41, 1)
assert result == 1
result = pickle_depickle(some_function, protocol=self.protocol)(81, 3)
assert result == 2
hidden_constant = lambda: LOCAL_CONSTANT # noqa: E731
class SomeClass:
"""Overly complicated class with nested references to symbols"""
def __init__(self, value):
self.value = value
def one(self):
return LOCAL_CONSTANT / hidden_constant()
def some_method(self, x):
return self.one() + some_function(x, 1) + self.value
# pickle the class definition
clone_class = pickle_depickle(SomeClass, protocol=self.protocol)
self.assertEqual(clone_class(1).one(), 1)
self.assertEqual(clone_class(5).some_method(41), 7)
clone_class = subprocess_pickle_echo(SomeClass, protocol=self.protocol)
self.assertEqual(clone_class(5).some_method(41), 7)
# pickle the class instances
self.assertEqual(pickle_depickle(SomeClass(1)).one(), 1)
self.assertEqual(pickle_depickle(SomeClass(5)).some_method(41), 7)
new_instance = subprocess_pickle_echo(SomeClass(5), protocol=self.protocol)
self.assertEqual(new_instance.some_method(41), 7)
# pickle the method instances
self.assertEqual(pickle_depickle(SomeClass(1).one)(), 1)
self.assertEqual(pickle_depickle(SomeClass(5).some_method)(41), 7)
new_method = subprocess_pickle_echo(
SomeClass(5).some_method, protocol=self.protocol
)
self.assertEqual(new_method(41), 7)
def test_partial(self):
partial_obj = functools.partial(min, 1)
partial_clone = pickle_depickle(partial_obj, protocol=self.protocol)
self.assertEqual(partial_clone(4), 1)
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="Skip numpy and scipy tests on PyPy",
)
def test_ufunc(self):
# test a numpy ufunc (universal function), which is a C-based function
# that is applied on a numpy array
if np:
# simple ufunc: np.add
self.assertEqual(pickle_depickle(np.add, protocol=self.protocol), np.add)
else: # skip if numpy is not available
pass
if spp:
# custom ufunc: scipy.special.iv
self.assertEqual(pickle_depickle(spp.iv, protocol=self.protocol), spp.iv)
else: # skip if scipy is not available
pass
def test_loads_namespace(self):
obj = 1, 2, 3, 4
returned_obj = cloudpickle.loads(cloudpickle.dumps(obj, protocol=self.protocol))
self.assertEqual(obj, returned_obj)
def test_load_namespace(self):
obj = 1, 2, 3, 4
bio = io.BytesIO()
cloudpickle.dump(obj, bio)
bio.seek(0)
returned_obj = cloudpickle.load(bio)
self.assertEqual(obj, returned_obj)
def test_generator(self):
def some_generator(cnt):
yield from range(cnt)
gen2 = pickle_depickle(some_generator, protocol=self.protocol)
assert isinstance(gen2(3), type(some_generator(3)))
assert list(gen2(3)) == list(range(3))
def test_classmethod(self):
class A:
@staticmethod
def test_sm():
return "sm"
@classmethod
def test_cm(cls):
return "cm"
sm = A.__dict__["test_sm"]
cm = A.__dict__["test_cm"]
A.test_sm = pickle_depickle(sm, protocol=self.protocol)
A.test_cm = pickle_depickle(cm, protocol=self.protocol)
self.assertEqual(A.test_sm(), "sm")
self.assertEqual(A.test_cm(), "cm")
def test_bound_classmethod(self):
class A:
@classmethod
def test_cm(cls):
return "cm"
A.test_cm = pickle_depickle(A.test_cm, protocol=self.protocol)
self.assertEqual(A.test_cm(), "cm")
def test_method_descriptors(self):
f = pickle_depickle(str.upper)
self.assertEqual(f("abc"), "ABC")
def test_instancemethods_without_self(self):
class F:
def f(self, x):
return x + 1
g = pickle_depickle(F.f, protocol=self.protocol)
self.assertEqual(g.__name__, F.f.__name__)
# self.assertEqual(g(F(), 1), 2) # still fails
def test_module(self):
pickle_clone = pickle_depickle(pickle, protocol=self.protocol)
self.assertEqual(pickle, pickle_clone)
def _check_dynamic_module(self, mod):
mod = types.ModuleType("mod")
code = """
x = 1
def f(y):
return x + y
class Foo:
def method(self, x):
return f(x)
"""
exec(textwrap.dedent(code), mod.__dict__)
mod2 = pickle_depickle(mod, protocol=self.protocol)
self.assertEqual(mod.x, mod2.x)
self.assertEqual(mod.f(5), mod2.f(5))
self.assertEqual(mod.Foo().method(5), mod2.Foo().method(5))
if platform.python_implementation() != "PyPy":
# XXX: this fails with excessive recursion on PyPy.
mod3 = subprocess_pickle_echo(mod, protocol=self.protocol)
self.assertEqual(mod.x, mod3.x)
self.assertEqual(mod.f(5), mod3.f(5))
self.assertEqual(mod.Foo().method(5), mod3.Foo().method(5))
# Test dynamic modules when imported back are singletons
mod1, mod2 = pickle_depickle([mod, mod])
self.assertEqual(id(mod1), id(mod2))
# Ensure proper pickling of mod's functions when module "looks" like a
# file-backed module even though it is not:
try:
sys.modules["mod"] = mod
depickled_f = pickle_depickle(mod.f, protocol=self.protocol)
self.assertEqual(mod.f(5), depickled_f(5))
finally:
sys.modules.pop("mod", None)
def test_dynamic_module(self):
mod = types.ModuleType("mod")
assert mod.__package__ is None
self._check_dynamic_module(mod)
def test_dynamic_module_no_package(self):
# non-regression test for #116
mod = types.ModuleType("mod")
del mod.__package__
assert not hasattr(mod, "__package__")
self._check_dynamic_module(mod)
def test_module_locals_behavior(self):
# Makes sure that a local function defined in another module is
# correctly serialized. This notably checks that the globals are
# accessible and that there is no issue with the builtins (see #211)
pickled_func_path = os.path.join(self.tmpdir, "local_func_g.pkl")
child_process_script = """
import pickle
import gc
with open("{pickled_func_path}", 'rb') as f:
func = pickle.load(f)
assert func(range(10)) == 45
"""
child_process_script = child_process_script.format(
pickled_func_path=_escape(pickled_func_path)
)
try:
from .testutils import make_local_function
g = make_local_function()
with open(pickled_func_path, "wb") as f:
cloudpickle.dump(g, f, protocol=self.protocol)
assert_run_python_script(textwrap.dedent(child_process_script))
finally:
os.unlink(pickled_func_path)
def test_dynamic_module_with_unpicklable_builtin(self):
# Reproducer of https://github.com/cloudpipe/cloudpickle/issues/316
# Some modules such as scipy inject some unpicklable objects into the
# __builtins__ module, which appears in every module's __dict__ under
# the '__builtins__' key. In such cases, cloudpickle used to fail
# when pickling dynamic modules.
class UnpickleableObject:
def __reduce__(self):
raise ValueError("Unpicklable object")
mod = types.ModuleType("mod")
exec("f = lambda x: abs(x)", mod.__dict__)
assert mod.f(-1) == 1
assert "__builtins__" in mod.__dict__
unpicklable_obj = UnpickleableObject()
with pytest.raises(ValueError):
cloudpickle.dumps(unpicklable_obj)
# Emulate the behavior of scipy by injecting an unpickleable object
# into mod's builtins.
# The __builtins__ entry of mod's __dict__ can either be the
# __builtins__ module, or the __builtins__ module's __dict__. #316
# happens only in the latter case.
if isinstance(mod.__dict__["__builtins__"], dict):
mod.__dict__["__builtins__"]["unpickleable_obj"] = unpicklable_obj
elif isinstance(mod.__dict__["__builtins__"], types.ModuleType):
mod.__dict__["__builtins__"].unpickleable_obj = unpicklable_obj
depickled_mod = pickle_depickle(mod, protocol=self.protocol)
assert "__builtins__" in depickled_mod.__dict__
if isinstance(depickled_mod.__dict__["__builtins__"], dict):
assert "abs" in depickled_mod.__builtins__
elif isinstance(depickled_mod.__dict__["__builtins__"], types.ModuleType):
assert hasattr(depickled_mod.__builtins__, "abs")
assert depickled_mod.f(-1) == 1
# Additional check testing that the issue #425 is fixed: without the
# fix for #425, `mod.f` would not have access to `__builtins__`, and
# thus calling `mod.f(-1)` (which relies on the `abs` builtin) would
# fail.
assert mod.f(-1) == 1
def test_load_dynamic_module_in_grandchild_process(self):
# Make sure that when loaded, a dynamic module preserves its dynamic
# property. Otherwise, this will lead to an ImportError if pickled in
# the child process and reloaded in another one.
# We create a new dynamic module
mod = types.ModuleType("mod")
code = """
x = 1
"""
exec(textwrap.dedent(code), mod.__dict__)
# This script will be ran in a separate child process. It will import
# the pickled dynamic module, and then re-pickle it under a new name.
# Finally, it will create a child process that will load the re-pickled
# dynamic module.
parent_process_module_file = os.path.join(
self.tmpdir, "dynamic_module_from_parent_process.pkl"
)
child_process_module_file = os.path.join(
self.tmpdir, "dynamic_module_from_child_process.pkl"
)
child_process_script = """
import pickle
import textwrap
import cloudpickle
from testutils import assert_run_python_script
child_of_child_process_script = {child_of_child_process_script}
with open('{parent_process_module_file}', 'rb') as f:
mod = pickle.load(f)
with open('{child_process_module_file}', 'wb') as f:
cloudpickle.dump(mod, f, protocol={protocol})
assert_run_python_script(textwrap.dedent(child_of_child_process_script))
"""
# The script ran by the process created by the child process
child_of_child_process_script = """ '''
import pickle
with open('{child_process_module_file}','rb') as fid:
mod = pickle.load(fid)
''' """
# Filling the two scripts with the pickled modules filepaths and,
# for the first child process, the script to be executed by its
# own child process.
child_of_child_process_script = child_of_child_process_script.format(
child_process_module_file=child_process_module_file
)
child_process_script = child_process_script.format(
parent_process_module_file=_escape(parent_process_module_file),
child_process_module_file=_escape(child_process_module_file),
child_of_child_process_script=_escape(child_of_child_process_script),
protocol=self.protocol,
)
try:
with open(parent_process_module_file, "wb") as fid:
cloudpickle.dump(mod, fid, protocol=self.protocol)
assert_run_python_script(textwrap.dedent(child_process_script))
finally:
# Remove temporary created files
if os.path.exists(parent_process_module_file):
os.unlink(parent_process_module_file)
if os.path.exists(child_process_module_file):
os.unlink(child_process_module_file)
def test_correct_globals_import(self):
def nested_function(x):
return x + 1
def unwanted_function(x):
return math.exp(x)
def my_small_function(x, y):
return nested_function(x) + y
b = cloudpickle.dumps(my_small_function, protocol=self.protocol)
# Make sure that the pickle byte string only includes the definition
# of my_small_function and its dependency nested_function while
# extra functions and modules such as unwanted_function and the math
# module are not included so as to keep the pickle payload as
# lightweight as possible.
assert b"my_small_function" in b
assert b"nested_function" in b
assert b"unwanted_function" not in b
assert b"math" not in b
def test_module_importability(self):
import pickle
import os.path
import collections
import collections.abc
assert _should_pickle_by_reference(pickle)
assert _should_pickle_by_reference(os.path) # fake (aliased) module
assert _should_pickle_by_reference(collections) # package
assert _should_pickle_by_reference(collections.abc) # module in package
dynamic_module = types.ModuleType("dynamic_module")
assert not _should_pickle_by_reference(dynamic_module)
if platform.python_implementation() == "PyPy":
import _codecs
assert _should_pickle_by_reference(_codecs)
# #354: Check that modules created dynamically during the import of
# their parent modules are considered importable by cloudpickle.
# See the mod_with_dynamic_submodule documentation for more
# details of this use case.
m = pytest.importorskip(
"_cloudpickle_testpkg.mod.dynamic_submodule"
) # noqa F841
assert _should_pickle_by_reference(m)
assert pickle_depickle(m, protocol=self.protocol) is m
# Check for similar behavior for a module that cannot be imported by
# attribute lookup.
from _cloudpickle_testpkg.mod import dynamic_submodule_two as m2
assert _should_pickle_by_reference(m2)
assert pickle_depickle(m2, protocol=self.protocol) is m2
# Submodule_three is a dynamic module only importable via module lookup
with pytest.raises(ImportError):
import _cloudpickle_testpkg.mod.submodule_three # noqa
from _cloudpickle_testpkg.mod import submodule_three as m3
assert not _should_pickle_by_reference(m3)
# This module cannot be pickled using attribute lookup (as it does not
# have a `__module__` attribute like classes and functions.
assert not hasattr(m3, "__module__")
depickled_m3 = pickle_depickle(m3, protocol=self.protocol)
assert depickled_m3 is not m3
assert m3.f(1) == depickled_m3.f(1)
# Do the same for an importable dynamic submodule inside a dynamic
# module inside a file-backed module.
import _cloudpickle_testpkg.mod.dynamic_submodule.dynamic_subsubmodule as sm # noqa
assert _should_pickle_by_reference(sm)
assert pickle_depickle(sm, protocol=self.protocol) is sm
expected = "cannot check importability of object instances"
with pytest.raises(TypeError, match=expected):
_should_pickle_by_reference(object())
def test_Ellipsis(self):
self.assertEqual(Ellipsis, pickle_depickle(Ellipsis, protocol=self.protocol))
def test_NotImplemented(self):
ExcClone = pickle_depickle(NotImplemented, protocol=self.protocol)
self.assertEqual(NotImplemented, ExcClone)
def test_NoneType(self):
res = pickle_depickle(type(None), protocol=self.protocol)
self.assertEqual(type(None), res)
def test_EllipsisType(self):
res = pickle_depickle(type(Ellipsis), protocol=self.protocol)
self.assertEqual(type(Ellipsis), res)
def test_NotImplementedType(self):
res = pickle_depickle(type(NotImplemented), protocol=self.protocol)
self.assertEqual(type(NotImplemented), res)
def test_builtin_function(self):
# Note that builtin_function_or_method are special-cased by cloudpickle
# only in python2.
# builtin function from the __builtin__ module
assert pickle_depickle(zip, protocol=self.protocol) is zip
from os import mkdir
# builtin function from a "regular" module
assert pickle_depickle(mkdir, protocol=self.protocol) is mkdir
def test_builtin_type_constructor(self):
# This test makes sure that cloudpickling builtin-type
# constructors works for all python versions/implementation.
# pickle_depickle some builtin methods of the __builtin__ module
for t in list, tuple, set, frozenset, dict, object:
cloned_new = pickle_depickle(t.__new__, protocol=self.protocol)
assert isinstance(cloned_new(t), t)
# The next 4 tests cover all cases into which builtin python methods can
# appear.
# There are 4 kinds of method: 'classic' methods, classmethods,
# staticmethods and slotmethods. They will appear under different types
# depending on whether they are called from the __dict__ of their
# class, their class itself, or an instance of their class. This makes
# 12 total combinations.
# This discussion and the following tests are relevant for the CPython
# implementation only. In PyPy, there is no builtin method or builtin
# function types/flavours. The only way into which a builtin method can be
# identified is with it's builtin-code __code__ attribute.
def test_builtin_classicmethod(self):
obj = 1.5 # float object
bound_classicmethod = obj.hex # builtin_function_or_method
unbound_classicmethod = type(obj).hex # method_descriptor
clsdict_classicmethod = type(obj).__dict__["hex"] # method_descriptor
assert unbound_classicmethod is clsdict_classicmethod
depickled_bound_meth = pickle_depickle(
bound_classicmethod, protocol=self.protocol
)
depickled_unbound_meth = pickle_depickle(
unbound_classicmethod, protocol=self.protocol
)
depickled_clsdict_meth = pickle_depickle(
clsdict_classicmethod, protocol=self.protocol
)
# No identity on the bound methods they are bound to different float
# instances
assert depickled_bound_meth() == bound_classicmethod()
assert depickled_unbound_meth is unbound_classicmethod
assert depickled_clsdict_meth is clsdict_classicmethod
def test_builtin_classmethod(self):
obj = 1.5 # float object
bound_clsmethod = obj.fromhex # builtin_function_or_method
unbound_clsmethod = type(obj).fromhex # builtin_function_or_method
depickled_bound_meth = pickle_depickle(bound_clsmethod, protocol=self.protocol)
depickled_unbound_meth = pickle_depickle(
unbound_clsmethod, protocol=self.protocol
)
# float.fromhex takes a string as input.
arg = "0x1"
# Identity on both the bound and the unbound methods cannot be
# tested: the bound methods are bound to different objects, and the
# unbound methods are actually recreated at each call.
assert depickled_bound_meth(arg) == bound_clsmethod(arg)
assert depickled_unbound_meth(arg) == unbound_clsmethod(arg)
@pytest.mark.skipif(
(
sys.version_info >= (3, 10, 8)
and platform.python_implementation() == "CPython"
),
reason=(
"CPython dropped support for pickling classmethod_descriptor,"
"https://github.com/python/cpython/issues/95196"
),
)
def test_builtin_classmethod_descriptor(self):
# `classmethod_descriptor` is the analogue `classmethod` (used for
# pure Python classes) for builtin types. Until CPython 3.10.8,
# `classmethod_descriptor` implemented an (incorrect) reducer. After
# https://github.com/python/cpython/issues/95196 revealed its
# incorrectness, this reducer was dropped (and not fixed), on the
# ground that pickling its Pythonic equivalent, `classmethod`,
# was never supported in the first place.
# Note that cloudpickle supports pickling `classmethod` objects,
# but never patched pickle's incorrect `classmethod_descriptor`
# reducer: pickling `classmethod_descriptor` objects using cloudpickle
# has always been broken.
obj = 1.5 # float object
clsdict_clsmethod = type(obj).__dict__["fromhex"] # classmethod_descriptor
depickled_clsdict_meth = pickle_depickle(
clsdict_clsmethod, protocol=self.protocol
)
# float.fromhex takes a string as input.
arg = "0x1"
if platform.python_implementation() == "CPython":
# Roundtripping a classmethod_descriptor results in a
# builtin_function_or_method (CPython upstream issue).
assert depickled_clsdict_meth(arg) == clsdict_clsmethod(float, arg)
if platform.python_implementation() == "PyPy":
# builtin-classmethods are simple classmethod in PyPy (not
# callable). We test equality of types and the functionality of the
# __func__ attribute instead. We do not test the the identity of
# the functions as __func__ attributes of classmethods are not
# pickleable and must be reconstructed at depickling time.
assert type(depickled_clsdict_meth) is type(clsdict_clsmethod)
assert depickled_clsdict_meth.__func__(
float, arg
) == clsdict_clsmethod.__func__(float, arg)
def test_builtin_slotmethod(self):
obj = 1.5 # float object
bound_slotmethod = obj.__repr__ # method-wrapper
unbound_slotmethod = type(obj).__repr__ # wrapper_descriptor
clsdict_slotmethod = type(obj).__dict__["__repr__"] # ditto
depickled_bound_meth = pickle_depickle(bound_slotmethod, protocol=self.protocol)
depickled_unbound_meth = pickle_depickle(
unbound_slotmethod, protocol=self.protocol
)
depickled_clsdict_meth = pickle_depickle(
clsdict_slotmethod, protocol=self.protocol
)
# No identity tests on the bound slotmethod are they are bound to
# different float instances
assert depickled_bound_meth() == bound_slotmethod()
assert depickled_unbound_meth is unbound_slotmethod
assert depickled_clsdict_meth is clsdict_slotmethod
@pytest.mark.skipif(
platform.python_implementation() == "PyPy",
reason="No known staticmethod example in the pypy stdlib",
)
def test_builtin_staticmethod(self):
obj = "foo" # str object
bound_staticmethod = obj.maketrans # builtin_function_or_method