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"])