def convert_example(): data = { "op": "OR", "content": [ { "op": "eq", "field": "host.id", "value": "hello" }, { "op": "not_eq", "field": "host.label", "value": ["db", "redis"] }, ], } # sql expression from iam.contrib.converter.sql import SQLConverter expr = make_expression(data) print("the expression:", expr.expr()) s = SQLConverter() print("to sql where: ", s.convert(data)) print_spearator() # django expression from iam.contrib.converter.queryset import DjangoQuerySetConverter s = DjangoQuerySetConverter() expr = make_expression(data) print("the expression:", expr.expr()) print("to django queryset:", s.convert(data))
def test_make_expression(): d = {"op": "eq", "field": "host.id", "value": "a1"} expr = make_expression(d) assert expr.expr() == "(host.id eq 'a1')" d1 = ObjectSet() d1.add_object("host", {"id": "a1", "name": "b1"}) assert expr.eval(d1)
def test_make_expression_or(): d = { "op": "OR", "content": [ { "op": "eq", "field": "host.id", "value": "a1" }, { "op": "eq", "field": "host.name", "value": "b1" }, ], } expr = make_expression(d) assert expr.expr() == "((host.id eq 'a1') OR (host.name eq 'b1'))" d1 = ObjectSet() d1.add_object("host", {"id": "a1", "name": "b1"}) assert expr.eval(d1)
def eval_exmaple(): # create a resource, type is host h = {"id": "hello"} host = DictObject(h) print("host.id =", host.id) print("host.notexists =", host.notexists) # create a resource, type is module class Module(object): pass m = Module() m.id = "world" module = DictObject(m) print("module.id =", module.id) print("module.notexists =", module.notexists) print_spearator() # make a object set contains two resource type s = ObjectSet() s.add_object("host", host) s.add_object("module", module) print("object_set host.id", s.get("host.id")) print("object_set host.id", s.get("host.notexists")) print("object_set module.id", s.get("module.id")) print("object_set module.id", s.get("module.notexists")) print("object_set cluster.id", s.get("cluster.id")) print_spearator() # define a policy data = { "op": "OR", "content": [ { "op": "eq", "field": "host.id", "value": "hello" }, { "op": "not_eq", "field": "module.id", "value": "world" }, ], } # make a policy expression expr = make_expression(data) print("the expression:", expr.expr()) print("the expression render:", expr.render(s)) print("the eval result:", expr.eval(s)) print_spearator() data1 = { "op": "eq", "field": "host.id", "value": "hello", } expr1 = make_expression(data1) print("the expression:", expr1.expr()) print("the expression render:", expr1.render(s)) print("the eval result:", expr1.eval(s)) print_spearator() data1 = { "op": "not_eq", "field": "host.id", "value": "hello", } expr1 = make_expression(data1) print("the expression:", expr1.expr()) print("the expression render:", expr1.render(s)) print("the eval result:", expr1.eval(s))