FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpython/Lib/test/test_builtin.py at v3.15.0rc2 · python/cpython · GitHub
cpython/Lib/test/test_builtin.py at v3.15.0rc2 · python/cpython · GitHub
Skip to content
Navigation Menu
Sign in
Platform
GitHub
Repository hosting, code review, and collaboration
Copilot
AI coding agent for tasks, projects and automated work
Build & Ship
Actions
CI/CD and automation
Code Quality
Quality analysis, fixes, and enforcement
Codespaces
Cloud development environments
Secure
Code Security
Vulnerability detection and remediation
Secret Protection
Secret scanning and leak prevention
All Features
Learn
Documentation
Training
Certifications
Build
Build with Copilot
Customize Copilot
Integrations
Explore
Trending repos
GitHub Sponsors
Events
Changelog
Changelog
Your source for the latest features, improvements, and fixes across GitHub products, all in one place.
By Stage
Enterprises
Team
Startups
Nonprofits
By Industry
Healthcare
Financial services
Manufacturing
Government
See all industries
Evaluate GitHub
Why GitHub
Customer Stories
Business insights
Trust Center
Add-ons
GitHub Advanced Security
Enterprise-grade code security
Copilot for business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Learn & Connect
Documentation
Resource center
Blog
Events & webinars
Community Forum
Customer Stories
Integrations
Support
Customer support
Training
GitHub Status
Company
About
Partners
Changelog
GitHub Universe
GitHub Universe
The event for developers, by developers — talks, workshops, and what’s next for GitHub.
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
python
cpython
Repository navigation
Code
Issues
5k+
(5k+)
Pull requests
2.3k
(2.3k)
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Lib
/
test
/
test_builtin.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
3225 lines (2805 loc) · 118 KB
Breadcrumbs
cpython
/
Lib
/
test
/
test_builtin.py
Copy path
File metadata and controls
3225 lines (2805 loc) · 118 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
# Python test set -- built-in functions
import
ast
import
builtins
import
collections
import
contextlib
import
copy
import
decimal
import
fractions
import
gc
import
io
import
locale
import
math
import
os
import
pickle
import
platform
import
random
import
re
import
sys
import
traceback
import
types
import
typing
import
unittest
import
warnings
import
weakref
from
contextlib
import
ExitStack
from
functools
import
partial
from
inspect
import
CO_COROUTINE
from
itertools
import
product
from
textwrap
import
dedent
from
types
import
AsyncGeneratorType
,
FunctionType
,
CellType
from
operator
import
neg
from
test
import
support
from
test
.
support
import
cpython_only
,
swap_attr
from
test
.
support
import
async_yield
,
run_yielding_async_fn
from
test
.
support
import
warnings_helper
from
test
.
support
.
import_helper
import
import_module
from
test
.
support
.
os_helper
import
(
EnvironmentVarGuard
,
TESTFN
,
unlink
)
from
test
.
support
.
script_helper
import
assert_python_ok
from
test
.
support
.
testcase
import
ComplexesAreIdenticalMixin
from
test
.
support
.
warnings_helper
import
check_warnings
from
test
.
support
import
requires_IEEE_754
from
unittest
.
mock
import
MagicMock
,
patch
try
:
import
pty
,
signal
except
ImportError
:
pty
=
signal
=
None
# Detect evidence of double-rounding: sum() does not always
# get improved accuracy on machines that suffer from double rounding.
x
,
y
=
1e16
,
2.9999
# use temporary values to defeat peephole optimizer
HAVE_DOUBLE_ROUNDING
=
(
x
+
y
==
1e16
+
4
)
# used as proof of globals being used
A_GLOBAL_VALUE
=
123
A_SENTINEL
=
sentinel
(
"A_SENTINEL"
)
class
SentinelContainer
:
CLASS_SENTINEL
=
sentinel
(
"SentinelContainer.CLASS_SENTINEL"
)
class
Squares
:
def
__init__
(
self
,
max
):
self
.
max
=
max
self
.
sofar
=
[]
def
__len__
(
self
):
return
len
(
self
.
sofar
)
def
__getitem__
(
self
,
i
):
if
not
0
<=
i
<
self
.
max
:
raise
IndexError
n
=
len
(
self
.
sofar
)
while
n
<=
i
:
self
.
sofar
.
append
(
n
*
n
)
n
+=
1
return
self
.
sofar
[
i
]
class
StrSquares
:
def
__init__
(
self
,
max
):
self
.
max
=
max
self
.
sofar
=
[]
def
__len__
(
self
):
return
len
(
self
.
sofar
)
def
__getitem__
(
self
,
i
):
if
not
0
<=
i
<
self
.
max
:
raise
IndexError
n
=
len
(
self
.
sofar
)
while
n
<=
i
:
self
.
sofar
.
append
(
str
(
n
*
n
))
n
+=
1
return
self
.
sofar
[
i
]
class
BitBucket
:
def
write
(
self
,
line
):
pass
test_conv_no_sign
=
[
(
'0'
,
0
),
(
'1'
,
1
),
(
'9'
,
9
),
(
'10'
,
10
),
(
'99'
,
99
),
(
'100'
,
100
),
(
'314'
,
314
),
(
' 314'
,
314
),
(
'314 '
,
314
),
(
'
\t
\t
314
\t
\t
'
,
314
),
(
repr
(
sys
.
maxsize
),
sys
.
maxsize
),
(
' 1x'
,
ValueError
),
(
' 1 '
,
1
),
(
' 1
\02
'
,
ValueError
),
(
''
,
ValueError
),
(
' '
,
ValueError
),
(
'
\t
\t
'
,
ValueError
),
(
str
(
br'\u0663\u0661\u0664 '
,
'raw-unicode-escape'
),
314
),
(
chr
(
0x200
),
ValueError
),
]
test_conv_sign
=
[
(
'0'
,
0
),
(
'1'
,
1
),
(
'9'
,
9
),
(
'10'
,
10
),
(
'99'
,
99
),
(
'100'
,
100
),
(
'314'
,
314
),
(
' 314'
,
ValueError
),
(
'314 '
,
314
),
(
'
\t
\t
314
\t
\t
'
,
ValueError
),
(
repr
(
sys
.
maxsize
),
sys
.
maxsize
),
(
' 1x'
,
ValueError
),
(
' 1 '
,
ValueError
),
(
' 1
\02
'
,
ValueError
),
(
''
,
ValueError
),
(
' '
,
ValueError
),
(
'
\t
\t
'
,
ValueError
),
(
str
(
br'\u0663\u0661\u0664 '
,
'raw-unicode-escape'
),
314
),
(
chr
(
0x200
),
ValueError
),
]
class
TestFailingBool
:
def
__bool__
(
self
):
raise
RuntimeError
class
TestFailingIter
:
def
__iter__
(
self
):
raise
RuntimeError
def
filter_char
(
arg
):
return
ord
(
arg
)
>
ord
(
"d"
)
def
map_char
(
arg
):
return
chr
(
ord
(
arg
)
+
1
)
def
pack
(
*
args
):
return
args
class
BuiltinTest
(
ComplexesAreIdenticalMixin
,
unittest
.
TestCase
):
# Helper to check picklability
def
check_iter_pickle
(
self
,
it
,
seq
,
proto
):
itorg
=
it
d
=
pickle
.
dumps
(
it
,
proto
)
it
=
pickle
.
loads
(
d
)
self
.
assertEqual
(
type
(
itorg
),
type
(
it
))
self
.
assertEqual
(
list
(
it
),
seq
)
#test the iterator after dropping one from it
it
=
pickle
.
loads
(
d
)
try
:
next
(
it
)
except
StopIteration
:
return
d
=
pickle
.
dumps
(
it
,
proto
)
it
=
pickle
.
loads
(
d
)
self
.
assertEqual
(
list
(
it
),
seq
[
1
:])
def
test_import
(
self
):
__import__
(
'sys'
)
__import__
(
'time'
)
__import__
(
'string'
)
__import__
(
name
=
'sys'
)
__import__
(
name
=
'time'
,
level
=
0
)
self
.
assertRaises
(
ModuleNotFoundError
,
__import__
,
'spamspam'
)
self
.
assertRaises
(
TypeError
,
__import__
,
1
,
2
,
3
,
4
)
self
.
assertRaises
(
ValueError
,
__import__
,
''
)
self
.
assertRaises
(
TypeError
,
__import__
,
'sys'
,
name
=
'sys'
)
# Relative import outside of a package with no __package__ or __spec__ (bpo-37409).
with
self
.
assertWarns
(
ImportWarning
):
self
.
assertRaises
(
ImportError
,
__import__
,
''
,
{
'__package__'
:
None
,
'__spec__'
:
None
,
'__name__'
:
'__main__'
},
locals
=
{},
fromlist
=
(
'foo'
,),
level
=
1
)
# embedded null character
self
.
assertRaises
(
ModuleNotFoundError
,
__import__
,
'string
\x00
'
)
def
test_abs
(
self
):
# int
self
.
assertEqual
(
abs
(
0
),
0
)
self
.
assertEqual
(
abs
(
1234
),
1234
)
self
.
assertEqual
(
abs
(
-
1234
),
1234
)
self
.
assertTrue
(
abs
(
-
sys
.
maxsize
-
1
)
>
0
)
# float
self
.
assertEqual
(
abs
(
0.0
),
0.0
)
self
.
assertEqual
(
abs
(
3.14
),
3.14
)
self
.
assertEqual
(
abs
(
-
3.14
),
3.14
)
# str
self
.
assertRaises
(
TypeError
,
abs
,
'a'
)
# bool
self
.
assertEqual
(
abs
(
True
),
1
)
self
.
assertEqual
(
abs
(
False
),
0
)
# other
self
.
assertRaises
(
TypeError
,
abs
)
self
.
assertRaises
(
TypeError
,
abs
,
None
)
class
AbsClass
(
object
):
def
__abs__
(
self
):
return
-
5
self
.
assertEqual
(
abs
(
AbsClass
()),
-
5
)
def
test_all
(
self
):
self
.
assertEqual
(
all
([
2
,
4
,
6
]),
True
)
self
.
assertEqual
(
all
([
2
,
None
,
6
]),
False
)
self
.
assertRaises
(
RuntimeError
,
all
, [
2
,
TestFailingBool
(),
6
])
self
.
assertRaises
(
RuntimeError
,
all
,
TestFailingIter
())
self
.
assertRaises
(
TypeError
,
all
,
10
)
# Non-iterable
self
.
assertRaises
(
TypeError
,
all
)
# No args
self
.
assertRaises
(
TypeError
,
all
, [
2
,
4
,
6
], [])
# Too many args
self
.
assertEqual
(
all
([]),
True
)
# Empty iterator
self
.
assertEqual
(
all
([
0
,
TestFailingBool
()]),
False
)
# Short-circuit
S
=
[
50
,
60
]
self
.
assertEqual
(
all
(
x
>
42
for
x
in
S
),
True
)
S
=
[
50
,
40
,
60
]
self
.
assertEqual
(
all
(
x
>
42
for
x
in
S
),
False
)
S
=
[
50
,
40
,
60
,
TestFailingBool
()]
self
.
assertEqual
(
all
(
x
>
42
for
x
in
S
),
False
)
def
test_any
(
self
):
self
.
assertEqual
(
any
([
None
,
None
,
None
]),
False
)
self
.
assertEqual
(
any
([
None
,
4
,
None
]),
True
)
self
.
assertRaises
(
RuntimeError
,
any
, [
None
,
TestFailingBool
(),
6
])
self
.
assertRaises
(
RuntimeError
,
any
,
TestFailingIter
())
self
.
assertRaises
(
TypeError
,
any
,
10
)
# Non-iterable
self
.
assertRaises
(
TypeError
,
any
)
# No args
self
.
assertRaises
(
TypeError
,
any
, [
2
,
4
,
6
], [])
# Too many args
self
.
assertEqual
(
any
([]),
False
)
# Empty iterator
self
.
assertEqual
(
any
([
1
,
TestFailingBool
()]),
True
)
# Short-circuit
S
=
[
40
,
60
,
30
]
self
.
assertEqual
(
any
(
x
>
42
for
x
in
S
),
True
)
S
=
[
40
,
60
,
30
,
TestFailingBool
()]
self
.
assertEqual
(
any
(
x
>
42
for
x
in
S
),
True
)
S
=
[
10
,
20
,
30
]
self
.
assertEqual
(
any
(
x
>
42
for
x
in
S
),
False
)
def
test_all_any_tuple_list_set_optimization
(
self
):
def
f_all
():
return
all
(
x
-
2
for
x
in
[
1
,
2
,
3
])
def
f_any
():
return
any
(
x
-
1
for
x
in
[
1
,
2
,
3
])
def
f_tuple
():
return
tuple
(
2
*
x
for
x
in
[
1
,
2
,
3
])
def
f_list
():
return
list
(
2
*
x
for
x
in
[
1
,
2
,
3
])
def
f_set
():
return
set
(
2
*
x
for
x
in
[
1
,
2
,
3
])
funcs
=
[
f_all
,
f_any
,
f_tuple
,
f_list
,
f_set
]
for
f
in
funcs
:
# check that generator code object is not duplicated
code_objs
=
[
c
for
c
in
f
.
__code__
.
co_consts
if
isinstance
(
c
,
type
(
f
.
__code__
))]
self
.
assertEqual
(
len
(
code_objs
),
1
)
# check the overriding the builtins works
global
all
,
any
,
tuple
,
list
,
set
saved
=
all
,
any
,
tuple
,
list
,
set
try
:
all
=
lambda
x
:
"all"
any
=
lambda
x
:
"any"
tuple
=
lambda
x
:
"tuple"
list
=
lambda
x
:
"list"
set
=
lambda
x
:
"set"
overridden_outputs
=
[
f
()
for
f
in
funcs
]
finally
:
all
,
any
,
tuple
,
list
,
set
=
saved
self
.
assertEqual
(
overridden_outputs
, [
'all'
,
'any'
,
'tuple'
,
'list'
,
'set'
])
# Now repeat, overriding the builtins module as well
saved
=
all
,
any
,
tuple
,
list
,
set
try
:
builtins
.
all
=
all
=
lambda
x
:
"all"
builtins
.
any
=
any
=
lambda
x
:
"any"
builtins
.
tuple
=
tuple
=
lambda
x
:
"tuple"
builtins
.
list
=
list
=
lambda
x
:
"list"
builtins
.
set
=
set
=
lambda
x
:
"set"
overridden_outputs
=
[
f
()
for
f
in
funcs
]
finally
:
all
,
any
,
tuple
,
list
,
set
=
saved
builtins
.
all
,
builtins
.
any
,
builtins
.
tuple
,
builtins
.
list
,
builtins
.
set
=
saved
self
.
assertEqual
(
overridden_outputs
, [
'all'
,
'any'
,
'tuple'
,
'list'
,
'set'
])
def
test_builtin_call_async_genexpr_no_crash
(
self
):
async
def
f_all
():
return
all
(
await
2
for
_
in
[])
async
def
f_any
():
return
any
(
await
2
for
_
in
[])
async
def
f_tuple
():
return
tuple
(
await
2
for
_
in
[])
async
def
f_list
():
return
list
(
await
2
for
_
in
[])
async
def
f_set
():
return
set
(
await
2
for
_
in
[])
for
f
in
(
f_all
,
f_any
,
f_tuple
,
f_list
,
f_set
):
with
self
.
subTest
(
func
=
f
.
__name__
):
with
self
.
assertRaises
(
TypeError
):
run_yielding_async_fn
(
f
)
def
test_ascii
(
self
):
self
.
assertEqual
(
ascii
(
''
),
'
\'
\'
'
)
self
.
assertEqual
(
ascii
(
0
),
'0'
)
self
.
assertEqual
(
ascii
(()),
'()'
)
self
.
assertEqual
(
ascii
([]),
'[]'
)
self
.
assertEqual
(
ascii
({}),
'{}'
)
a
=
[]
a
.
append
(
a
)
self
.
assertEqual
(
ascii
(
a
),
'[[...]]'
)
a
=
{}
a
[
0
]
=
a
self
.
assertEqual
(
ascii
(
a
),
'{0: {...}}'
)
# Advanced checks for unicode strings
def
_check_uni
(
s
):
self
.
assertEqual
(
ascii
(
s
),
repr
(
s
))
_check_uni
(
"'"
)
_check_uni
(
'"'
)
_check_uni
(
'"
\'
'
)
_check_uni
(
'
\0
'
)
_check_uni
(
'
\r
\n
\t
.'
)
# Unprintable non-ASCII characters
_check_uni
(
'
\x85
'
)
_check_uni
(
'
\u1fff
'
)
_check_uni
(
'
\U00012fff
'
)
# Lone surrogates
_check_uni
(
'
\ud800
'
)
_check_uni
(
'
\udfff
'
)
# Issue #9804: surrogates should be joined even for printable
# wide characters (UCS-2 builds).
self
.
assertEqual
(
ascii
(
'
\U0001d121
'
),
"'
\\
U0001d121'"
)
# All together
s
=
"'
\0
\"
\n
\r
\t
abcd
\x85
é
\U00012fff
\uD800
\U0001D121
xxx."
self
.
assertEqual
(
ascii
(
s
),
r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'"""
)
def
test_neg
(
self
):
x
=
-
sys
.
maxsize
-
1
self
.
assertTrue
(
isinstance
(
x
,
int
))
self
.
assertEqual
(
-
x
,
sys
.
maxsize
+
1
)
def
test_callable
(
self
):
self
.
assertTrue
(
callable
(
len
))
self
.
assertFalse
(
callable
(
"a"
))
self
.
assertTrue
(
callable
(
callable
))
self
.
assertTrue
(
callable
(
lambda
x
,
y
:
x
+
y
))
self
.
assertFalse
(
callable
(
__builtins__
))
def
f
():
pass
self
.
assertTrue
(
callable
(
f
))
class
C1
:
def
meth
(
self
):
pass
self
.
assertTrue
(
callable
(
C1
))
c
=
C1
()
self
.
assertTrue
(
callable
(
c
.
meth
))
self
.
assertFalse
(
callable
(
c
))
# __call__ is looked up on the class, not the instance
c
.
__call__
=
None
self
.
assertFalse
(
callable
(
c
))
c
.
__call__
=
lambda
self
:
0
self
.
assertFalse
(
callable
(
c
))
del
c
.
__call__
self
.
assertFalse
(
callable
(
c
))
class
C2
(
object
):
def
__call__
(
self
):
pass
c2
=
C2
()
self
.
assertTrue
(
callable
(
c2
))
c2
.
__call__
=
None
self
.
assertTrue
(
callable
(
c2
))
class
C3
(
C2
):
pass
c3
=
C3
()
self
.
assertTrue
(
callable
(
c3
))
def
test_chr
(
self
):
self
.
assertEqual
(
chr
(
0
),
'
\0
'
)
self
.
assertEqual
(
chr
(
32
),
' '
)
self
.
assertEqual
(
chr
(
65
),
'A'
)
self
.
assertEqual
(
chr
(
97
),
'a'
)
self
.
assertEqual
(
chr
(
0xff
),
'
\xff
'
)
self
.
assertRaises
(
TypeError
,
chr
)
self
.
assertRaises
(
TypeError
,
chr
,
65.0
)
self
.
assertEqual
(
chr
(
0x0000FFFF
),
"
\U0000FFFF
"
)
self
.
assertEqual
(
chr
(
0x00010000
),
"
\U00010000
"
)
self
.
assertEqual
(
chr
(
0x00010001
),
"
\U00010001
"
)
self
.
assertEqual
(
chr
(
0x000FFFFE
),
"
\U000FFFFE
"
)
self
.
assertEqual
(
chr
(
0x000FFFFF
),
"
\U000FFFFF
"
)
self
.
assertEqual
(
chr
(
0x00100000
),
"
\U00100000
"
)
self
.
assertEqual
(
chr
(
0x00100001
),
"
\U00100001
"
)
self
.
assertEqual
(
chr
(
0x0010FFFE
),
"
\U0010FFFE
"
)
self
.
assertEqual
(
chr
(
0x0010FFFF
),
"
\U0010FFFF
"
)
self
.
assertRaises
(
ValueError
,
chr
,
-
1
)
self
.
assertRaises
(
ValueError
,
chr
,
0x00110000
)
self
.
assertRaises
(
ValueError
,
chr
,
1
<<
24
)
self
.
assertRaises
(
ValueError
,
chr
,
2
**
32
-
1
)
self
.
assertRaises
(
ValueError
,
chr
,
-
2
**
32
)
self
.
assertRaises
(
ValueError
,
chr
,
2
**
1000
)
self
.
assertRaises
(
ValueError
,
chr
,
-
2
**
1000
)
def
test_cmp
(
self
):
self
.
assertNotHasAttr
(
builtins
,
"cmp"
)
def
test_compile
(
self
):
compile
(
'print(1)
\n
'
,
''
,
'exec'
)
bom
=
b'
\xef
\xbb
\xbf
'
compile
(
bom
+
b'print(1)
\n
'
,
''
,
'exec'
)
compile
(
source
=
'pass'
,
filename
=
'?'
,
mode
=
'exec'
)
compile
(
dont_inherit
=
False
,
filename
=
'tmp'
,
source
=
'0'
,
mode
=
'eval'
)
compile
(
'pass'
,
'?'
,
dont_inherit
=
True
,
mode
=
'exec'
)
compile
(
memoryview
(
b"text"
),
"name"
,
"exec"
)
self
.
assertRaises
(
TypeError
,
compile
)
self
.
assertRaises
(
ValueError
,
compile
,
'print(42)
\n
'
,
'<string>'
,
'badmode'
)
self
.
assertRaises
(
ValueError
,
compile
,
'print(42)
\n
'
,
'<string>'
,
'single'
,
0xff
)
self
.
assertRaises
(
TypeError
,
compile
,
'pass'
,
'?'
,
'exec'
,
mode
=
'eval'
,
source
=
'0'
,
filename
=
'tmp'
)
compile
(
'print("
\xe5
")
\n
'
,
''
,
'exec'
)
self
.
assertRaises
(
SyntaxError
,
compile
,
chr
(
0
),
'f'
,
'exec'
)
self
.
assertRaises
(
ValueError
,
compile
,
str
(
'a = 1'
),
'f'
,
'bad'
)
# test the optimize argument
codestr
=
'''def f():
"""doc"""
debug_enabled = False
if __debug__:
debug_enabled = True
try:
assert False
except AssertionError:
return (True, f.__doc__, debug_enabled, __debug__)
else:
return (False, f.__doc__, debug_enabled, __debug__)
'''
def
f
():
"""doc"""
values
=
[(
-
1
,
__debug__
,
f
.
__doc__
,
__debug__
,
__debug__
),
(
0
,
True
,
'doc'
,
True
,
True
),
(
1
,
False
,
'doc'
,
False
,
False
),
(
2
,
False
,
None
,
False
,
False
)]
for
optval
,
*
expected
in
values
:
with
self
.
subTest
(
optval
=
optval
):
# test both direct compilation and compilation via AST
codeobjs
=
[]
codeobjs
.
append
(
compile
(
codestr
,
"<test>"
,
"exec"
,
optimize
=
optval
))
tree
=
ast
.
parse
(
codestr
,
optimize
=
optval
)
codeobjs
.
append
(
compile
(
tree
,
"<test>"
,
"exec"
,
optimize
=
optval
))
for
code
in
codeobjs
:
ns
=
{}
exec
(
code
,
ns
)
rv
=
ns
[
'f'
]()
self
.
assertEqual
(
rv
,
tuple
(
expected
))
def
test_compile_top_level_await_no_coro
(
self
):
"""Make sure top level non-await codes get the correct coroutine flags"""
modes
=
(
'single'
,
'exec'
)
code_samples
=
[
'''def f():pass
\n
'''
,
'''[x for x in l]'''
,
'''{x for x in l}'''
,
'''(x for x in l)'''
,
'''{x:x for x in l}'''
,
]
for
mode
,
code_sample
in
product
(
modes
,
code_samples
):
source
=
dedent
(
code_sample
)
co
=
compile
(
source
,
'?'
,
mode
,
flags
=
ast
.
PyCF_ALLOW_TOP_LEVEL_AWAIT
)
self
.
assertNotEqual
(
co
.
co_flags
&
CO_COROUTINE
,
CO_COROUTINE
,
msg
=
f"source=
{
source
}
mode=
{
mode
}
"
)
def
test_compile_top_level_await
(
self
):
"""Test whether code with top level await can be compiled.
Make sure it compiles only with the PyCF_ALLOW_TOP_LEVEL_AWAIT flag
set, and make sure the generated code object has the CO_COROUTINE flag
set in order to execute it with `await eval(.....)` instead of exec,
or via a FunctionType.
"""
# helper function just to check we can run top=level async-for
async
def
arange
(
n
):
for
i
in
range
(
n
):
yield
i
class
Lock
:
async
def
__aenter__
(
self
):
return
self
async
def
__aexit__
(
self
,
*
exc_info
):
pass
async
def
sleep
(
delay
,
result
=
None
):
assert
delay
==
0
await
async_yield
(
None
)
return
result
modes
=
(
'single'
,
'exec'
)
optimizations
=
(
-
1
,
0
,
1
,
2
)
code_samples
=
[
'''a = await sleep(0, result=1)'''
,
'''async for i in arange(1):
a = 1'''
,
'''async with Lock() as l:
a = 1'''
,
'''a = [x async for x in arange(2)][1]'''
,
'''a = 1 in {x async for x in arange(2)}'''
,
'''a = {x:1 async for x in arange(1)}[0]'''
,
'''a = [x async for x in arange(2) async for x in arange(2)][1]'''
,
'''a = [x async for x in (x async for x in arange(5))][1]'''
,
'''a, = [1 for x in {x async for x in arange(1)}]'''
,
'''a = [await sleep(0, x) async for x in arange(2)][1]'''
,
# gh-121637: Make sure we correctly handle the case where the
# async code is optimized away
'''assert not await sleep(0); a = 1'''
,
'''assert [x async for x in arange(1)]; a = 1'''
,
'''assert {x async for x in arange(1)}; a = 1'''
,
'''assert {x: x async for x in arange(1)}; a = 1'''
,
'''
if (a := 1) and __debug__:
async with Lock() as l:
pass
'''
,
'''
if (a := 1) and __debug__:
async for x in arange(2):
pass
'''
,
]
for
mode
,
code_sample
,
optimize
in
product
(
modes
,
code_samples
,
optimizations
):
with
self
.
subTest
(
mode
=
mode
,
code_sample
=
code_sample
,
optimize
=
optimize
):
source
=
dedent
(
code_sample
)
with
self
.
assertRaises
(
SyntaxError
,
msg
=
f"source=
{
source
}
mode=
{
mode
}
"
):
compile
(
source
,
'?'
,
mode
,
optimize
=
optimize
)
co
=
compile
(
source
,
'?'
,
mode
,
flags
=
ast
.
PyCF_ALLOW_TOP_LEVEL_AWAIT
,
optimize
=
optimize
)
self
.
assertEqual
(
co
.
co_flags
&
CO_COROUTINE
,
CO_COROUTINE
,
msg
=
f"source=
{
source
}
mode=
{
mode
}
"
)
# test we can create and advance a function type
globals_
=
{
'Lock'
:
Lock
,
'a'
:
0
,
'arange'
:
arange
,
'sleep'
:
sleep
}
run_yielding_async_fn
(
FunctionType
(
co
,
globals_
))
self
.
assertEqual
(
globals_
[
'a'
],
1
)
# test we can await-eval,
globals_
=
{
'Lock'
:
Lock
,
'a'
:
0
,
'arange'
:
arange
,
'sleep'
:
sleep
}
run_yielding_async_fn
(
lambda
:
eval
(
co
,
globals_
))
self
.
assertEqual
(
globals_
[
'a'
],
1
)
def
test_compile_top_level_await_invalid_cases
(
self
):
# helper function just to check we can run top=level async-for
async
def
arange
(
n
):
for
i
in
range
(
n
):
yield
i
class
Lock
:
async
def
__aenter__
(
self
):
return
self
async
def
__aexit__
(
self
,
*
exc_info
):
pass
modes
=
(
'single'
,
'exec'
)
code_samples
=
[
'''def f(): await arange(10)
\n
'''
,
'''def f(): [x async for x in arange(10)]
\n
'''
,
'''def f(): [await x async for x in arange(10)]
\n
'''
,
'''def f():
async for i in arange(1):
a = 1
'''
,
'''def f():
async with Lock() as l:
a = 1
'''
]
for
mode
,
code_sample
in
product
(
modes
,
code_samples
):
source
=
dedent
(
code_sample
)
with
self
.
assertRaises
(
SyntaxError
,
msg
=
f"source=
{
source
}
mode=
{
mode
}
"
):
compile
(
source
,
'?'
,
mode
)
with
self
.
assertRaises
(
SyntaxError
,
msg
=
f"source=
{
source
}
mode=
{
mode
}
"
):
co
=
compile
(
source
,
'?'
,
mode
,
flags
=
ast
.
PyCF_ALLOW_TOP_LEVEL_AWAIT
)
def
test_compile_async_generator
(
self
):
"""
With the PyCF_ALLOW_TOP_LEVEL_AWAIT flag added in 3.8, we want to
make sure AsyncGenerators are still properly not marked with the
CO_COROUTINE flag.
"""
code
=
dedent
(
"""async def ticker():
for i in range(10):
yield i
await sleep(0)"""
)
co
=
compile
(
code
,
'?'
,
'exec'
,
flags
=
ast
.
PyCF_ALLOW_TOP_LEVEL_AWAIT
)
glob
=
{}
exec
(
co
,
glob
)
self
.
assertEqual
(
type
(
glob
[
'ticker'
]()),
AsyncGeneratorType
)
def
test_compile_ast
(
self
):
args
=
(
"a*__debug__"
,
"f.py"
,
"exec"
)
raw
=
compile
(
*
args
,
flags
=
ast
.
PyCF_ONLY_AST
).
body
[
0
]
opt1
=
compile
(
*
args
,
flags
=
ast
.
PyCF_OPTIMIZED_AST
).
body
[
0
]
opt2
=
compile
(
ast
.
parse
(
args
[
0
]),
*
args
[
1
:],
flags
=
ast
.
PyCF_OPTIMIZED_AST
).
body
[
0
]
for
tree
in
(
raw
,
opt1
,
opt2
):
self
.
assertIsInstance
(
tree
.
value
,
ast
.
BinOp
)
self
.
assertIsInstance
(
tree
.
value
.
op
,
ast
.
Mult
)
self
.
assertIsInstance
(
tree
.
value
.
left
,
ast
.
Name
)
self
.
assertEqual
(
tree
.
value
.
left
.
id
,
'a'
)
raw_right
=
raw
.
value
.
right
self
.
assertIsInstance
(
raw_right
,
ast
.
Name
)
self
.
assertEqual
(
raw_right
.
id
,
"__debug__"
)
for
opt
in
[
opt1
,
opt2
]:
opt_right
=
opt
.
value
.
right
self
.
assertIsInstance
(
opt_right
,
ast
.
Constant
)
self
.
assertEqual
(
opt_right
.
value
,
__debug__
)
def
test_delattr
(
self
):
sys
.
spam
=
1
delattr
(
sys
,
'spam'
)
self
.
assertRaises
(
TypeError
,
delattr
)
self
.
assertRaises
(
TypeError
,
delattr
,
sys
)
msg
=
r"^attribute name must be string, not 'int'$"
self
.
assertRaisesRegex
(
TypeError
,
msg
,
delattr
,
sys
,
1
)
def
test_dir
(
self
):
# dir(wrong number of arguments)
self
.
assertRaises
(
TypeError
,
dir
,
42
,
42
)
# dir() - local scope
local_var
=
1
self
.
assertIn
(
'local_var'
,
dir
())
# dir(module)
self
.
assertIn
(
'exit'
,
dir
(
sys
))
# dir(module_with_invalid__dict__)
class
Foo
(
types
.
ModuleType
):
__dict__
=
8
f
=
Foo
(
"foo"
)
self
.
assertRaises
(
TypeError
,
dir
,
f
)
# dir(type)
self
.
assertIn
(
"strip"
,
dir
(
str
))
self
.
assertNotIn
(
"__mro__"
,
dir
(
str
))
# dir(obj)
class
Foo
(
object
):
def
__init__
(
self
):
self
.
x
=
7
self
.
y
=
8
self
.
z
=
9
f
=
Foo
()
self
.
assertIn
(
"y"
,
dir
(
f
))
# dir(obj_no__dict__)
class
Foo
(
object
):
__slots__
=
[]
f
=
Foo
()
self
.
assertIn
(
"__repr__"
,
dir
(
f
))
# dir(obj_no__class__with__dict__)
# (an ugly trick to cause getattr(f, "__class__") to fail)
class
Foo
(
object
):
__slots__
=
[
"__class__"
,
"__dict__"
]
def
__init__
(
self
):
self
.
bar
=
"wow"
f
=
Foo
()
self
.
assertNotIn
(
"__repr__"
,
dir
(
f
))
self
.
assertIn
(
"bar"
,
dir
(
f
))
# dir(obj_using __dir__)
class
Foo
(
object
):
def
__dir__
(
self
):
return
[
"kan"
,
"ga"
,
"roo"
]
f
=
Foo
()
self
.
assertTrue
(
dir
(
f
)
==
[
"ga"
,
"kan"
,
"roo"
])
# dir(obj__dir__tuple)
class
Foo
(
object
):
def
__dir__
(
self
):
return
(
"b"
,
"c"
,
"a"
)
res
=
dir
(
Foo
())
self
.
assertIsInstance
(
res
,
list
)
self
.
assertTrue
(
res
==
[
"a"
,
"b"
,
"c"
])
# dir(obj__dir__iterable)
class
Foo
(
object
):
def
__dir__
(
self
):
return
{
"b"
,
"c"
,
"a"
}
res
=
dir
(
Foo
())
self
.
assertIsInstance
(
res
,
list
)
self
.
assertEqual
(
sorted
(
res
), [
"a"
,
"b"
,
"c"
])
# dir(obj__dir__not_sequence)
class
Foo
(
object
):
def
__dir__
(
self
):
return
7
f
=
Foo
()
self
.
assertRaises
(
TypeError
,
dir
,
f
)
# dir(traceback)
try
:
raise
IndexError
except
IndexError
as
e
:
self
.
assertEqual
(
len
(
dir
(
e
.
__traceback__
)),
4
)
# test that object has a __dir__()
self
.
assertEqual
(
sorted
([].
__dir__
()),
dir
([]))
def
test___ne__
(
self
):
self
.
assertFalse
(
None
.
__ne__
(
None
))
self
.
assertIs
(
None
.
__ne__
(
0
),
NotImplemented
)
self
.
assertIs
(
None
.
__ne__
(
"abc"
),
NotImplemented
)
def
test_divmod
(
self
):
self
.
assertEqual
(
divmod
(
12
,
7
), (
1
,
5
))
self
.
assertEqual
(
divmod
(
-
12
,
7
), (
-
2
,
2
))
self
.
assertEqual
(
divmod
(
12
,
-
7
), (
-
2
,
-
2
))
self
.
assertEqual
(
divmod
(
-
12
,
-
7
), (
1
,
-
5
))
self
.
assertEqual
(
divmod
(
-
sys
.
maxsize
-
1
,
-
1
), (
sys
.
maxsize
+
1
,
0
))
for
num
,
denom
,
exp_result
in
[ (
3.25
,
1.0
, (
3.0
,
0.25
)),
(
-
3.25
,
1.0
, (
-
4.0
,
0.75
)),
(
3.25
,
-
1.0
, (
-
4.0
,
-
0.75
)),
(
-
3.25
,
-
1.0
, (
3.0
,
-
0.25
))]:
result
=
divmod
(
num
,
denom
)
self
.
assertAlmostEqual
(
result
[
0
],
exp_result
[
0
])
self
.
assertAlmostEqual
(
result
[
1
],
exp_result
[
1
])
self
.
assertRaises
(
TypeError
,
divmod
)
self
.
assertRaisesRegex
(
ZeroDivisionError
,
"division by zero"
,
divmod
,
1
,
0
,
)
self
.
assertRaisesRegex
(
ZeroDivisionError
,
"division by zero"
,
divmod
,
0.0
,
0
,
)
def
test_eval
(
self
):
self
.
assertEqual
(
eval
(
'1+1'
),
2
)
self
.
assertEqual
(
eval
(
' 1+1
\n
'
),
2
)
globals
=
{
'a'
:
1
,
'b'
:
2
}
locals
=
{
'b'
:
200
,
'c'
:
300
}
self
.
assertEqual
(
eval
(
'a'
,
globals
) ,
1
)
self
.
assertEqual
(
eval
(
'a'
,
globals
,
locals
),
1
)
self
.
assertEqual
(
eval
(
'b'
,
globals
,
locals
),
200
)
self
.
assertEqual
(
eval
(
'c'
,
globals
,
locals
),
300
)
globals
=
{
'a'
:
1
,
'b'
:
2
}
locals
=
{
'b'
:
200
,
'c'
:
300
}
bom
=
b'
\xef
\xbb
\xbf
'
self
.
assertEqual
(
eval
(
bom
+
b'a'
,
globals
,
locals
),
1
)
self
.
assertEqual
(
eval
(
'"
\xe5
"'
,
globals
),
"
\xe5
"
)
self
.
assertRaises
(
TypeError
,
eval
)
self
.
assertRaises
(
TypeError
,
eval
, ())
self
.
assertRaises
(
SyntaxError
,
eval
,
bom
[:
2
]
+
b'a'
)
class
X
:
def
__getitem__
(
self
,
key
):
raise
ValueError
self
.
assertRaises
(
ValueError
,
eval
,
"foo"
, {},
X
())
def
test_eval_frozendict
(
self
):
ns
=
frozendict
(
x
=
1
,
data
=
[],
__builtins__
=
__builtins__
)
eval
(
"data.append(x)"
,
ns
,
ns
)
self
.
assertEqual
(
ns
[
'data'
], [
1
])
ns
=
frozendict
()
errmsg
=
"cannot assign __builtins__ to frozendict globals"
with
self
.
assertRaisesRegex
(
TypeError
,
errmsg
):
eval
(
""
,
ns
,
ns
)
def
test_eval_kwargs
(
self
):
data
=
{
"A_GLOBAL_VALUE"
:
456
}
self
.
assertEqual
(
eval
(
"globals()['A_GLOBAL_VALUE']"
,
globals
=
data
),
456
)
self
.
assertEqual
(
eval
(
"globals()['A_GLOBAL_VALUE']"
,
locals
=
data
),
123
)
def
test_general_eval
(
self
):
# Tests that general mappings can be used for the locals argument
class
M
:
"Test mapping interface versus possible calls from eval()."
def
__getitem__
(
self
,
key
):
if
key
==
'a'
:
return
12
raise
KeyError
def
keys
(
self
):
return
list
(
'xyz'
)
m
=
M
()
g
=
globals
()
self
.
assertEqual
(
eval
(
'a'
,
g
,
m
),
12
)
self
.
assertRaises
(
NameError
,
eval
,
'b'
,
g
,
m
)
self
.
assertEqual
(
eval
(
'dir()'
,
g
,
m
),
list
(
'xyz'
))
self
.
assertEqual
(
eval
(
'globals()'
,
g
,
m
),
g
)
self
.
assertEqual
(
eval
(
'locals()'
,
g
,
m
),
m
)
self
.
assertRaises
(
TypeError
,
eval
,
'a'
,
m
)
class
A
:
"Non-mapping"
pass
m
=
A
()
self
.
assertRaises
(
TypeError
,
eval
,
'a'
,
g
,
m
)
# Verify that dict subclasses work as well
class
D
(
dict
):
def
__getitem__
(
self
,
key
):
if
key
==
'a'
:
return
12
return
dict
.
__getitem__
(
self
,
key
)
def
keys
(
self
):
return
list
(
'xyz'
)
d
=
D
()
self
.
assertEqual
(
eval
(
'a'
,
g
,
d
),
12
)
self
.
assertRaises
(
NameError
,
eval
,
'b'
,
g
,
d
)
self
.
assertEqual
(
eval
(
'dir()'
,
g
,
d
),
list
(
'xyz'
))
self
.
assertEqual
(
eval
(
'globals()'
,
g
,
d
),
g
)
self
.
assertEqual
(
eval
(
'locals()'
,
g
,
d
),
d
)
# Verify locals stores (used by list comps)
eval
(
'[locals() for i in (2,3)]'
,
g
,
d
)
eval
(
'[locals() for i in (2,3)]'
,
g
,
collections
.
UserDict
())
class
SpreadSheet
:
"Sample application showing nested, calculated lookups."
_cells
=
{}
def
__setitem__
(
self
,
key
,
formula
):
self
.
_cells
[
key
]
=
formula
def
__getitem__
(
self
,
key
):
return
eval
(
self
.
_cells
[
key
],
globals
(),
self
)
ss
=
SpreadSheet
()
ss
[
'a1'
]
=
'5'
ss
[
'a2'
]
=
'a1*6'
ss
[
'a3'
]
=
'a2*7'
self
.
assertEqual
(
ss
[
'a3'
],
210
)
# Verify that dir() catches a non-list returned by eval
# SF bug #1004669
class
C
:
def
__getitem__
(
self
,
item
):
raise
KeyError
(
item
)
def
keys
(
self
):
return
1
# used to be 'a' but that's no longer an error
self
.
assertRaises
(
TypeError
,
eval
,
'dir()'
,
globals
(),
C
())
def
test_exec
(
self
):
g
=
{}
exec
(
'z = 1'
,
g
)
if
'__builtins__'
in
g
:
del
g
[
'__builtins__'
]
self
.
assertEqual
(
g
, {
'z'
:
1
})
exec
(
'z = 1+1'
,
g
)
if
'__builtins__'
in
g
:
del
g
[
'__builtins__'
]
self
.
assertEqual
(
g
, {
'z'
:
2
})
g
=
{}
l
=
{}
with
check_warnings
():
warnings
.
filterwarnings
(
"ignore"
,
"global statement"
,
module
=
"<string>"
)
exec
(
'global a; a = 1; b = 2'
,
g
,
l
)
if
'__builtins__'
in
g
:
del
g
[
'__builtins__'
]
if
'__builtins__'
in
l
:
del
l
[
'__builtins__'
]
self
.
assertEqual
((
g
,
l
), ({
'a'
:
1
}, {
'b'
:
2
}))
def
test_exec_frozendict
(
self
):
ns
=
frozendict
(
x
=
1
,
data
=
[],
__builtins__
=
__builtins__
)
exec
(
"data.append(x)"
,
ns
,
ns
)
self
.
assertEqual
(
ns
[
'data'
], [
1
])
ns
=
frozendict
(
__builtins__
=
__builtins__
)
errmsg
=
"'frozendict' object does not support item assignment"
with
self
.
assertRaisesRegex
(
TypeError
,
errmsg
):
exec
(
"x = 1"
,
ns
,
ns
)
ns
=
frozendict
()
errmsg
=
"cannot assign __builtins__ to frozendict globals"
with
self
.
assertRaisesRegex
(
TypeError
,
errmsg
):
exec
(
""
,
ns
,
ns
)
def
test_exec_kwargs
(
self
):
g
=
{}
exec
(
'global z
\n
z = 1'
,
globals
=
g
)
if
'__builtins__'
in
g
:
del
g
[
'__builtins__'
]
self
.
assertEqual
(
g
, {
'z'
:
1
})
# if we only set locals, the global assignment will not
# reach this locals dictionary
g
=
{}
exec
(
'global z
\n
z = 1'
,
locals
=
g
)
self
.
assertEqual
(
g
, {})
def
test_exec_globals
(
self
):
code
=
compile
(
"print('Hello World!')"
,
""
,
"exec"
)
# no builtin function
self
.
assertRaisesRegex
(
NameError
,
"name 'print' is not defined"
,
exec
,
code
, {
'__builtins__'
: {}})
# __builtins__ must be a mapping type
self
.
assertRaises
(
TypeError
,
exec
,
code
, {
'__builtins__'
:
123
})
def
test_exec_globals_frozen
(
self
):
class
frozendict_error
(
Exception
):
pass
class
frozendict
(
dict
):
def
__setitem__
(
self
,
key
,
value
):
raise
frozendict_error
(
"frozendict is readonly"
)
# read-only builtins
if
isinstance
(
__builtins__
,
types
.
ModuleType
):
frozen_builtins
=
frozendict
(
__builtins__
.
__dict__
)
else
:
frozen_builtins
=
frozendict
(
__builtins__
)
code
=
compile
(
"__builtins__['superglobal']=2; print(superglobal)"
,
"test"
,
"exec"
)
self
.
assertRaises
(
frozendict_error
,
exec
,
code
, {
'__builtins__'
:
frozen_builtins
})
# no __build_class__ function
code
=
compile
(
"class A: pass"
,
""
,
"exec"
)
self
.
assertRaisesRegex
(
NameError
,
"__build_class__ not found"
,
exec
,
code
, {
'__builtins__'
: {}})
# __build_class__ in a custom __builtins__
exec
(
code
, {
'__builtins__'
:
frozen_builtins
})
self
.
assertRaisesRegex
(
NameError
,
"__build_class__ not found"
,
exec
,
code
, {
'__builtins__'
:
frozendict
()})
# read-only globals
namespace
=
frozendict
({})
code
=
compile
(
"x=1"
,
"test"
,
"exec"
)
self
.
assertRaises
(
frozendict_error
,
exec
,
code
,
namespace
)
def
test_exec_globals_error_on_get
(
self
):
# custom `globals` or `builtins` can raise errors on item access
class
setonlyerror
(
Exception
):
pass
class
setonlydict
(
dict
):
def
__getitem__
(
self
,
key
):
raise
setonlyerror
# globals' `__getitem__` raises
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL