File size: 29,242 Bytes
d086025 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 | diff --git a/tests/_test_acr_translator.py b/tests/_test_acr_translator.py
new file mode 100644
--- /dev/null
+++ b/tests/_test_acr_translator.py
@@ -0,0 +1,156 @@
+import ast
+import sys
+from collections import defaultdict
+
+from pynalyser.acr import classes as acr
+
+# from pynalyser.acr import classes as acr
+from pynalyser.acr.translation import Translator, translate_ast_to_acr
+from pynalyser.acr.utils import dump
+
+tree = ast.parse(
+ # """
+ # if x:
+ # a = 69 + 42
+ # """)
+ # (
+ # """
+ # # if a:
+ # # if b:
+ # # c
+ # # else:
+ # # d
+ # # else:
+ # # if e:
+ # # f
+ # # else:
+ # # g
+ # # try:
+ # # 8
+ # # except x:
+ # # 6
+ # # chain
+ # # from itertools import chain as c
+ # if x:
+ # a, b[0] = 5, 8
+ # else:
+ # 7
+ # # @lambda x: x
+ # # def t():
+ # # pass
+ # # try:
+ # # 9
+ # # except y:
+ # # 8
+ # # if a:
+ # # def tt():
+ # # if h:
+ # # 8
+ # # 3
+ # # else:
+ # # 7
+ # # 9
+ # """)
+ """
+class T:
+ 7
+
+class TT:
+ def t():
+ 8
+
+def a():
+ 5
+
+def b():
+ class B:
+ 0
+
+def b():
+ def c():
+ 2
+
+69
+"""
+)
+
+if sys.version_info >= (3, 9):
+ print(ast.dump(tree, indent=4, include_attributes=True))
+
+# print(acr.ScopeWithAttributes("", lineno=0, col_offset=4)._attributes)
+# out = acr.Function(
+# name='b',
+# lineno=12,
+# col_offset=0)
+
+# out.body.append(
+# acr.CodeBlock([
+# ast.Constant(
+# value=7,
+# kind=None,
+# lineno=3,
+# col_offset=4,
+# end_lineno=3,
+# end_col_offset=5)]))
+
+# print(ast.NodeVisitor().visit(out))
+
+out = translate_ast_to_acr(tree, "test")
+print(dump(out, indent="| ", include_attributes=True))
+
+if sys.version_info < (3, 7):
+ breakpoint = object
+
+breakpoint
+
+# acr.dump(f)) # out.scopes["a"][0]))
+# f = out.blocks[0].body[0].value.get_scope(out)
+quit()
+
+# import attr
+
+# @attr.s(auto_attribs=True)
+# class T:
+# i: int
+
+# t = T(5)
+# print(attrs.asdict(t),
+# attrs.fields_dict(T),
+# attrs.fields(T))
+# del t.i
+# print(attrs.asdict(t))
+
+
+[
+ ast.Expr(
+ value=ast.BinOp(
+ left=ast.Name(id="a", ctx=ast.Load()),
+ op=ast.Add(),
+ right=ast.Name(id="b", ctx=ast.Load()),
+ )
+ )
+]
+
+
+def test_Module():
+ tree = ast.Module(body=[], type_ignores=[])
+ name = "test"
+ acr_module = translate_ast_to_acr(tree, name)
+ assert type(acr_module) == acr.Module
+ assert acr_module.name == name
+ assert acr_module.body == []
+
+
+def test_Expr():
+ tree = ast.Module(
+ body=[ast.Expr(value=ast.Name(id="a", ctx=ast.Load()))], type_ignores=[]
+ )
+ acr_module = translate_ast_to_acr(tree, "test")
+ # TODO
+ breakpoint
+
+
+if __name__ == "__main__":
+ import pytest
+
+ pytest.main([__file__])
diff --git a/tests/test_inherit_dicts.py b/tests/test_inherit_dicts.py
new file mode 100644
--- /dev/null
+++ b/tests/test_inherit_dicts.py
@@ -0,0 +1,167 @@
+import pytest
+from pynalyser.inherit_dicts import (
+ DICTS,
+ DictNotFoundError,
+ InheritDicts,
+ MetaInheritDicts,
+)
+
+from utils import do_test
+
+
+def all_attrs(obj):
+ return {name: getattr(obj, name) for name in dir(obj) if not name.startswith("__")}
+
+
+def test_empty():
+ class Cls1(metaclass=MetaInheritDicts):
+ pass
+
+ assert all_attrs(Cls1()) == {DICTS: set()}
+
+ class Cls2(metaclass=MetaInheritDicts):
+ _dicts_to_inherit = set()
+
+ assert all_attrs(Cls2()) == {DICTS: set()}
+
+ class Cls3(InheritDicts):
+ pass
+
+ assert all_attrs(Cls3()) == {DICTS: set()}
+
+ class Cls4(InheritDicts):
+ _dicts_to_inherit = set()
+
+ assert all_attrs(Cls4()) == {DICTS: set()}
+
+
+def test_one_dict():
+ class Parent(InheritDicts):
+ _dicts_to_inherit = {"a"}
+ a = {1: 2}
+
+ assert all_attrs(Parent()) == {DICTS: {"a"}, "a": {1: 2}}
+
+ class Child(Parent):
+ a = {3: 4}
+
+ assert all_attrs(Child()) == {DICTS: {"a"}, "a": {1: 2, 3: 4}}
+
+ class Child2(Child):
+ a = {1: 5}
+
+ assert all_attrs(Child2()) == {DICTS: {"a"}, "a": {1: 5, 3: 4}}
+
+
+def test_two_dicts():
+ class Parent(InheritDicts):
+ _dicts_to_inherit = {"a", "b"}
+ a = {1: 2}
+ b = {10: 11}
+
+ assert all_attrs(Parent()) == {DICTS: {"a", "b"}, "a": {1: 2}, "b": {10: 11}}
+
+ class Child(Parent):
+ b = {12: 13}
+
+ assert all_attrs(Child()) == {DICTS: {"a", "b"}, "a": {1: 2}, "b": {10: 11, 12: 13}}
+
+ class Child2(Child):
+ a = {1: 5}
+
+ assert all_attrs(Child2()) == {
+ DICTS: {"a", "b"},
+ "a": {1: 5},
+ "b": {10: 11, 12: 13},
+ }
+
+ class Child3(Child2):
+ a = {3: 4}
+ b = {12: 0}
+
+ assert all_attrs(Child3()) == {
+ DICTS: {"a", "b"},
+ "a": {1: 5, 3: 4},
+ "b": {10: 11, 12: 0},
+ }
+
+
+def test_removal():
+ class Parent(InheritDicts):
+ _dicts_to_inherit = {"a"}
+ a = {1: 2}
+
+ assert all_attrs(Parent()) == {DICTS: {"a"}, "a": {1: 2}}
+
+ class Child(Parent):
+ _dicts_to_inherit = set()
+ a = {3: 4}
+
+ assert all_attrs(Child()) == {DICTS: set(), "a": {3: 4}}
+
+ class Child2(Parent):
+ _dicts_to_inherit = set()
+
+ # regular inheritance
+ assert all_attrs(Child2()) == {DICTS: set(), "a": {1: 2}}
+
+
+def test_persists():
+ class Parent(InheritDicts):
+ _dicts_to_inherit = {"a"}
+ a = {1: 2}
+
+ assert all_attrs(Parent()) == {DICTS: {"a"}, "a": {1: 2}}
+
+ class Child(Parent):
+ pass
+
+ assert all_attrs(Child()) == {DICTS: {"a"}, "a": {1: 2}}
+
+
+def test_nonexisting():
+ with pytest.raises(DictNotFoundError, match=str(DictNotFoundError("a", "Cls1"))):
+
+ class Cls1(InheritDicts):
+ _dicts_to_inherit = {"a"}
+
+ with pytest.raises(DictNotFoundError, match=str(DictNotFoundError("b", "Cls2"))):
+
+ class Cls2(InheritDicts):
+ _dicts_to_inherit = {"a", "b"}
+ a = {1: 2}
+
+
+def test_as_a_whole():
+ class A(InheritDicts):
+ _dicts_to_inherit = {"a"}
+ a = {1: 2}
+
+ class B(A):
+ a = {5: 6}
+
+ class C(B):
+ _dicts_to_inherit = {"a", "b"}
+ a = {1: 8}
+ b = {1: 9}
+
+ class D(C):
+ _dicts_to_inherit = {"b"}
+ b = {2: 19}
+
+ classes = [InheritDicts, A, B, C, D]
+ values = [
+ {DICTS: set()},
+ {DICTS: {"a"}, "a": {1: 2}},
+ {DICTS: {"a"}, "a": {1: 2, 5: 6}},
+ {DICTS: {"b", "a"}, "a": {1: 8, 5: 6}, "b": {1: 9}},
+ {DICTS: {"b"}, "a": {1: 8, 5: 6}, "b": {1: 9, 2: 19}},
+ ]
+
+ assert len(classes) == len(values)
+ for cls, value in zip(classes, values):
+ assert value == all_attrs(cls()), cls.__name__
+
+
+if __name__ == "__main__":
+ do_test(__file__)
diff --git a/tests/test_inheritance.py b/tests/test_inheritance.py
new file mode 100644
--- /dev/null
+++ b/tests/test_inheritance.py
@@ -0,0 +1,233 @@
+from typing import Tuple, Type
+from pynalyser.types.inheritance import Inheritable, is_subclass, is_type, set_bases
+from pynalyser.types.exceptions import duplicate_base, invalid_mro
+from utils import do_test, raises_instance
+
+
+def make_class(
+ name: str = "", bases: Tuple[Type[Inheritable], ...] = ()
+) -> Type[Inheritable]:
+ cls = type(name, (Inheritable,), {})
+ set_bases(cls, bases)
+ return cls
+
+
+# some tests are adopted from cpython/Lib/test/test_descr.py
+def test_no_inheritance():
+ A = make_class("A")
+ assert A.mro == (A,)
+
+
+def test_single_inheritance():
+ A = make_class("A")
+ B = make_class("B", (A,))
+ assert B.mro == (B, A)
+
+
+def test_multiple_inheritance():
+ A = make_class("A")
+ A = make_class("A")
+ B = make_class("B")
+ C = make_class("C", (A, B))
+ assert C.mro == (C, A, B)
+
+
+def test_diamond_inheritance():
+ A = make_class("A")
+ B = make_class("B", (A,))
+ C = make_class("C", (A,))
+ D = make_class("D", (B, C))
+ assert D.mro == (D, B, C, A)
+
+ E = make_class("E", (C, B))
+ assert E.mro == (E, C, B, A)
+
+ with raises_instance(invalid_mro(["D", "E"])):
+ make_class("F", (D, E))
+
+ with raises_instance(invalid_mro(["E", "D"])):
+ make_class("G", (E, D))
+
+
+def test_ex5_from_c3_switch():
+ A = make_class("A")
+ B = make_class("B")
+ C = make_class("C")
+ X = make_class("X", (A,))
+ Y = make_class("Y", (A,))
+ Z = make_class("Z", (X, B, Y, C))
+ assert Z.mro == (Z, X, B, Y, A, C)
+
+
+def test_monotonicity():
+ Boat = make_class("Boat")
+ DayBoat = make_class("DayBoat", (Boat,))
+ WheelBoat = make_class("WheelBoat", (Boat,))
+ EngineLess = make_class("EngineLess", (DayBoat,))
+ SmallMultihull = make_class("SmallMultihull", (DayBoat,))
+ PedalWheelBoat = make_class("PedalWheelBoat", (EngineLess, WheelBoat))
+ SmallCatamaran = make_class("SmallCatamaran", (SmallMultihull,))
+ Pedalo = make_class("Pedalo", (PedalWheelBoat, SmallCatamaran))
+ assert PedalWheelBoat.mro == (
+ PedalWheelBoat,
+ EngineLess,
+ DayBoat,
+ WheelBoat,
+ Boat,
+ )
+ assert SmallCatamaran.mro == (SmallCatamaran, SmallMultihull, DayBoat, Boat)
+ assert Pedalo.mro == (
+ Pedalo,
+ PedalWheelBoat,
+ EngineLess,
+ SmallCatamaran,
+ SmallMultihull,
+ DayBoat,
+ WheelBoat,
+ Boat,
+ )
+
+
+def test_consistency_with_epg():
+ Pane = make_class("Pane")
+ ScrollingMixin = make_class("ScrollingMixin")
+ EditingMixin = make_class("EditingMixin")
+ ScrollablePane = make_class("ScrollablePane", (Pane, ScrollingMixin))
+ EditablePane = make_class("EditablePane", (Pane, EditingMixin))
+ EditableScrollablePane = make_class(
+ "EditableScrollablePane", (ScrollablePane, EditablePane)
+ )
+ assert EditableScrollablePane.mro == (
+ EditableScrollablePane,
+ ScrollablePane,
+ EditablePane,
+ Pane,
+ ScrollingMixin,
+ EditingMixin,
+ )
+
+
+def test_mro_disagreement():
+ # FIXME: the exact msg is generally considered an impl detail
+ # if util.check_impl_detail(): check message
+
+ A = make_class("A")
+ B = make_class("B", (A,))
+ C = make_class("C")
+
+ with raises_instance(duplicate_base("A")):
+ make_class("X", (A, A))
+
+ with raises_instance(invalid_mro(["A", "B"])):
+ make_class("X", (A, B))
+
+ with raises_instance(invalid_mro(["A", "C", "B"])):
+ make_class("X", (A, C, B))
+
+ GridLayout = make_class("GridLayout")
+ HorizontalGrid = make_class("HorizontalGrid", (GridLayout,))
+ VerticalGrid = make_class("VerticalGrid", (GridLayout,))
+ HVGrid = make_class("HVGrid", (HorizontalGrid, VerticalGrid))
+ VHGrid = make_class("VHGrid", (VerticalGrid, HorizontalGrid))
+
+ with raises_instance(invalid_mro(["HVGrid", "VHGrid"])):
+ make_class("ConfusedGrid", (HVGrid, VHGrid))
+
+
+# TODO: add cpython/Lib/test/test_genericclass.py
+
+
+def test_is_type():
+ A = make_class("A")
+ B = make_class("B")
+ assert not is_type(A, B)
+ assert not is_type(A, B())
+ assert not is_type(A(), B)
+ assert not is_type(A(), B())
+
+ C = make_class("C")
+ assert is_type(C, C)
+ assert is_type(C, C())
+ assert is_type(C(), C)
+ assert is_type(C(), C())
+
+
+def test_is_subclass():
+ A = make_class("A")
+ B = make_class("B")
+
+ assert not is_subclass(A, B)
+ assert not is_subclass(A, B())
+ assert not is_subclass(A(), B)
+ assert not is_subclass(A(), B())
+
+ assert not is_subclass(B, A)
+ assert not is_subclass(B, A())
+ assert not is_subclass(B(), A)
+ assert not is_subclass(B(), A())
+
+ C = make_class("C")
+ D = make_class("D", (C,))
+
+ assert is_subclass(D, C)
+ assert is_subclass(D, C())
+ assert is_subclass(D(), C)
+ assert is_subclass(D(), C())
+
+ assert not is_subclass(C, D)
+ assert not is_subclass(C, D())
+ assert not is_subclass(C(), D)
+ assert not is_subclass(C(), D())
+
+ E = make_class("E", (D, A))
+
+ assert is_subclass(E, D)
+ assert is_subclass(E, D())
+ assert is_subclass(E(), D)
+ assert is_subclass(E(), D())
+
+ assert is_subclass(E, C)
+ assert is_subclass(E, C())
+ assert is_subclass(E(), C)
+ assert is_subclass(E(), C())
+
+ assert is_subclass(E, A)
+ assert is_subclass(E, A())
+ assert is_subclass(E(), A)
+ assert is_subclass(E(), A())
+
+
+def test_is_subclass_tuple():
+ A = make_class("A")
+
+ assert not is_subclass(A, ())
+ assert not is_subclass(A(), ())
+
+ B = make_class("B")
+ C = make_class("C")
+
+ assert not is_subclass(A, (B, C))
+ assert not is_subclass(A, (B, C()))
+ assert not is_subclass(A, (B(), C))
+ assert not is_subclass(A, (B(), C()))
+
+ assert not is_subclass(A(), (B, C))
+ assert not is_subclass(A(), (B, C()))
+ assert not is_subclass(A(), (B(), C))
+ assert not is_subclass(A(), (B(), C()))
+
+ D = make_class("D", (A,))
+
+ assert is_subclass(D, (B, A))
+ assert is_subclass(D, (B, A()))
+ assert is_subclass(D, (B(), A))
+ assert is_subclass(D, (B(), A()))
+
+ assert is_subclass(D(), (B, A))
+ assert is_subclass(D(), (B, A()))
+ assert is_subclass(D(), (B(), A))
+ assert is_subclass(D(), (B(), A()))
+
+
+if __name__ == "__main__":
+ do_test(__file__)
diff --git a/tests/test_normalize_ast.py b/tests/test_normalize_ast.py
new file mode 100644
--- /dev/null
+++ b/tests/test_normalize_ast.py
@@ -0,0 +1,427 @@
+import ast
+import sys
+from typing import cast
+
+from pynalyser.ast import AstNormalizer, normalize_ast
+
+from utils import do_test
+
+
+def assert_node_equality(node1: ast.AST, node2: ast.AST, attributes: bool = False):
+ assert ast.dump(node1, include_attributes=attributes) == ast.dump(
+ node2, include_attributes=attributes
+ )
+
+
+USE_STR = "use '<>' instead of '!='"
+USE_BYTES = USE_STR.encode()
+
+nodes = dict(
+ Num=(
+ "42",
+ ast.Num(n=42, lineno=1, col_offset=0, end_lineno=1, end_col_offset=2),
+ ast.Constant(
+ value=42, kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=2
+ ),
+ ),
+ Str1=(
+ "''",
+ ast.Str(s="", lineno=1, col_offset=0, end_lineno=1, end_col_offset=2),
+ ast.Constant(
+ value="", kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=2
+ ),
+ ),
+ Str2=(
+ repr(USE_STR),
+ ast.Str(s=USE_STR, lineno=1, col_offset=0, end_lineno=1, end_col_offset=26),
+ ast.Constant(
+ value=USE_STR,
+ kind=None,
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=26,
+ ),
+ ),
+ Bytes1=(
+ "b''",
+ ast.Bytes(s=b"", lineno=1, col_offset=0, end_lineno=1, end_col_offset=3),
+ ast.Constant(
+ value=b"", kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=3
+ ),
+ ),
+ Bytes2=(
+ repr(USE_BYTES),
+ ast.Bytes(s=USE_BYTES, lineno=1, col_offset=0, end_lineno=1, end_col_offset=27),
+ ast.Constant(
+ value=USE_BYTES,
+ kind=None,
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=27,
+ ),
+ ),
+ NameConstant1=(
+ "True",
+ ast.NameConstant(
+ value=True, lineno=1, col_offset=0, end_lineno=1, end_col_offset=4
+ ),
+ ast.Constant(
+ value=True,
+ kind=None,
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=4,
+ ),
+ ),
+ NameConstant2=(
+ "False",
+ ast.NameConstant(
+ value=False, lineno=1, col_offset=0, end_lineno=1, end_col_offset=5
+ ),
+ ast.Constant(
+ value=False,
+ kind=None,
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=5,
+ ),
+ ),
+ NameConstant3=(
+ "None",
+ ast.NameConstant(
+ value=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=4
+ ),
+ ast.Constant(
+ value=None,
+ kind=None,
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=4,
+ ),
+ ),
+ Ellipsis1=(
+ "...",
+ ast.Ellipsis(lineno=1, col_offset=0, end_lineno=1, end_col_offset=3),
+ ast.Constant(
+ value=Ellipsis,
+ kind=None,
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=3,
+ ),
+ ),
+ Ellipsis2=(
+ "...",
+ ast.Ellipsis(lineno=1, col_offset=0, end_lineno=1, end_col_offset=3),
+ ast.Constant(
+ value=..., kind=None, lineno=1, col_offset=0, end_lineno=1, end_col_offset=3
+ ),
+ ),
+ Index1=(
+ "the_numbers_thou_shalt_count [ 3 ]",
+ ast.Subscript(
+ value=ast.Name(
+ id="the_numbers_thou_shalt_count",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=28,
+ ),
+ slice=ast.Index(
+ value=ast.Num(
+ n=3, lineno=1, col_offset=31, end_lineno=1, end_col_offset=32
+ )
+ ),
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=34,
+ ),
+ ast.Subscript(
+ value=ast.Name(
+ id="the_numbers_thou_shalt_count",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=28,
+ ),
+ slice=ast.Constant(
+ value=3,
+ kind=None,
+ lineno=1,
+ col_offset=31,
+ end_lineno=1,
+ end_col_offset=32,
+ ),
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=34,
+ ),
+ ),
+ Index2=(
+ "airspeed_velocities [ UnladenSwallow ]",
+ ast.Subscript(
+ value=ast.Name(
+ id="airspeed_velocities",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=19,
+ ),
+ slice=ast.Index(
+ value=ast.Name(
+ id="UnladenSwallow",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=22,
+ end_lineno=1,
+ end_col_offset=36,
+ )
+ ),
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=38,
+ ),
+ ast.Subscript(
+ value=ast.Name(
+ id="airspeed_velocities",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=19,
+ ),
+ slice=ast.Name(
+ id="UnladenSwallow",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=22,
+ end_lineno=1,
+ end_col_offset=36,
+ ),
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=38,
+ ),
+ ),
+ ExtSlice=(
+ "pi [ 3 : 14, 15 ]",
+ ast.Subscript(
+ value=ast.Name(
+ id="pi",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=2,
+ ),
+ slice=ast.ExtSlice(
+ dims=[
+ ast.Slice(
+ lower=ast.Num(
+ n=3,
+ lineno=1,
+ col_offset=5,
+ end_lineno=1,
+ end_col_offset=6,
+ ),
+ upper=ast.Num(
+ n=14,
+ lineno=1,
+ col_offset=9,
+ end_lineno=1,
+ end_col_offset=11,
+ ),
+ step=None,
+ lineno=1,
+ col_offset=5,
+ end_lineno=1,
+ end_col_offset=11,
+ ),
+ ast.Index(
+ value=ast.Num(
+ n=15,
+ lineno=1,
+ col_offset=13,
+ end_lineno=1,
+ end_col_offset=15,
+ )
+ ),
+ ]
+ ),
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=17,
+ ),
+ ast.Subscript(
+ value=ast.Name(
+ id="pi",
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=2,
+ ),
+ slice=ast.Tuple(
+ elts=[
+ ast.Slice(
+ lower=ast.Constant(
+ value=3,
+ lineno=1,
+ col_offset=5,
+ end_lineno=1,
+ end_col_offset=6,
+ ),
+ upper=ast.Constant(
+ value=14,
+ lineno=1,
+ col_offset=9,
+ end_lineno=1,
+ end_col_offset=11,
+ ),
+ step=None,
+ lineno=1,
+ col_offset=5,
+ end_lineno=1,
+ end_col_offset=11,
+ ),
+ ast.Constant(
+ value=15,
+ lineno=1,
+ col_offset=13,
+ end_lineno=1,
+ end_col_offset=15,
+ ),
+ ],
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=5,
+ end_lineno=1,
+ end_col_offset=15,
+ ),
+ ctx=ast.Load(),
+ lineno=1,
+ col_offset=0,
+ end_lineno=1,
+ end_col_offset=17,
+ ),
+ ),
+)
+
+
+############ AstNormalizer #############
+
+
+def normalized_node(node: ast.AST) -> ast.AST:
+ return AstNormalizer().visit(node)
+
+
+def check_node(source: str, deprecated_node: ast.AST, node: ast.AST) -> None:
+ assert_node_equality(normalized_node(deprecated_node), node, True)
+
+
+if sys.version < "3.8":
+
+ def test_visit_Num():
+ check_node(*nodes["Num"])
+
+
+def test_visit_Str():
+ check_node(*nodes["Str1"])
+ check_node(*nodes["Str2"])
+
+
+def test_visit_Bytes():
+ check_node(*nodes["Bytes1"])
+ check_node(*nodes["Bytes2"])
+
+
+def test_visit_NameConstant():
+ check_node(*nodes["NameConstant1"])
+ check_node(*nodes["NameConstant2"])
+ check_node(*nodes["NameConstant3"])
+
+
+def test_visit_Ellipsis():
+ check_node(*nodes["Ellipsis1"])
+ check_node(*nodes["Ellipsis2"])
+
+
+if sys.version < "3.9":
+
+ def test_visit_Index():
+ check_node(*nodes["Index1"])
+ check_node(*nodes["Index2"])
+
+ def test_visit_ExtSlice():
+ return # for now
+ check_node(*nodes["ExtSlice"])
+
+
+############ normalize_ast #############
+
+
+def normalized_source(source: str) -> ast.AST:
+ tree = normalize_ast(ast.parse(source, mode="eval"))
+ return cast(ast.Expression, tree).body
+
+
+def check_source(source: str, deprecated_node: ast.AST, node: ast.AST) -> None:
+ assert_node_equality(normalized_source(source), node, True)
+
+
+def test_normalize_ast_Num():
+ check_source(*nodes["Num"])
+
+
+def test_normalize_ast_Str():
+ check_source(*nodes["Str1"])
+ check_source(*nodes["Str2"])
+
+
+def test_normalize_ast_Bytes():
+ check_source(*nodes["Bytes1"])
+ check_source(*nodes["Bytes2"])
+
+
+def test_normalize_ast_NameConstant():
+ check_source(*nodes["NameConstant1"])
+ check_source(*nodes["NameConstant2"])
+ check_source(*nodes["NameConstant3"])
+
+
+def test_normalize_ast_Ellipsis():
+ check_source(*nodes["Ellipsis1"])
+ check_source(*nodes["Ellipsis2"])
+
+
+def test_normalize_ast_Index():
+ check_source(*nodes["Index1"])
+ check_source(*nodes["Index2"])
+
+
+def test_normalize_ast_ExtSlice():
+ return # for now
+ check_source(*nodes["ExtSlice"])
+
+
+if __name__ == "__main__":
+ do_test(__file__)
diff --git a/tests/test_structure_types.py b/tests/test_structure_types.py
new file mode 100644
--- /dev/null
+++ b/tests/test_structure_types.py
@@ -0,0 +1,75 @@
+from pynalyser.types import *
+from pynalyser.analysers.type_inference import CMPOP, BINOP
+
+from utils import do_test
+
+import operator
+
+# you cannot overwrite 'is' and True/False != BoolType :(
+# operator.__is__ = operator.is_ # type: ignore[attr-defined]
+# operator.__is_not__ = operator.is_not # type: ignore[attr-defined]
+operator.__contains_not__ = lambda a, b: a not in b # type: ignore[attr-defined]
+
+
+def check_binop(op, lhs, rhs, result):
+ assert isinstance(getattr(operator, f"__{op}__")(lhs, rhs), result)
+ assert isinstance(BinOpType(lhs, op, rhs).deref(report=True), result)
+
+
+def check_cmpop(op, lhs, rhs, result):
+ if op not in ("is", "is_not"):
+ assert isinstance(getattr(operator, f"__{op}__")(lhs, rhs), result)
+ assert isinstance(CompareOpType(lhs, [op], [rhs]).deref(report=True), result)
+
+
+BINOPS = set(BINOP.values())
+
+CMPOPS = set(CMPOP.values())
+
+
+def test_int_binop():
+ for op in BINOPS - {"matmul", "truediv", "pow"}:
+ check_binop(op, IntType(), IntType(), IntType)
+ check_binop("truediv", IntType(), IntType(), FloatType)
+ # IntType() ** X() can be different, depending on the sign
+
+
+def test_int_cmp():
+ for op in CMPOPS - {"contains", "contains_not"}:
+ check_cmpop(op, IntType(), IntType(), BoolType)
+
+
+def test_float_binop():
+ for op in BINOPS - {"matmul", "pow"}:
+ check_binop(op, FloatType(), IntType(), FloatType)
+ check_binop(op, IntType(), FloatType(), FloatType)
+ check_binop(op, FloatType(), FloatType(), FloatType)
+ # FloatType() ** X() can be different, depending on the sign
+
+
+def test_sequence():
+ seq = SequenceType(item_type=PynalyserType(), is_builtin=False)
+ check_binop("mul", seq, IntType(), SequenceType)
+ check_binop("mul", IntType(), seq, SequenceType)
+ # assert seq[SliceType()] is AnyType
+ assert SubscriptType(seq, SliceType()).deref(True) is AnyType
+
+
+def test_list():
+ lst = ListType(item_type=DataType(name="test", is_builtin=False), is_builtin=False)
+ assert isinstance(lst * IntType(), SequenceType)
+ # assert lst[IntType()] is lst.item_type
+ assert SubscriptType(lst, IntType()).deref(True) is lst.item_type
+ # assert isinstance(lst[SliceType()], ListType)
+ assert isinstance(SubscriptType(lst, SliceType()).deref(True), ListType)
+
+
+def test_tuple():
+ tpl = TupleType(item_type=PynalyserType(), is_builtin=False)
+ assert isinstance(tpl * IntType(), SequenceType)
+ # assert tpl[SliceType()] is AnyType
+ assert SubscriptType(tpl, SliceType()).deref(True) is AnyType
+
+
+if __name__ == "__main__":
+ do_test(__file__)
diff --git a/tests/utils.py b/tests/utils.py
new file mode 100644
--- /dev/null
+++ b/tests/utils.py
@@ -0,0 +1,19 @@
+"""
+Things that simplify the testing process and help with it
+"""
+
+import re
+
+import pytest
+
+
+def fix_message(message: str):
+ return "^" + re.escape(message).replace("\\ ", " ") + "$"
+
+
+def raises_instance(exc: Exception):
+ return pytest.raises(type(exc), match=fix_message(exc.args[0]))
+
+
+def do_test(file: str) -> None:
+ pytest.main([file, "-vv", "-W", "ignore::pytest.PytestAssertRewriteWarning"])
|