Debian Codegraph @

tests/test_guarded_eval.py

raw
1 import sys
2 from contextlib import contextmanager
3 from importlib import import_module
4 from typing import (
5 Annotated,
6 AnyStr,
7 NamedTuple,
8 Literal,
9 NewType,
10 Optional,
11 Protocol,
12 TypeGuard,
13 Union,
14 TypedDict,
15 TypeVar,
16 List,
17 Callable,
18 Any,
19 Dict,
20 )
21 from functools import partial
22 from IPython.core.guarded_eval import (
23 EvaluationContext,
24 GuardRejection,
25 guarded_eval,
26 _unbind_method,
27 )
28 from IPython.testing import decorators as dec
29 import pytest
30 from IPython.core.guarded_eval import _is_type_annotation
31
32
33 from typing import Self, LiteralString
34
35 from typing import TypeAliasType
36
37
38 def create_context(evaluation: str, **kwargs):
39 return EvaluationContext(locals=kwargs, globals={}, evaluation=evaluation)
40
41
42 forbidden = partial(create_context, "forbidden")
43 minimal = partial(create_context, "minimal")
44 limited = partial(create_context, "limited")
45 unsafe = partial(create_context, "unsafe")
46 dangerous = partial(create_context, "dangerous")
47
48 LIMITED_OR_HIGHER = [limited, unsafe, dangerous]
49 MINIMAL_OR_HIGHER = [minimal, *LIMITED_OR_HIGHER]
50
51
52 @contextmanager
53 def module_not_installed(module: str):
54 import sys
55
56 try:
57 to_restore = sys.modules[module]
58 del sys.modules[module]
59 except KeyError:
60 to_restore = None
61 try:
62 yield
63 finally:
64 sys.modules[module] = to_restore
65
66
67 def test_external_not_installed():
68 """
69 Because attribute check requires checking if object is not of allowed
70 external type, this tests logic for absence of external module.
71 """
72
73 class Custom:
74 def __init__(self):
75 self.test = 1
76
77 def __getattr__(self, key):
78 return key
79
80 with module_not_installed("pandas"):
81 context = limited(x=Custom())
82 with pytest.raises(GuardRejection):
83 guarded_eval("x.test", context)
84
85
86 @dec.skip_without("pandas")
87 def test_external_changed_api(monkeypatch):
88 """Check that the execution rejects if external API changed paths"""
89 import pandas as pd
90
91 series = pd.Series([1], index=["a"])
92
93 with monkeypatch.context() as m:
94 m.delattr(pd, "Series")
95 context = limited(data=series)
96 with pytest.raises(GuardRejection):
97 guarded_eval("data.iloc[0]", context)
98
99
100 @dec.skip_without("pandas")
101 def test_pandas_series_iloc():
102 import pandas as pd
103
104 series = pd.Series([1], index=["a"])
105 context = limited(data=series)
106 assert guarded_eval("data.iloc[0]", context) == 1
107
108
109 def test_rejects_custom_properties():
110 class BadProperty:
111 @property
112 def iloc(self):
113 return [None]
114
115 series = BadProperty()
116 context = limited(data=series)
117
118 with pytest.raises(GuardRejection):
119 guarded_eval("data.iloc[0]", context)
120
121
122 @dec.skip_without("pandas")
123 def test_accepts_non_overriden_properties():
124 import pandas as pd
125
126 class GoodProperty(pd.Series):
127 pass
128
129 series = GoodProperty([1], index=["a"])
130 context = limited(data=series)
131
132 assert guarded_eval("data.iloc[0]", context) == 1
133
134
135 @dec.skip_without("pandas")
136 def test_pandas_series():
137 import pandas as pd
138
139 context = limited(data=pd.Series([1], index=["a"]))
140 assert guarded_eval('data["a"]', context) == 1
141 with pytest.raises(KeyError):
142 guarded_eval('data["c"]', context)
143
144
145 @dec.skip_without("pandas")
146 def test_pandas_bad_series():
147 import pandas as pd
148
149 class BadItemSeries(pd.Series):
150 def __getitem__(self, key):
151 return "CUSTOM_ITEM"
152
153 class BadAttrSeries(pd.Series):
154 def __getattr__(self, key):
155 return "CUSTOM_ATTR"
156
157 bad_series = BadItemSeries([1], index=["a"])
158 context = limited(data=bad_series)
159
160 with pytest.raises(GuardRejection):
161 guarded_eval('data["a"]', context)
162 with pytest.raises(GuardRejection):
163 guarded_eval('data["c"]', context)
164
165 # note: here result is a bit unexpected because
166 # pandas `__getattr__` calls `__getitem__`;
167 # FIXME - special case to handle it?
168 assert guarded_eval("data.a", context) == "CUSTOM_ITEM"
169
170 context = unsafe(data=bad_series)
171 assert guarded_eval('data["a"]', context) == "CUSTOM_ITEM"
172
173 bad_attr_series = BadAttrSeries([1], index=["a"])
174 context = limited(data=bad_attr_series)
175 assert guarded_eval('data["a"]', context) == 1
176 with pytest.raises(GuardRejection):
177 guarded_eval("data.a", context)
178
179
180 @dec.skip_without("pandas")
181 def test_pandas_dataframe_loc():
182 import pandas as pd
183 from pandas.testing import assert_series_equal
184
185 data = pd.DataFrame([{"a": 1}])
186 context = limited(data=data)
187 assert_series_equal(guarded_eval('data.loc[:, "a"]', context), data["a"])
188
189
190 def test_named_tuple():
191 class GoodNamedTuple(NamedTuple):
192 a: str
193 pass
194
195 class BadNamedTuple(NamedTuple):
196 a: str
197
198 def __getitem__(self, key):
199 return None
200
201 good = GoodNamedTuple(a="x")
202 bad = BadNamedTuple(a="x")
203
204 context = limited(data=good)
205 assert guarded_eval("data[0]", context) == "x"
206
207 context = limited(data=bad)
208 with pytest.raises(GuardRejection):
209 guarded_eval("data[0]", context)
210
211
212 def test_dict():
213 context = limited(data={"a": 1, "b": {"x": 2}, ("x", "y"): 3})
214 assert guarded_eval('data["a"]', context) == 1
215 assert guarded_eval('data["b"]', context) == {"x": 2}
216 assert guarded_eval('data["b"]["x"]', context) == 2
217 assert guarded_eval('data["x", "y"]', context) == 3
218
219 assert guarded_eval("data.keys", context)
220
221
222 def test_set():
223 context = limited(data={"a", "b"})
224 assert guarded_eval("data.difference", context)
225
226
227 def test_list():
228 context = limited(data=[1, 2, 3])
229 assert guarded_eval("data[1]", context) == 2
230 assert guarded_eval("data.copy", context)
231
232
233 def test_dict_literal():
234 context = limited()
235 assert guarded_eval("{}", context) == {}
236 assert guarded_eval('{"a": 1}', context) == {"a": 1}
237
238
239 def test_list_literal():
240 context = limited()
241 assert guarded_eval("[]", context) == []
242 assert guarded_eval('[1, "a"]', context) == [1, "a"]
243
244
245 def test_set_literal():
246 context = limited()
247 assert guarded_eval("set()", context) == set()
248 assert guarded_eval('{"a"}', context) == {"a"}
249
250
251 def test_evaluates_if_expression():
252 context = limited()
253 assert guarded_eval("2 if True else 3", context) == 2
254 assert guarded_eval("4 if False else 5", context) == 5
255
256
257 def test_object():
258 obj = object()
259 context = limited(obj=obj)
260 assert guarded_eval("obj.__dir__", context) == obj.__dir__
261
262
263 @pytest.mark.parametrize(
264 "code,expected",
265 [
266 ["int.numerator", int.numerator],
267 ["float.is_integer", float.is_integer],
268 ["complex.real", complex.real],
269 ],
270 )
271 def test_number_attributes(code, expected):
272 assert guarded_eval(code, limited()) == expected
273
274
275 def test_method_descriptor():
276 context = limited()
277 assert guarded_eval("list.copy.__name__", context) == "copy"
278
279
280 class HeapType:
281 pass
282
283
284 class CallCreatesHeapType:
285 def __call__(self) -> HeapType:
286 return HeapType()
287
288
289 class CallCreatesBuiltin:
290 def __call__(self) -> frozenset:
291 return frozenset()
292
293
294 class HasStaticMethod:
295 @staticmethod
296 def static_method() -> HeapType:
297 return HeapType()
298
299
300 class InitReturnsFrozenset:
301 def __new__(self) -> frozenset: # type:ignore[misc]
302 return frozenset()
303
304
305 class StringAnnotation:
306 def heap(self) -> "HeapType":
307 return HeapType()
308
309 def copy(self) -> "StringAnnotation":
310 return StringAnnotation()
311
312
313 CustomIntType = NewType("CustomIntType", int)
314 CustomHeapType = NewType("CustomHeapType", HeapType)
315 IntTypeAlias = TypeAliasType("IntTypeAlias", int)
316 HeapTypeAlias = TypeAliasType("HeapTypeAlias", HeapType)
317
318
319 class ProtocolTest(Protocol):
320 def test_method(self) -> bool:
321 pass
322
323
324 class ProtocolTestImplementer(ProtocolTest):
325 def test_method(self) -> bool:
326 return True
327
328
329 class TypedClass:
330 def test_method(self) -> bool:
331 return True
332
333
334 class Movie(TypedDict):
335 name: str
336 year: int
337
338
339 class SpecialTyping:
340 def custom_int_type(self) -> CustomIntType:
341 return CustomIntType(1)
342
343 def custom_heap_type(self) -> CustomHeapType:
344 return CustomHeapType(HeapType())
345
346 def int_type_alias(self) -> IntTypeAlias:
347 return 1
348
349 def heap_type_alias(self) -> HeapTypeAlias:
350 return 1
351
352 def literal(self) -> Literal[False]:
353 return False
354
355 def literal_string(self) -> LiteralString:
356 return "test"
357
358 def self(self) -> Self:
359 return self
360
361 def any_str(self, x: AnyStr) -> AnyStr:
362 return x
363
364 def with_kwargs(self, a=1, b=2, c=3) -> int:
365 return a + b + c
366
367 def annotated(self) -> Annotated[float, "positive number"]:
368 return 1
369
370 def annotated_self(self) -> Annotated[Self, "self with metadata"]:
371 self._metadata = "test"
372 return self
373
374 def int_type_guard(self, x) -> TypeGuard[int]:
375 return isinstance(x, int)
376
377 def optional_float(self) -> Optional[float]:
378 return 1.0
379
380 def union_str_and_int(self) -> Union[str, int]:
381 return ""
382
383 def protocol(self) -> ProtocolTest:
384 return ProtocolTestImplementer()
385
386 def typed_dict(self) -> Movie:
387 return {"name": "The Matrix", "year": 1999}
388
389
390 @pytest.mark.parametrize(
391 "data,code,expected,equality",
392 [
393 [[1, 2, 3], "data.index(2)", 1, True],
394 [{"a": 1}, "data.keys().isdisjoint({})", True, True],
395 [StringAnnotation(), "data.heap()", HeapType, False],
396 [StringAnnotation(), "data.copy()", StringAnnotation, False],
397 # test cases for `__call__`
398 [CallCreatesHeapType(), "data()", HeapType, False],
399 [CallCreatesBuiltin(), "data()", frozenset, False],
400 # Test cases for `__init__`
401 [HeapType, "data()", HeapType, False],
402 [InitReturnsFrozenset, "data()", frozenset, False],
403 [HeapType(), "data.__class__()", HeapType, False],
404 # supported special cases for typing
405 [SpecialTyping(), "data.custom_int_type()", int, False],
406 [SpecialTyping(), "data.custom_heap_type()", HeapType, False],
407 [SpecialTyping(), "data.int_type_alias()", int, False],
408 [SpecialTyping(), "data.heap_type_alias()", HeapType, False],
409 [SpecialTyping(), "data.self()", SpecialTyping, False],
410 [SpecialTyping(), "data.literal()", False, True],
411 [SpecialTyping(), "data.literal_string()", str, False],
412 [SpecialTyping(), "data.any_str('a')", str, False],
413 [SpecialTyping(), "data.any_str(b'a')", bytes, False],
414 [SpecialTyping(), "data.with_kwargs(b=3)", int, False],
415 [SpecialTyping(), "data.annotated()", float, False],
416 [SpecialTyping(), "data.annotated_self()", SpecialTyping, False],
417 [SpecialTyping(), "data.int_type_guard()", int, False],
418 # test cases for static methods
419 [HasStaticMethod, "data.static_method()", HeapType, False],
420 ],
421 )
422 def test_evaluates_calls(data, code, expected, equality):
423 context = limited(data=data, HeapType=HeapType, StringAnnotation=StringAnnotation)
424 value = guarded_eval(code, context)
425 if equality:
426 assert value == expected
427 else:
428 assert isinstance(value, expected)
429
430
431 @pytest.mark.parametrize(
432 "data,code,expected_attributes",
433 [
434 [SpecialTyping(), "data.optional_float()", ["is_integer"]],
435 [
436 SpecialTyping(),
437 "data.union_str_and_int()",
438 ["capitalize", "as_integer_ratio"],
439 ],
440 [SpecialTyping(), "data.protocol()", ["test_method"]],
441 [SpecialTyping(), "data.typed_dict()", ["keys", "values", "items"]],
442 ],
443 )
444 def test_mocks_attributes_of_call_results(data, code, expected_attributes):
445 context = limited(data=data, HeapType=HeapType, StringAnnotation=StringAnnotation)
446 result = guarded_eval(code, context)
447 for attr in expected_attributes:
448 assert hasattr(result, attr)
449 assert attr in dir(result)
450
451
452 @pytest.mark.parametrize(
453 "data,code,expected_items",
454 [
455 [SpecialTyping(), "data.typed_dict()", {"year": int, "name": str}],
456 ],
457 )
458 def test_mocks_items_of_call_results(data, code, expected_items):
459 context = limited(data=data, HeapType=HeapType, StringAnnotation=StringAnnotation)
460 result = guarded_eval(code, context)
461 ipython_keys = result._ipython_key_completions_()
462 for key, value in expected_items.items():
463 assert isinstance(result[key], value)
464 assert key in ipython_keys
465
466
467 @pytest.mark.parametrize(
468 "code,expected",
469 [
470 ["\n".join(["instance = TypedClass()", "instance.test_method()"]), bool],
471 ["\n".join(["def func() -> int:", " pass", "func()"]), int],
472 [
473 "\n".join(
474 [
475 "class NotYetDefined:",
476 " def method(self) -> str:",
477 " pass",
478 "instance = NotYetDefined()",
479 "instance.method()",
480 ]
481 ),
482 str,
483 ],
484 [
485 "\n".join(
486 [
487 "class NotYetDefined:",
488 " def method(self, argument) -> int:",
489 " pass",
490 "instance = NotYetDefined()",
491 "instance.method()",
492 ]
493 ),
494 int,
495 ],
496 [
497 "\n".join(
498 [
499 "class NotYetDefined:",
500 " @property",
501 " def my_prop(self) -> int:",
502 " pass",
503 "instance = NotYetDefined()",
504 "instance.my_prop",
505 ]
506 ),
507 int,
508 ],
509 [
510 "\n".join(
511 [
512 "class NotYetDefined:",
513 " @unkown_decorator",
514 " @property",
515 " def my_prop(self) -> int:",
516 " pass",
517 "instance = NotYetDefined()",
518 "instance.my_prop",
519 ]
520 ),
521 int,
522 ],
523 [
524 "\n".join(
525 [
526 "class NotYetDefined:",
527 " attribute = 42",
528 "instance = NotYetDefined()",
529 "instance.attribute",
530 ]
531 ),
532 int,
533 ],
534 [
535 "\n".join(
536 [
537 "class NotYetDefined:",
538 " def any_str(self, argument: AnyStr) -> AnyStr:",
539 " pass",
540 "instance = NotYetDefined()",
541 "instance.any_str(b'test')",
542 ]
543 ),
544 bytes,
545 ],
546 [
547 "\n".join(
548 [
549 "class NotYetDefined:",
550 " def any_str(self, argument: AnyStr) -> AnyStr:",
551 " pass",
552 "instance = NotYetDefined()",
553 "instance.any_str('test')",
554 ]
555 ),
556 str,
557 ],
558 [
559 "\n".join(
560 [
561 "async def async_func():",
562 " return []",
563 "(await async_func())",
564 ]
565 ),
566 list,
567 ],
568 [
569 "\n".join(
570 [
571 "make_list = lambda:[]",
572 "make_list()",
573 ]
574 ),
575 list,
576 ],
577 ],
578 )
579 def test_mock_class_and_func_instances(code, expected):
580 context = limited(TypedClass=TypedClass, AnyStr=AnyStr)
581 value = guarded_eval(code, context)
582 assert isinstance(value, expected)
583
584
585 @pytest.mark.parametrize(
586 "annotation,expected",
587 [
588 # Basic types
589 (int, True),
590 (str, True),
591 (list, True),
592 # Typing generics
593 (list[str], True),
594 (dict[str, int], True),
595 (Optional[int], True),
596 (Union[int, str], True),
597 # Special forms
598 (AnyStr, True),
599 (TypeVar("T"), True),
600 (Callable[[int], str], True),
601 (Literal["GET", "POST"], True),
602 (Any, True),
603 (str | int, True),
604 # Nested
605 (List[Dict[str, int]], True),
606 # Non-annotations
607 (42, False),
608 ("string", False),
609 ([1, 2, 3], False),
610 (None, False),
611 ],
612 )
613 def test_is_type_annotation(annotation, expected):
614 assert _is_type_annotation(annotation) == expected
615
616
617 @pytest.mark.parametrize(
618 "code,expected",
619 [
620 ["\n".join(["a = True", "a"]), bool],
621 ["\n".join(["a, b, c = 1, 'b', 3.0", "a"]), int],
622 ["\n".join(["a, b, c = 1, 'b', 3.0", "b"]), str],
623 ["\n".join(["a, b, c = 1, 'b', 3.0", "c"]), float],
624 ["\n".join(["a, *rest = 1, 'b', 3.0", "a"]), int],
625 ["\n".join(["a, *rest = 1, 'b', 3.0", "rest"]), list],
626 ],
627 )
628 def test_evaluates_assignments(code, expected):
629 context = limited()
630 value = guarded_eval(code, context)
631 assert isinstance(value, expected)
632
633
634 def equals(a, b):
635 return a == b
636
637
638 def quacks_like(test_duck, reference_duck):
639 return set(dir(reference_duck)) - set(dir(test_duck)) == set()
640
641
642 @pytest.mark.parametrize(
643 "code,expected,check",
644 [
645 ["\n".join(["a: Literal[True]", "a"]), True, equals],
646 ["\n".join(["a: bool", "a"]), bool, isinstance],
647 ["\n".join(["a: str", "a"]), str, isinstance],
648 # for lists we need quacking as we do not know:
649 # - how many elements in the list
650 # - which element is of which type
651 ["\n".join(["a: list[str]", "a"]), list, quacks_like],
652 ["\n".join(["a: list[str]", "a[0]"]), str, quacks_like],
653 ["\n".join(["a: list[str]", "a[999]"]), str, quacks_like],
654 # set
655 ["\n".join(["a: set[str]", "a"]), set, quacks_like],
656 # for tuples we do know which element is which
657 ["\n".join(["a: tuple[str, int]", "a"]), tuple, isinstance],
658 ["\n".join(["a: tuple[str, int]", "a[0]"]), str, isinstance],
659 ["\n".join(["a: tuple[str, int]", "a[1]"]), int, isinstance],
660 ],
661 )
662 def test_evaluates_type_assignments(code, expected, check):
663 context = limited(Literal=Literal)
664 value = guarded_eval(code, context)
665 assert check(value, expected)
666
667
668 @pytest.mark.parametrize(
669 "data,bad",
670 [
671 [[1, 2, 3], "data.append(4)"],
672 [{"a": 1}, "data.update()"],
673 ],
674 )
675 def test_rejects_calls_with_side_effects(data, bad):
676 context = limited(data=data)
677
678 with pytest.raises(GuardRejection):
679 guarded_eval(bad, context)
680
681
682 @pytest.mark.parametrize(
683 "code,expected",
684 [
685 ["(1\n+\n1)", 2],
686 ["list(range(10))[-1:]", [9]],
687 ["list(range(20))[3:-2:3]", [3, 6, 9, 12, 15]],
688 ],
689 )
690 @pytest.mark.parametrize("context", LIMITED_OR_HIGHER)
691 def test_evaluates_complex_cases(code, expected, context):
692 assert guarded_eval(code, context()) == expected
693
694
695 @pytest.mark.parametrize(
696 "code,expected",
697 [
698 ["1", 1],
699 ["1.0", 1.0],
700 ["0xdeedbeef", 0xDEEDBEEF],
701 ["True", True],
702 ["None", None],
703 ["{}", {}],
704 ["[]", []],
705 ],
706 )
707 @pytest.mark.parametrize("context", MINIMAL_OR_HIGHER)
708 def test_evaluates_literals(code, expected, context):
709 assert guarded_eval(code, context()) == expected
710
711
712 @pytest.mark.parametrize(
713 "code,expected",
714 [
715 ["-5", -5],
716 ["+5", +5],
717 ["~5", -6],
718 ],
719 )
720 @pytest.mark.parametrize("context", LIMITED_OR_HIGHER)
721 def test_evaluates_unary_operations(code, expected, context):
722 assert guarded_eval(code, context()) == expected
723
724
725 @pytest.mark.parametrize(
726 "code,expected",
727 [
728 ["1 + 1", 2],
729 ["3 - 1", 2],
730 ["2 * 3", 6],
731 ["5 // 2", 2],
732 ["5 / 2", 2.5],
733 ["5**2", 25],
734 ["2 >> 1", 1],
735 ["2 << 1", 4],
736 ["1 | 2", 3],
737 ["1 & 1", 1],
738 ["1 & 2", 0],
739 ],
740 )
741 @pytest.mark.parametrize("context", LIMITED_OR_HIGHER)
742 def test_evaluates_binary_operations(code, expected, context):
743 assert guarded_eval(code, context()) == expected
744
745
746 @pytest.mark.parametrize(
747 "code,expected",
748 [
749 ["2 > 1", True],
750 ["2 < 1", False],
751 ["2 <= 1", False],
752 ["2 <= 2", True],
753 ["1 >= 2", False],
754 ["2 >= 2", True],
755 ["2 == 2", True],
756 ["1 == 2", False],
757 ["1 != 2", True],
758 ["1 != 1", False],
759 ["1 < 4 < 3", False],
760 ["(1 < 4) < 3", True],
761 ["4 > 3 > 2 > 1", True],
762 ["4 > 3 > 2 > 9", False],
763 ["1 < 2 < 3 < 4", True],
764 ["9 < 2 < 3 < 4", False],
765 ["1 < 2 > 1 > 0 > -1 < 1", True],
766 ["1 in [1] in [[1]]", True],
767 ["1 in [1] in [[2]]", False],
768 ["1 in [1]", True],
769 ["0 in [1]", False],
770 ["1 not in [1]", False],
771 ["0 not in [1]", True],
772 ["True is True", True],
773 ["False is False", True],
774 ["True is False", False],
775 ["True is not True", False],
776 ["False is not True", True],
777 ],
778 )
779 @pytest.mark.parametrize("context", LIMITED_OR_HIGHER)
780 def test_evaluates_comparisons(code, expected, context):
781 assert guarded_eval(code, context()) == expected
782
783
784 def test_guards_comparisons():
785 class GoodEq(int):
786 pass
787
788 class BadEq(int):
789 def __eq__(self, other):
790 assert False
791
792 context = limited(bad=BadEq(1), good=GoodEq(1))
793
794 with pytest.raises(GuardRejection):
795 guarded_eval("bad == 1", context)
796
797 with pytest.raises(GuardRejection):
798 guarded_eval("bad != 1", context)
799
800 with pytest.raises(GuardRejection):
801 guarded_eval("1 == bad", context)
802
803 with pytest.raises(GuardRejection):
804 guarded_eval("1 != bad", context)
805
806 assert guarded_eval("good == 1", context) is True
807 assert guarded_eval("good != 1", context) is False
808 assert guarded_eval("1 == good", context) is True
809 assert guarded_eval("1 != good", context) is False
810
811
812 def test_guards_unary_operations():
813 class GoodOp(int):
814 pass
815
816 class BadOpInv(int):
817 def __inv__(self, other):
818 assert False
819
820 class BadOpInverse(int):
821 def __inv__(self, other):
822 assert False
823
824 context = limited(good=GoodOp(1), bad1=BadOpInv(1), bad2=BadOpInverse(1))
825
826 with pytest.raises(GuardRejection):
827 guarded_eval("~bad1", context)
828
829 with pytest.raises(GuardRejection):
830 guarded_eval("~bad2", context)
831
832
833 def test_guards_binary_operations():
834 class GoodOp(int):
835 pass
836
837 class BadOp(int):
838 def __add__(self, other):
839 assert False
840
841 context = limited(good=GoodOp(1), bad=BadOp(1))
842
843 with pytest.raises(GuardRejection):
844 guarded_eval("1 + bad", context)
845
846 with pytest.raises(GuardRejection):
847 guarded_eval("bad + 1", context)
848
849 assert guarded_eval("good + 1", context) == 2
850 assert guarded_eval("1 + good", context) == 2
851
852
853 def test_guards_attributes():
854 class GoodAttr(float):
855 pass
856
857 class BadAttr1(float):
858 def __getattr__(self, key):
859 assert False
860
861 class BadAttr2(float):
862 def __getattribute__(self, key):
863 assert False
864
865 context = limited(good=GoodAttr(0.5), bad1=BadAttr1(0.5), bad2=BadAttr2(0.5))
866
867 with pytest.raises(GuardRejection):
868 guarded_eval("bad1.as_integer_ratio", context)
869
870 with pytest.raises(GuardRejection):
871 guarded_eval("bad2.as_integer_ratio", context)
872
873 assert guarded_eval("good.as_integer_ratio()", context) == (1, 2)
874
875
876 @pytest.mark.parametrize("context", MINIMAL_OR_HIGHER)
877 def test_access_builtins(context):
878 assert guarded_eval("round", context()) == round
879
880
881 def test_access_builtins_fails():
882 context = limited()
883 with pytest.raises(NameError):
884 guarded_eval("this_is_not_builtin", context)
885
886
887 def test_rejects_forbidden():
888 context = forbidden()
889 with pytest.raises(GuardRejection):
890 guarded_eval("1", context)
891
892
893 def test_guards_locals_and_globals():
894 context = EvaluationContext(
895 locals={"local_a": "a"}, globals={"global_b": "b"}, evaluation="minimal"
896 )
897
898 with pytest.raises(GuardRejection):
899 guarded_eval("local_a", context)
900
901 with pytest.raises(GuardRejection):
902 guarded_eval("global_b", context)
903
904
905 def test_access_locals_and_globals():
906 context = EvaluationContext(
907 locals={"local_a": "a"}, globals={"global_b": "b"}, evaluation="limited"
908 )
909 assert guarded_eval("local_a", context) == "a"
910 assert guarded_eval("global_b", context) == "b"
911
912
913 @pytest.mark.parametrize(
914 "code",
915 ["x += 1", "del x"],
916 )
917 @pytest.mark.parametrize("context", [minimal(x=1), limited(x=1), unsafe(x=1)])
918 def test_does_not_modify_namespace(code, context):
919 guarded_eval(code, context)
920 assert context.locals["x"] == 1
921
922
923 @pytest.mark.parametrize(
924 "code",
925 ["def test(): pass", "class test: pass", "import ast as test"],
926 )
927 @pytest.mark.parametrize("context", [minimal(), limited(), unsafe()])
928 def test_does_not_populate_namespace(code, context):
929 guarded_eval(code, context)
930 assert "test" not in context.locals
931 assert "test" not in context.globals
932
933
934 def test_subscript():
935 context = EvaluationContext(
936 locals={}, globals={}, evaluation="limited", in_subscript=True
937 )
938 empty_slice = slice(None, None, None)
939 assert guarded_eval("", context) == tuple()
940 assert guarded_eval(":", context) == empty_slice
941 assert guarded_eval("1:2:3", context) == slice(1, 2, 3)
942 assert guarded_eval(':, "a"', context) == (empty_slice, "a")
943
944
945 def test_unbind_method():
946 class X(list):
947 def index(self, k):
948 return "CUSTOM"
949
950 x = X()
951 assert _unbind_method(x.index) is X.index
952 assert _unbind_method([].index) is list.index
953 assert _unbind_method(list.index) is None
954
955
956 def test_assumption_instance_attr_do_not_matter():
957 """This is semi-specified in Python documentation.
958
959 However, since the specification says 'not guaranteed
960 to work' rather than 'is forbidden to work', future
961 versions could invalidate this assumptions. This test
962 is meant to catch such a change if it ever comes true.
963 """
964
965 class T:
966 def __getitem__(self, k):
967 return "a"
968
969 def __getattr__(self, k):
970 return "a"
971
972 def f(self):
973 return "b"
974
975 t = T()
976 t.__getitem__ = f
977 t.__getattr__ = f
978 assert t[1] == "a"
979 assert t[1] == "a"
980
981
982 def test_assumption_named_tuples_share_getitem():
983 """Check assumption on named tuples sharing __getitem__"""
984 from typing import NamedTuple
985
986 class A(NamedTuple):
987 pass
988
989 class B(NamedTuple):
990 pass
991
992 assert A.__getitem__ == B.__getitem__
993
994
995 @dec.skip_without("numpy")
996 def test_module_access():
997 import numpy
998
999 context = limited(numpy=numpy)
1000 assert guarded_eval("numpy.linalg.norm", context) == numpy.linalg.norm
1001
1002 context = minimal(numpy=numpy)
1003 with pytest.raises(GuardRejection):
1004 guarded_eval("np.linalg.norm", context)
1005
1006
1007 def test_autoimport_module():
1008 context = EvaluationContext(
1009 locals={},
1010 globals={},
1011 evaluation="limited",
1012 auto_import=import_module,
1013 policy_overrides={"allow_auto_import": True},
1014 )
1015 pi = guarded_eval("math.pi", context)
1016 assert round(pi, 2) == 3.14
1017
1018
1019 def test_autoimport_deep_module():
1020 context = EvaluationContext(
1021 locals={},
1022 globals={},
1023 evaluation="limited",
1024 auto_import=import_module,
1025 policy_overrides={"allow_auto_import": True},
1026 )
1027 ElementTree = guarded_eval("xml.etree.ElementTree", context)
1028 assert hasattr(ElementTree, "ElementTree")