def test_partial_constraint(polar): class User: pass class Post: pass polar.register_class(User) polar.register_class(Post) polar.load_str("f(x: User) if x.user = 1;") polar.load_str("f(x: Post) if x.post = 1;") partial = Partial("x", TypeConstraint("User")) results = polar.query_rule("f", partial) first = next(results)["bindings"]["x"] and_args = unwrap_and(first) assert len(and_args) == 2 assert and_args[0] == Expression("Isa", [Variable("_this"), Pattern("User", {})]) unify = unwrap_and(and_args[1]) assert unify == Expression( "Unify", [Expression("Dot", [Variable("_this"), "user"]), 1] ) with pytest.raises(StopIteration): next(results)
def test_dict_specializers(polar, qvar, qeval, query): class Animal: def __init__(self, species=None, genus=None, family=None): self.genus = genus self.species = species polar.register_class(Animal) rules = """ what_is(_: {genus: "canis"}, res) if res = "canine"; what_is(_: {species: "canis lupus", genus: "canis"}, res) if res = "wolf"; what_is(_: {species: "canis familiaris", genus: "canis"}, res) if res = "dog"; """ polar.load_str(rules) wolf = 'new Animal(species: "canis lupus", genus: "canis", family: "canidae")' dog = 'new Animal(species: "canis familiaris", genus: "canis", family: "canidae")' canine = 'new Animal(genus: "canis", family: "canidae")' assert len(query(f"what_is({wolf}, res)")) == 2 assert len(query(f"what_is({dog}, res)")) == 2 assert len(query(f"what_is({canine}, res)")) == 1 assert qvar(f"what_is({wolf}, res)", "res") == ["wolf", "canine"] assert qvar(f"what_is({dog}, res)", "res") == ["dog", "canine"] assert qvar(f"what_is({canine}, res)", "res") == ["canine"]
def test_method_with_kwargs(polar, qvar): class Test: def kwarg_method(self, x=1, y=2): self.x = x self.y = y return True polar.register_class(Test) rules = """ defaults(result) if test = new Test() and test.kwarg_method() and result = [test.x, test.y]; kwargs(result) if test = new Test() and test.kwarg_method(y: 4, x: 3) and result = [test.x, test.y]; args(result) if test = new Test() and test.kwarg_method(5, 6) and result = [test.x, test.y]; mixed(result) if test = new Test() and test.kwarg_method(7, y: 8) and result = [test.x, test.y]; """ polar.load_str(rules) qvar("defaults(result)", "result") == [1, 2] qvar("kwargs(result)", "result") == [3, 4] qvar("args(result)", "result") == [5, 6] qvar("mixed(result)", "result") == [7, 8]
def test_bool_from_external_call(polar, qeval, qvar, query): class Booler: def whats_up(self): yield True polar.register_class(Booler) result = qvar("new Booler().whats_up() = var", "var", one=True) assert qeval("new Booler().whats_up()")
def test_external(polar, qvar, qeval): class Bar: def y(self): return "y" class Foo: def __init__(self, a="a"): self.a = a def b(self): yield "b" @classmethod def c(cls): assert issubclass(cls, Foo) return "c" def d(self, x): return x def bar(self): return Bar() def e(self): return [1, 2, 3] def f(self): yield [1, 2, 3] yield [4, 5, 6] yield 7 def g(self): return {"hello": "world"} def h(self): return True def capital_foo(): return Foo(a="A") polar.register_class(Foo, from_polar=capital_foo) assert qvar("new Foo().a = x", "x", one=True) == "A" with pytest.raises(RuntimeError, match="tried to call 'a' but it is not callable"): assert not qeval("new Foo().a() = x") assert not qvar("new Foo().b = x", "x", one=True) == "b" assert qvar("new Foo().b() = x", "x", one=True) == "b" assert not qvar("Foo.c = x", "x", one=True) == "c" assert qvar("Foo.c() = x", "x", one=True) == "c" assert qvar("new Foo() = f and f.a = x", "x", one=True) == "A" assert qvar("new Foo().bar().y() = x", "x", one=True) == "y" assert qvar("new Foo().e() = x", "x", one=True) == [1, 2, 3] assert qvar("new Foo().f() = x", "x") == [[1, 2, 3], [4, 5, 6], 7] assert qvar("new Foo().g().hello = x", "x", one=True) == "world" assert qvar("new Foo().h() = x", "x", one=True) is True
def test_clear_rules(polar, query): class Test: pass polar.register_class(Test) polar.load_str("f(x) if x = 1;") assert len(query("f(1)")) == 1 assert len(query("x = new Test()")) == 1 polar.clear_rules() assert len(query("f(1)")) == 0 assert len(query("x = new Test()")) == 1
def test_return_list(polar, query): class User: def groups(self): return ["engineering", "social", "admin"] polar.register_class(User) # for testing lists polar.load_str('allow(actor: User, "join", "party") if "social" in actor.groups();') assert query(Predicate(name="allow", args=[User(), "join", "party"]))
def test_static_method(polar, qeval): class Foo(list): @staticmethod def plus_one(x): return x + 1 def map(self, f): return [f(x) for x in self] polar.register_class(Foo) polar.load_str("f(x: Foo) if x.map(Foo.plus_one) = [2, 3, 4];") assert next(polar.query_rule("f", Foo([1, 2, 3])))
def test_external(polar, qvar): class Bar: def y(self): return "y" class Foo: def __init__(self, a="a"): self.a = a def b(self): yield "b" @classmethod def c(cls): assert issubclass(cls, Foo) return "c" def d(self, x): return x def bar(self): return Bar() def e(self): return [1, 2, 3] def f(self): yield [1, 2, 3] yield [4, 5, 6] yield 7 def g(self): return {"hello": "world"} def h(self): return True def capital_foo(): return Foo(a="A") polar.register_class(Foo, from_polar=capital_foo) assert qvar("new Foo{}.a = x", "x", one=True) == "A" assert qvar("new Foo{}.a() = x", "x", one=True) == "A" assert qvar("new Foo{}.b = x", "x", one=True) == "b" assert qvar("new Foo{}.b() = x", "x", one=True) == "b" assert qvar("Foo.c = x", "x", one=True) == "c" assert qvar("Foo.c() = x", "x", one=True) == "c" assert qvar("new Foo{} = f and f.a() = x", "x", one=True) == "A" assert qvar("new Foo{}.bar().y() = x", "x", one=True) == "y" assert qvar("new Foo{}.e = x", "x", one=True) == [1, 2, 3] assert qvar("new Foo{}.f = x", "x") == [[1, 2, 3], [4, 5, 6], 7] assert qvar("new Foo{}.g.hello = x", "x", one=True) == "world" assert qvar("new Foo{}.h = x", "x", one=True) is True
def test_lookup_errors(polar, query): class Foo: def foo(self): return "foo" polar.register_class(Foo) # Unify with an invalid field doesn't error. assert query('new Foo() = {bar: "bar"}') == [] # Dot op with an invalid field does error. with pytest.raises(exceptions.PolarRuntimeError) as e: query('new Foo().bar = "bar"') == [] assert "Application error: 'Foo' object has no attribute 'bar'" in str(e.value)
def test_unify(polar, qeval): class Foo: def __init__(self, foo): self.foo = foo def __eq__(self, other): if isinstance(other, Foo): return self.foo == other.foo return False polar.register_class(Foo) polar.load_str("foo() if new Foo(foo: 1) = new Foo(foo: 1);") assert qeval("foo()")
def test_class_specializers(polar, qvar, qeval, query): class A: def a(self): return "A" def x(self): return "A" class B(A): def b(self): return "B" def x(self): return "B" class C(B): def c(self): return "C" def x(self): return "C" class X: def x(self): return "X" polar.register_class(A) polar.register_class(B) polar.register_class(C) polar.register_class(X) rules = """ test(_: A{}); test(_: B{}); try(_: B{}, res) if res = 2; try(_: C{}, res) if res = 3; try(_: A{}, res) if res = 1; """ polar.load_str(rules) assert qvar("new A{}.a = x", "x", one=True) == "A" assert qvar("new A{}.x = x", "x", one=True) == "A" assert qvar("new B{}.a = x", "x", one=True) == "A" assert qvar("new B{}.b = x", "x", one=True) == "B" assert qvar("new B{}.x = x", "x", one=True) == "B" assert qvar("new C{}.a = x", "x", one=True) == "A" assert qvar("new C{}.b = x", "x", one=True) == "B" assert qvar("new C{}.c = x", "x", one=True) == "C" assert qvar("new C{}.x = x", "x", one=True) == "C" assert qvar("new X{}.x = x", "x", one=True) == "X" assert len(query("test(new A{})")) == 1 assert len(query("test(new B{})")) == 2 assert qvar("try(new A{}, x)", "x") == [1] assert qvar("try(new B{}, x)", "x") == [2, 1] assert qvar("try(new C{}, x)", "x") == [3, 2, 1] assert qvar("try(new X{}, x)", "x") == []
def test_class_field_specializers(polar, qvar, qeval, query): class Animal: def __init__(self, species=None, genus=None, family=None): self.genus = genus self.species = species self.family = family polar.register_class(Animal) rules = """ what_is(_: Animal, res) if res = "animal"; what_is(_: Animal{genus: "canis"}, res) if res = "canine"; what_is(_: Animal{family: "canidae"}, res) if res = "canid"; what_is(_: Animal{species: "canis lupus", genus: "canis"}, res) if res = "wolf"; what_is(_: Animal{species: "canis familiaris", genus: "canis"}, res) if res = "dog"; what_is(_: Animal{species: s, genus: "canis"}, res) if res = s; """ polar.load_str(rules) wolf = 'new Animal(species: "canis lupus", genus: "canis", family: "canidae")' dog = 'new Animal(species: "canis familiaris", genus: "canis", family: "canidae")' canine = 'new Animal(genus: "canis", family: "canidae")' canid = 'new Animal(family: "canidae")' animal = "new Animal()" assert len(query(f"what_is({wolf}, res)")) == 5 assert len(query(f"what_is({dog}, res)")) == 5 assert len(query(f"what_is({canine}, res)")) == 4 assert len(query(f"what_is({canid}, res)")) == 2 assert len(query(f"what_is({animal}, res)")) == 1 assert qvar(f"what_is({wolf}, res)", "res") == [ "wolf", "canis lupus", "canine", "canid", "animal", ] assert qvar(f"what_is({dog}, res)", "res") == [ "dog", "canis familiaris", "canine", "canid", "animal", ] assert qvar(f"what_is({canine}, res)", "res") == [None, "canine", "canid", "animal"] assert qvar(f"what_is({canid}, res)", "res") == ["canid", "animal"] assert qvar(f"what_is({animal}, res)", "res") == ["animal"]
def test_class_specializers(polar, qvar, qeval, query): class A: def a(self): return "A" def x(self): return "A" class B(A): def b(self): return "B" def x(self): return "B" class C(B): def c(self): return "C" def x(self): return "C" class X: def x(self): return "X" polar.register_class(A) polar.register_class(B) polar.register_class(C) polar.register_class(X) rules = """ test(_: A); test(_: B); try(_: B, res) if res = 2; try(_: C, res) if res = 3; try(_: A, res) if res = 1; """ polar.load_str(rules) assert qvar("new A().a() = x", "x", one=True) == "A" assert qvar("new A().x() = x", "x", one=True) == "A" assert qvar("new B().a() = x", "x", one=True) == "A" assert qvar("new B().b() = x", "x", one=True) == "B" assert qvar("new B().x() = x", "x", one=True) == "B" assert qvar("new C().a() = x", "x", one=True) == "A" assert qvar("new C().b() = x", "x", one=True) == "B" assert qvar("new C().c() = x", "x", one=True) == "C" assert qvar("new C().x() = x", "x", one=True) == "C" assert qvar("new X().x() = x", "x", one=True) == "X" assert len(query("test(new A())")) == 1 assert len(query("test(new B())")) == 2 assert qvar("try(new A(), x)", "x") == [1] assert qvar("try(new B(), x)", "x") == [2, 1] assert qvar("try(new C(), x)", "x") == [3, 2, 1] assert qvar("try(new X(), x)", "x") == []
def test_iterators(polar, qeval, qvar): class Foo: pass polar.register_class(Foo) with pytest.raises(exceptions.InvalidIteratorError) as e: qeval("x in new Foo()") class Bar(list): def sum(self): return sum(x for x in self) polar.register_class(Bar) assert qvar("x in new Bar([1, 2, 3])", "x") == [1, 2, 3] assert qvar("x = new Bar([1, 2, 3]).sum()", "x", one=True) == 6
def test_return_none(polar, qeval): class Foo: def this_is_none(self): return None polar.register_class(Foo) polar.load_str("f(x) if x.this_is_none = 1;") assert not list(polar.query_rule("f", Foo())) polar.load_str("f(x) if x.this_is_none.bad_call = 1;") with pytest.raises(exceptions.PolarRuntimeException) as e: list(polar.query_rule("f", Foo())) assert str(e.value).find( "Application error: 'NoneType' object has no attribute 'bad_call'")
def test_instance_cache(polar, qeval, query): class Counter: count = 0 def __init__(self): self.__class__.count += 1 polar.register_class(Counter) polar.load_str("f(c: Counter) if c.count > 0;") assert Counter.count == 0 c = Counter() assert Counter.count == 1 assert query(Predicate(name="f", args=[c])) assert Counter.count == 1 assert c not in polar.host.instances.values()
def test_numbers_from_external_call(polar, qeval, qvar, query): class Numberer: def give_me_an_int(self): yield 1 def give_me_a_float(self): yield 1.234 polar.register_class(Numberer) result = qvar("new Numberer().give_me_an_int() = var", "var", one=True) assert result == 1 assert qeval("new Numberer().give_me_an_int() = 1") result = qvar("new Numberer().give_me_a_float() = var", "var", one=True) assert result == 1.234 assert qeval("new Numberer().give_me_a_float() = 1.234")
def test_constructor(polar, qvar): """Test that class constructor is called correctly with constructor syntax.""" class Foo: def __init__(self, a, b, bar, baz): self.a = a self.b = b self.bar = bar self.baz = baz polar.register_class(Foo) # test positional args instance = qvar( "instance = new Foo(1,2,3,4)", "instance", one=True, ) assert instance.a == 1 assert instance.b == 2 assert instance.bar == 3 assert instance.baz == 4 # test positional and kwargs instance = qvar( "instance = new Foo(1, 2, bar: 3, baz: 4)", "instance", one=True, ) assert instance.a == 1 assert instance.b == 2 assert instance.bar == 3 assert instance.baz == 4 # test kwargs instance = qvar( "instance = new Foo(bar: 3, a: 1, baz: 4, b: 2)", "instance", one=True, ) assert instance.a == 1 assert instance.b == 2 assert instance.bar == 3 assert instance.baz == 4
def test_constructor(polar, qvar): """Test that class constructor is called correctly with constructor syntax.""" class TestConstructor: def __init__(self, x): self.x = x polar.register_class(TestConstructor) assert ( qvar("instance = new TestConstructor{x: 1} and y = instance.x", "y", one=True) == 1 ) assert ( qvar("instance = new TestConstructor{x: 2} and y = instance.x", "y", one=True) == 2 ) assert ( qvar( "instance = new TestConstructor{x: new TestConstructor{x: 3}} and y = instance.x.x", "y", one=True, ) == 3 ) class TestConstructorTwo: def __init__(self, x, y): self.x = x self.y = y polar.register_class(TestConstructorTwo) assert ( qvar( "instance = new TestConstructorTwo{x: 1, y: 2} and x = instance.x and y = instance.y", "y", one=True, ) == 2 )
def test_external_op(polar, query): class A: def __init__(self, a): self.a = a def __gt__(self, other): return self.a > other.a def __lt__(self, other): return self.a < other.a def __eq__(self, other): return self.a == other.a polar.register_class(A) a1 = A(1) a2 = A(2) polar.load_str("lt(a, b) if a < b;") polar.load_str("gt(a, b) if a > b;") assert query(Predicate("lt", [a1, a2])) assert not query(Predicate("lt", [a2, a1])) assert query(Predicate("gt", [a2, a1]))
def load_policy(polar): polar.register_class(Http) polar.register_class(PathMapper) polar.load_file(Path(__file__).parent / "policies" / "test_api.polar")
def externals(polar): polar.register_class(Qux) polar.register_class(Bar) polar.register_class(Foo) polar.register_class(MyClass) polar.register_class(YourClass) polar.register_class(OurClass)
def test_specializers_mixed(polar, qvar, qeval, query): class Animal: def __init__(self, species=None, genus=None, family=None): self.genus = genus self.species = species self.family = family polar.register_class(Animal) # load rules rules = """ what_is(_: Animal, res) if res = "animal_class"; what_is(_: Animal{genus: "canis"}, res) if res = "canine_class"; what_is(_: {genus: "canis"}, res) if res = "canine_dict"; what_is(_: Animal{family: "canidae"}, res) if res = "canid_class"; what_is(_: {species: "canis lupus", genus: "canis"}, res) if res = "wolf_dict"; what_is(_: {species: "canis familiaris", genus: "canis"}, res) if res = "dog_dict"; what_is(_: Animal{species: "canis lupus", genus: "canis"}, res) if res = "wolf_class"; what_is(_: Animal{species: "canis familiaris", genus: "canis"}, res) if res = "dog_class"; """ polar.load_str(rules) wolf = 'new Animal(species: "canis lupus", genus: "canis", family: "canidae")' dog = 'new Animal(species: "canis familiaris", genus: "canis", family: "canidae")' canine = 'new Animal(genus: "canis", family: "canidae")' wolf_dict = '{species: "canis lupus", genus: "canis", family: "canidae"}' dog_dict = '{species: "canis familiaris", genus: "canis", family: "canidae"}' canine_dict = '{genus: "canis", family: "canidae"}' # test number of results assert len(query(f"what_is({wolf}, res)")) == 6 assert len(query(f"what_is({dog}, res)")) == 6 assert len(query(f"what_is({canine}, res)")) == 4 assert len(query(f"what_is({wolf_dict}, res)")) == 2 assert len(query(f"what_is({dog_dict}, res)")) == 2 assert len(query(f"what_is({canine_dict}, res)")) == 1 # test rule ordering for instances assert qvar(f"what_is({wolf}, res)", "res") == [ "wolf_class", "canine_class", "canid_class", "animal_class", "wolf_dict", "canine_dict", ] assert qvar(f"what_is({dog}, res)", "res") == [ "dog_class", "canine_class", "canid_class", "animal_class", "dog_dict", "canine_dict", ] assert qvar(f"what_is({canine}, res)", "res") == [ "canine_class", "canid_class", "animal_class", "canine_dict", ] # test rule ordering for dicts assert qvar(f"what_is({wolf_dict}, res)", "res") == ["wolf_dict", "canine_dict"] assert qvar(f"what_is({dog_dict}, res)", "res") == ["dog_dict", "canine_dict"] assert qvar(f"what_is({canine_dict}, res)", "res") == ["canine_dict"]