[SEBA-412] Automated reformat of Python code
Passes of modernize, autopep8, black, then check with flake8
flake8 + manual fixes:
lib/xos-config
lib/xos-kafka
lib/xos-util
xos/coreapi
xos/api
xos/xos_client
Change-Id: Ib23cf84cb13beb3c6381fa0d79594dc9131dc815
diff --git a/lib/xos-genx/xos-genx-tests/__init__.py b/lib/xos-genx/xos-genx-tests/__init__.py
index d4e8062..b0fb0b2 100644
--- a/lib/xos-genx/xos-genx-tests/__init__.py
+++ b/lib/xos-genx/xos-genx-tests/__init__.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -12,5 +11,3 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-
-
diff --git a/lib/xos-genx/xos-genx-tests/attics/xosmodel_bottom.py b/lib/xos-genx/xos-genx-tests/attics/xosmodel_bottom.py
index 734aed5..b4fbd54 100644
--- a/lib/xos-genx/xos-genx-tests/attics/xosmodel_bottom.py
+++ b/lib/xos-genx/xos-genx-tests/attics/xosmodel_bottom.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,4 +14,4 @@
def bottom():
- return 'bottom'
+ return "bottom"
diff --git a/lib/xos-genx/xos-genx-tests/attics/xosmodel_header.py b/lib/xos-genx/xos-genx-tests/attics/xosmodel_header.py
index 5cee4a3..9ac13cc 100644
--- a/lib/xos-genx/xos-genx-tests/attics/xosmodel_header.py
+++ b/lib/xos-genx/xos-genx-tests/attics/xosmodel_header.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,4 +14,4 @@
def header():
- return 'header'
+ return "header"
diff --git a/lib/xos-genx/xos-genx-tests/attics/xosmodel_model.py b/lib/xos-genx/xos-genx-tests/attics/xosmodel_model.py
index 048641a..5d5ab91 100644
--- a/lib/xos-genx/xos-genx-tests/attics/xosmodel_model.py
+++ b/lib/xos-genx/xos-genx-tests/attics/xosmodel_model.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,4 +14,4 @@
def model():
- return 'model'
+ return "model"
diff --git a/lib/xos-genx/xos-genx-tests/attics/xosmodel_top.py b/lib/xos-genx/xos-genx-tests/attics/xosmodel_top.py
index 79752d0..e25560a 100644
--- a/lib/xos-genx/xos-genx-tests/attics/xosmodel_top.py
+++ b/lib/xos-genx/xos-genx-tests/attics/xosmodel_top.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,4 +14,4 @@
def top():
- return 'top'
+ return "top"
diff --git a/lib/xos-genx/xos-genx-tests/counts b/lib/xos-genx/xos-genx-tests/counts
index 8ab44d4..bfbbd7c 100755
--- a/lib/xos-genx/xos-genx-tests/counts
+++ b/lib/xos-genx/xos-genx-tests/counts
@@ -5,14 +5,16 @@
from core.models import XOSBase, PlModelMixIn
import pdb
+
def count(lst):
c = 0
for l in lst[0]:
- ll = l.lstrip()
- if (ll and not ll.startswith('#') and ll.rstrip()!='pass' and 'ModelLink' not in ll and 'CHOICES' not in ll):
- c+=1
+ ll = l.lstrip()
+ if (ll and not ll.startswith('#') and ll.rstrip() != 'pass' and 'ModelLink' not in ll and 'CHOICES' not in ll):
+ c += 1
return c
+
def is_model_class(model):
""" Return True if 'model' is something that we're interested in """
if not inspect.isclass(model):
@@ -26,9 +28,9 @@
return False
+
for a in dir(core.models):
- x = getattr(core.models,a)
+ x = getattr(core.models, a)
if (is_model_class(x)):
lines = inspect.getsourcelines(x)
- print x.__name__,":",count(lines)
-
+ print x.__name__, ":", count(lines)
diff --git a/lib/xos-genx/xos-genx-tests/helpers.py b/lib/xos-genx/xos-genx-tests/helpers.py
index ae52076..4687bb3 100644
--- a/lib/xos-genx/xos-genx-tests/helpers.py
+++ b/lib/xos-genx/xos-genx-tests/helpers.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,18 +18,19 @@
# Constants
OUTPUT_DIR = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/out/")
-TMP_TARGET_PATH = os.path.join(OUTPUT_DIR, 'tmp.xtarget')
+TMP_TARGET_PATH = os.path.join(OUTPUT_DIR, "tmp.xtarget")
# Passed around in various security / validation checks
+
+
class FakeObject:
pass
-class XProtoTestHelpers:
+class XProtoTestHelpers:
@staticmethod
def write_tmp_target(target):
- tmp_file = open(TMP_TARGET_PATH, 'w')
+ tmp_file = open(TMP_TARGET_PATH, "w")
tmp_file.write(target)
tmp_file.close()
return TMP_TARGET_PATH
-
diff --git a/lib/xos-genx/xos-genx-tests/test_cli.py b/lib/xos-genx/xos-genx-tests/test_cli.py
index 4beef06..3f94865 100644
--- a/lib/xos-genx/xos-genx-tests/test_cli.py
+++ b/lib/xos-genx/xos-genx-tests/test_cli.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,33 +18,39 @@
from mock import patch
from xosgenx.xosgen import XosGen
+
class Args:
pass
+
class XOSProcessorTest(unittest.TestCase):
"""
Testing the CLI binding for the XOS Generative Toolchain
"""
def setUp(self):
- os.chdir(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), ".."))
+ os.chdir(
+ os.path.join(
+ os.path.abspath(os.path.dirname(os.path.realpath(__file__))), ".."
+ )
+ )
def test_generator(self):
"""
[XOS-GenX] The CLI entry point should correctly parse params
"""
args = Args()
- args.files = ['xos-genx-tests/xproto/test.xproto']
- args.target = 'xos-genx-tests/xtarget/test.xtarget'
- args.output = 'xos-genx-tests/out/dir/'
+ args.files = ["xos-genx-tests/xproto/test.xproto"]
+ args.target = "xos-genx-tests/xtarget/test.xtarget"
+ args.output = "xos-genx-tests/out/dir/"
args.write_to_file = "target"
args.dest_file = None
args.dest_extension = None
expected_args = Args()
- expected_args.files = [os.path.abspath(os.getcwd() + '/' + args.files[0])]
- expected_args.target = os.path.abspath(os.getcwd() + '/' + args.target)
- expected_args.output = os.path.abspath(os.getcwd() + '/' + args.output)
+ expected_args.files = [os.path.abspath(os.getcwd() + "/" + args.files[0])]
+ expected_args.target = os.path.abspath(os.getcwd() + "/" + args.target)
+ expected_args.output = os.path.abspath(os.getcwd() + "/" + args.output)
with patch("xosgenx.xosgen.XOSProcessor.process") as generator:
XosGen.init(args)
@@ -53,5 +58,6 @@
self.assertEqual(actual_args.files, expected_args.files)
self.assertEqual(actual_args.output, expected_args.output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
diff --git a/lib/xos-genx/xos-genx-tests/test_django_generator.py b/lib/xos-genx/xos-genx-tests/test_django_generator.py
index 4f4dae4..a81f80c 100644
--- a/lib/xos-genx/xos-genx-tests/test_django_generator.py
+++ b/lib/xos-genx/xos-genx-tests/test_django_generator.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,34 +17,36 @@
import os
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
-VROUTER_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/vrouterport.xproto")
+VROUTER_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/vrouterport.xproto"
+)
# Generate Protobuf from Xproto and then parse the resulting Protobuf
+
+
class XProtoProtobufGeneratorTest(unittest.TestCase):
def test_proto_generator(self):
"""
[XOS-GenX] Generate DJANGO models, verify Fields and Foreign Keys
"""
- args = XOSProcessorArgs(files = [VROUTER_XPROTO],
- target = 'django.xtarget')
+ args = XOSProcessorArgs(files=[VROUTER_XPROTO], target="django.xtarget")
output = XOSProcessor.process(args)
- fields = filter(lambda s:'Field(' in s, output.splitlines())
+ fields = filter(lambda s: "Field(" in s, output.splitlines())
self.assertEqual(len(fields), 2)
- links = filter(lambda s:'Key(' in s, output.splitlines())
+ links = filter(lambda s: "Key(" in s, output.splitlines())
self.assertEqual(len(links), 2)
def test_optional_relations(self):
"""
[XOS-GenX] Generate DJANGO models, verify relations
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
message ENodeB {
}
-
+
message Handover {
}
@@ -55,15 +56,14 @@
}
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = 'django.xtarget')
+ args = XOSProcessorArgs(inputs=xproto, target="django.xtarget")
output = XOSProcessor.process(args)
- null_true = filter(lambda s: 'null = True' in s, output.splitlines())
- null_false = filter(lambda s: 'null = False' in s, output.splitlines())
+ null_true = filter(lambda s: "null = True" in s, output.splitlines())
+ null_false = filter(lambda s: "null = False" in s, output.splitlines())
- blank_true = filter(lambda s: 'blank = True' in s, output.splitlines())
- blank_false = filter(lambda s: 'blank = False' in s, output.splitlines())
+ blank_true = filter(lambda s: "blank = True" in s, output.splitlines())
+ blank_false = filter(lambda s: "blank = False" in s, output.splitlines())
self.assertEqual(len(null_true), 1)
self.assertEqual(len(null_false), 1)
@@ -74,8 +74,7 @@
"""
[XOS-GenX] Generate DJANGO models, verify feedback_state fields
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
message ParentFoo {
@@ -87,8 +86,7 @@
}
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = 'django.xtarget')
+ args = XOSProcessorArgs(inputs=xproto, target="django.xtarget")
output = XOSProcessor.process(args)
self.assertIn("feedback_state_fields = ['parent_name', 'name']", output)
@@ -97,8 +95,7 @@
"""
[XOS-GenX] Use django validors for min and max values
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
message Foo (ParentFoo) {
@@ -106,15 +103,13 @@
}
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = 'django.xtarget')
+ args = XOSProcessorArgs(inputs=xproto, target="django.xtarget")
output = XOSProcessor.process(args)
self.assertIn("validators=[", output)
self.assertIn("MinValueValidator(1)", output)
self.assertIn("MaxValueValidator(10)", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_field_graph.py b/lib/xos-genx/xos-genx-tests/test_field_graph.py
index 478708a..cfb4c8b 100644
--- a/lib/xos-genx/xos-genx-tests/test_field_graph.py
+++ b/lib/xos-genx/xos-genx-tests/test_field_graph.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,11 +17,12 @@
from xosgenx.jinja2_extensions import FieldNotFound
from helpers import XProtoTestHelpers
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
+from functools import reduce
+
class XProtoFieldGraphTest(unittest.TestCase):
def _test_field_graph(self):
- xproto = \
-"""
+ xproto = """
message VRouterDevice (PlCoreBase){
optional string name = 1 [help_text = "device friendly name", max_length = 20, null = True, db_index = False, blank = True, unique_with="openflow_id"];
required string openflow_id = 2 [help_text = "device identifier in ONOS", max_length = 20, null = False, db_index = False, blank = False, unique_with="name"];
@@ -39,45 +39,46 @@
}
"""
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{{ xproto_field_graph_components(proto.messages.0.fields, proto.messages.0) }}
-""")
+"""
+ )
- args = XOSProcessorArgs(inputs = xproto,
- target = target)
+ args = XOSProcessorArgs(inputs=xproto, target=target)
output = XOSProcessor.process(args)
- output = eval(output)
- self.assertIn({'A','B','C'}, output)
- self.assertIn({'openflow_id','name'}, output)
- self.assertIn({'config_key','vrouter_service','driver'}, output)
- self.assertIn({'E','F','G'}, output)
-
- union = reduce(lambda acc,x: acc | x, output)
- self.assertNotIn('D', union)
+ output = eval(output)
+ self.assertIn({"A", "B", "C"}, output)
+ self.assertIn({"openflow_id", "name"}, output)
+ self.assertIn({"config_key", "vrouter_service", "driver"}, output)
+ self.assertIn({"E", "F", "G"}, output)
+
+ union = reduce(lambda acc, x: acc | x, output)
+ self.assertNotIn("D", union)
def test_missing_field(self):
- xproto = \
-"""
+ xproto = """
message Foo (PlCoreBase){
required string A = 6 [unique_with="B"];
}
"""
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{{ xproto_field_graph_components(proto.messages.0.fields, proto.messages.0) }}
-""")
+"""
+ )
def generate():
- args = XOSProcessorArgs(inputs = xproto,
- target = target)
+ args = XOSProcessorArgs(inputs=xproto, target=target)
output = XOSProcessor.process(args)
with self.assertRaises(FieldNotFound) as e:
- generate()
+ generate()
- self.assertEqual(e.exception.message, 'Field "B" not found in model "Foo", referenced from field "A" by option "unique_with"')
+ self.assertEqual(
+ e.exception.message,
+ 'Field "B" not found in model "Foo", referenced from field "A" by option "unique_with"',
+ )
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_general_security.py b/lib/xos-genx/xos-genx-tests/test_general_security.py
index 1a7b7ca..c675b16 100644
--- a/lib/xos-genx/xos-genx-tests/test_general_security.py
+++ b/lib/xos-genx/xos-genx-tests/test_general_security.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,33 +20,38 @@
"""The function below is for eliminating warnings arising due to the missing output_security_check,
which is generated and loaded dynamically.
"""
+
+
def output_security_check(x, y):
raise Exception("Security enforcer not generated. Test failed.")
return False
+
"""
-The tests below use the Python code target to generate
+The tests below use the Python code target to generate
Python security policies, set up an appropriate environment and execute the Python.
"""
+
+
class XProtoSecurityTest(unittest.TestCase):
def setUp(self):
- self.target = XProtoTestHelpers.write_tmp_target("""
+ self.target = XProtoTestHelpers.write_tmp_target(
+ """
{% for name, policy in proto.policies.items() %}
{{ xproto_fol_to_python_test(name, policy, None, '0') }}
{% endfor %}
-""")
+"""
+ )
def test_constant(self):
- xproto = \
-"""
+ xproto = """
policy output < True >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def output_security_check(obj, ctx):
@@ -59,17 +63,15 @@
self.assertTrue(verdict)
def test_equal(self):
- xproto = \
-"""
+ xproto = """
policy output < ctx.user = obj.user >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def output_security_check(obj, ctx):
@@ -85,18 +87,18 @@
verdict = output_security_check(obj, ctx)
def test_call_policy(self):
- xproto = \
-"""
+ xproto = """
policy sub_policy < ctx.user = obj.user >
policy output < *sub_policy(child) >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output,globals()) # This loads the generated function, which should look like this:
+ exec(
+ output, globals()
+ ) # This loads the generated function, which should look like this:
"""
def sub_policy_security_check(obj, ctx):
@@ -105,10 +107,10 @@
def output_security_check(obj, ctx):
if obj.child:
- i1 = sub_policy_security_check(obj.child, ctx)
- else:
- i1 = True
- return i1
+ i1 = sub_policy_security_check(obj.child, ctx)
+ else:
+ i1 = True
+ return i1
"""
obj = FakeObject()
@@ -122,18 +124,18 @@
self.assertTrue(verdict)
def test_call_policy_child_none(self):
- xproto = \
-"""
+ xproto = """
policy sub_policy < ctx.user = obj.user >
policy output < *sub_policy(child) >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output,globals()) # This loads the generated function, which should look like this:
+ exec(
+ output, globals()
+ ) # This loads the generated function, which should look like this:
"""
def sub_policy_security_check(obj, ctx):
@@ -142,10 +144,10 @@
def output_security_check(obj, ctx):
if obj.child:
- i1 = sub_policy_security_check(obj.child, ctx)
- else:
- i1 = True
- return i1
+ i1 = sub_policy_security_check(obj.child, ctx)
+ else:
+ i1 = True
+ return i1
"""
obj = FakeObject()
@@ -158,23 +160,21 @@
self.assertTrue(verdict)
def test_bin(self):
- xproto = \
-"""
+ xproto = """
policy output < ctx.is_admin = True | obj.empty = True>
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
- def output_security_check(obj, ctx):
- i2 = (ctx.is_admin == True)
- i3 = (obj.empty == True)
- i1 = (i2 or i3)
- return i1
+ def output_security_check(obj, ctx):
+ i2 = (ctx.is_admin == True)
+ i3 = (obj.empty == True)
+ i1 = (i2 or i3)
+ return i1
"""
obj = FakeObject()
@@ -187,35 +187,30 @@
self.assertTrue(verdict)
-
def test_exists(self):
- xproto = \
-"""
+ xproto = """
policy output < exists Privilege: Privilege.object_id = obj.id >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
- def output_security_check(obj, ctx):
- i1 = Privilege.objects.filter(object_id=obj.id)
- return i1
+ def output_security_check(obj, ctx):
+ i1 = Privilege.objects.filter(object_id=obj.id)
+ return i1
"""
self.assertTrue(output_security_check is not None)
-
+
def test_python(self):
- xproto = \
-"""
+ xproto = """
policy output < {{ "jack" in ["the", "box"] }} = False >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def output_security_check(obj, ctx):
@@ -228,13 +223,11 @@
def test_forall(self):
# This one we only parse
- xproto = \
-"""
+ xproto = """
policy output < forall Credential: Credential.obj_id = obj_id >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
"""
@@ -245,5 +238,6 @@
"""
exec(output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
diff --git a/lib/xos-genx/xos-genx-tests/test_general_validation.py b/lib/xos-genx/xos-genx-tests/test_general_validation.py
index 048167a..0e2a785 100644
--- a/lib/xos-genx/xos-genx-tests/test_general_validation.py
+++ b/lib/xos-genx/xos-genx-tests/test_general_validation.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -22,33 +21,38 @@
"""The function below is for eliminating warnings arising due to the missing policy_output_validator,
which is generated and loaded dynamically.
"""
+
+
def policy_output_validator(x, y):
raise Exception("Validator not generated. Test failed.")
return False
+
"""
-The tests below use the Python code target to generate
+The tests below use the Python code target to generate
Python validation policies, set up an appropriate environment and execute the Python.
"""
+
+
class XProtoGeneralValidationTest(unittest.TestCase):
def setUp(self):
- self.target = XProtoTestHelpers.write_tmp_target("""
+ self.target = XProtoTestHelpers.write_tmp_target(
+ """
{% for name, policy in proto.policies.items() %}
{{ xproto_fol_to_python_validator(name, policy, None, 'Necessary Failure') }}
{% endfor %}
-""")
+"""
+ )
def test_constant(self):
- xproto = \
-"""
+ xproto = """
policy output < False >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -58,20 +62,18 @@
"""
with self.assertRaises(Exception):
- policy_output_validator({}, {})
-
+ policy_output_validator({}, {})
+
def test_equal(self):
- xproto = \
-"""
+ xproto = """
policy output < not (ctx.user = obj.user) >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -87,20 +89,18 @@
ctx.user = 1
with self.assertRaises(Exception):
- policy_output_validator(obj, ctx)
+ policy_output_validator(obj, ctx)
def test_equal(self):
- xproto = \
-"""
+ xproto = """
policy output < not (ctx.user = obj.user) >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -116,11 +116,10 @@
ctx.user = 1
with self.assertRaises(Exception):
- policy_output_validator(obj, ctx)
+ policy_output_validator(obj, ctx)
def test_bin(self):
- xproto = \
-"""
+ xproto = """
policy output < (ctx.is_admin = True | obj.empty = True) | False>
"""
@@ -129,7 +128,7 @@
args.target = self.target
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -149,17 +148,14 @@
with self.assertRaises(Exception):
verdict = policy_output_validator(obj, ctx)
-
def test_exists(self):
- xproto = \
-"""
+ xproto = """
policy output < exists Privilege: Privilege.object_id = obj.id >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -169,16 +165,14 @@
"""
self.assertTrue(policy_output_validator is not None)
-
+
def test_python(self):
- xproto = \
-"""
+ xproto = """
policy output < {{ "jack" in ["the", "box"] }} = True >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -192,18 +186,18 @@
self.assertTrue(policy_output_validator({}, {}) is True)
def test_call_policy(self):
- xproto = \
-"""
+ xproto = """
policy sub_policy < ctx.user = obj.user >
policy output < *sub_policy(child) >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
- exec(output,globals()) # This loads the generated function, which should look like this:
+ exec(
+ output, globals()
+ ) # This loads the generated function, which should look like this:
"""
def policy_sub_policy_validator(obj, ctx):
@@ -229,13 +223,11 @@
def test_forall(self):
# This one we only parse
- xproto = \
-"""
+ xproto = """
policy output < forall Credential: Credential.obj_id = obj_id >
"""
- args = XOSProcessorArgs(inputs = xproto,
- target = self.target)
+ args = XOSProcessorArgs(inputs=xproto, target=self.target)
output = XOSProcessor.process(args)
@@ -246,7 +238,8 @@
return i1
"""
- self.assertIn('policy_output_validator', output)
+ self.assertIn("policy_output_validator", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
diff --git a/lib/xos-genx/xos-genx-tests/test_generator.py b/lib/xos-genx/xos-genx-tests/test_generator.py
index 3daa594..1de6bd8 100644
--- a/lib/xos-genx/xos-genx-tests/test_generator.py
+++ b/lib/xos-genx/xos-genx-tests/test_generator.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -30,38 +29,64 @@
description: "Help Files"
"""
-BASE_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/base.xproto")
-TEST_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/test.xproto")
-FIELDTEST_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/fieldtest.xproto")
-REVERSEFIELDTEST_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/reversefieldtest.xproto")
-FILTERTEST_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/filtertest.xproto")
-SKIP_DJANGO_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/skip_django.xproto")
-VROUTER_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/vrouterport.xproto")
-TEST_TARGET = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xtarget/test.xtarget")
-FIELDTEST_TARGET = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xtarget/fieldtest.xtarget")
-FILTERTEST_TARGET = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xtarget/filtertest.xtarget")
-SPLIT_TARGET = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xtarget/split.xtarget")
+BASE_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/base.xproto"
+)
+TEST_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/test.xproto"
+)
+FIELDTEST_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/fieldtest.xproto"
+)
+REVERSEFIELDTEST_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/reversefieldtest.xproto"
+)
+FILTERTEST_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/filtertest.xproto"
+)
+SKIP_DJANGO_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/skip_django.xproto"
+)
+VROUTER_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/vrouterport.xproto"
+)
+TEST_TARGET = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xtarget/test.xtarget"
+)
+FIELDTEST_TARGET = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xtarget/fieldtest.xtarget"
+)
+FILTERTEST_TARGET = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xtarget/filtertest.xtarget"
+)
+SPLIT_TARGET = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xtarget/split.xtarget"
+)
TEST_ATTICS = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/attics/")
+
class XOSProcessorTest(unittest.TestCase):
"""
Testing the XOS Generative Toolchain
"""
def setUp(self):
- os.chdir(os.path.join(os.path.abspath(os.path.dirname(os.path.realpath(__file__))), ".."))
+ os.chdir(
+ os.path.join(
+ os.path.abspath(os.path.dirname(os.path.realpath(__file__))), ".."
+ )
+ )
filesToRemove = [f for f in os.listdir(OUTPUT_DIR)]
for f in filesToRemove:
- if not f.startswith('.'):
- os.remove(OUTPUT_DIR + '/' + f)
+ if not f.startswith("."):
+ os.remove(OUTPUT_DIR + "/" + f)
def test_generator_custom_target_from_file(self):
"""
[XOS-GenX] Generate output from base.xproto
"""
- args = XOSProcessorArgs(files = [TEST_XPROTO],
- target = TEST_TARGET)
+ args = XOSProcessorArgs(files=[TEST_XPROTO], target=TEST_TARGET)
output = XOSProcessor.process(args)
self.assertEqual(output, TEST_EXPECTED_OUTPUT)
@@ -69,8 +94,7 @@
"""
[XOS-GenX] Generate output from base.xproto
"""
- args = XOSProcessorArgs(inputs = open(TEST_XPROTO).read(),
- target = TEST_TARGET)
+ args = XOSProcessorArgs(inputs=open(TEST_XPROTO).read(), target=TEST_TARGET)
output = XOSProcessor.process(args)
self.assertEqual(output, TEST_EXPECTED_OUTPUT)
@@ -78,73 +102,79 @@
"""
[XOS-GenX] Generate django output from test.xproto
"""
- args = XOSProcessorArgs(files = [TEST_XPROTO, VROUTER_XPROTO],
- target = 'django.xtarget',
- attic = TEST_ATTICS,
- output = OUTPUT_DIR,
- dest_extension = 'py',
- write_to_file = 'model')
+ args = XOSProcessorArgs(
+ files=[TEST_XPROTO, VROUTER_XPROTO],
+ target="django.xtarget",
+ attic=TEST_ATTICS,
+ output=OUTPUT_DIR,
+ dest_extension="py",
+ write_to_file="model",
+ )
output = XOSProcessor.process(args)
# xosmodel has custom header attic
- self.assertIn('from xosmodel_header import *', output['XOSModel'])
- self.assertIn('class XOSModel(XOSBase):', output['XOSModel'])
+ self.assertIn("from xosmodel_header import *", output["XOSModel"])
+ self.assertIn("class XOSModel(XOSBase):", output["XOSModel"])
# vrouter port use the default header
- self.assertIn('header import *', output['VRouterPort'])
- self.assertIn('class VRouterPort(XOSBase):', output['VRouterPort'])
+ self.assertIn("header import *", output["VRouterPort"])
+ self.assertIn("class VRouterPort(XOSBase):", output["VRouterPort"])
- #verify files
- xosmodel = OUTPUT_DIR + '/xosmodel.py'
+ # verify files
+ xosmodel = OUTPUT_DIR + "/xosmodel.py"
self.assertTrue(os.path.isfile(xosmodel))
xmf = open(xosmodel).read()
- self.assertIn('from xosmodel_header import *', xmf)
- self.assertIn('class XOSModel(XOSBase):', xmf)
+ self.assertIn("from xosmodel_header import *", xmf)
+ self.assertIn("class XOSModel(XOSBase):", xmf)
- vrouterport = OUTPUT_DIR + '/vrouterport.py'
+ vrouterport = OUTPUT_DIR + "/vrouterport.py"
self.assertTrue(os.path.isfile(vrouterport))
vrpf = open(vrouterport).read()
- self.assertIn('header import *', vrpf)
- self.assertIn('class VRouterPort(XOSBase):', vrpf)
+ self.assertIn("header import *", vrpf)
+ self.assertIn("class VRouterPort(XOSBase):", vrpf)
def test_django_with_base(self):
- args = XOSProcessorArgs(files = [TEST_XPROTO, BASE_XPROTO],
- target = 'django.xtarget',
- attic = TEST_ATTICS,
- output = OUTPUT_DIR,
- dest_extension = 'py',
- write_to_file = 'model')
+ args = XOSProcessorArgs(
+ files=[TEST_XPROTO, BASE_XPROTO],
+ target="django.xtarget",
+ attic=TEST_ATTICS,
+ output=OUTPUT_DIR,
+ dest_extension="py",
+ write_to_file="model",
+ )
output = XOSProcessor.process(args)
# verify files
- xosmodel = OUTPUT_DIR + '/xosmodel.py'
+ xosmodel = OUTPUT_DIR + "/xosmodel.py"
self.assertTrue(os.path.isfile(xosmodel))
xmf = open(xosmodel).read()
- self.assertIn('from xosmodel_header import *', xmf)
- self.assertIn('class XOSModel(XOSBase):', xmf)
+ self.assertIn("from xosmodel_header import *", xmf)
+ self.assertIn("class XOSModel(XOSBase):", xmf)
- xosbase = OUTPUT_DIR + '/xosbase.py'
+ xosbase = OUTPUT_DIR + "/xosbase.py"
self.assertTrue(os.path.isfile(xosbase))
xbf = open(xosbase).read()
- self.assertIn('header import *', xbf)
- self.assertIn('class XOSBase(models.Model, PlModelMixIn):', xbf)
+ self.assertIn("header import *", xbf)
+ self.assertIn("class XOSBase(models.Model, PlModelMixIn):", xbf)
def test_write_multiple_files(self):
"""
[XOS-GenX] read multiple models as input, print one file per model
"""
- args = XOSProcessorArgs(files = [TEST_XPROTO, VROUTER_XPROTO],
- target = TEST_TARGET,
- output = OUTPUT_DIR,
- dest_extension = 'txt',
- write_to_file = 'model')
+ args = XOSProcessorArgs(
+ files=[TEST_XPROTO, VROUTER_XPROTO],
+ target=TEST_TARGET,
+ output=OUTPUT_DIR,
+ dest_extension="txt",
+ write_to_file="model",
+ )
XOSProcessor.process(args)
- generated_files = [f for f in os.listdir(OUTPUT_DIR) if not f.startswith('.')]
+ generated_files = [f for f in os.listdir(OUTPUT_DIR) if not f.startswith(".")]
self.assertEqual(len(generated_files), 2)
- xosmodel = open(os.path.join(OUTPUT_DIR, 'xosmodel.txt'), "r").read()
- vrouterport = open(os.path.join(OUTPUT_DIR, 'vrouterport.txt'), "r").read()
+ xosmodel = open(os.path.join(OUTPUT_DIR, "xosmodel.txt"), "r").read()
+ vrouterport = open(os.path.join(OUTPUT_DIR, "vrouterport.txt"), "r").read()
self.assertIn("name: XOSModel", xosmodel)
self.assertIn("name: VRouterPort", vrouterport)
@@ -153,58 +183,63 @@
"""
[XOS-GenX] read multiple models as input, print separate files based on +++
"""
- args = XOSProcessorArgs(files = [TEST_XPROTO, VROUTER_XPROTO],
- target = SPLIT_TARGET,
- output = OUTPUT_DIR,
- write_to_file = 'target')
+ args = XOSProcessorArgs(
+ files=[TEST_XPROTO, VROUTER_XPROTO],
+ target=SPLIT_TARGET,
+ output=OUTPUT_DIR,
+ write_to_file="target",
+ )
XOSProcessor.process(args)
- generated_files = [f for f in os.listdir(OUTPUT_DIR) if not f.startswith('.')]
+ generated_files = [f for f in os.listdir(OUTPUT_DIR) if not f.startswith(".")]
self.assertEqual(len(generated_files), 2)
- xosmodel = open(os.path.join(OUTPUT_DIR, 'xosmodel.txt'), "r").read()
- vrouterport = open(os.path.join(OUTPUT_DIR, 'vrouterport.txt'), "r").read()
+ xosmodel = open(os.path.join(OUTPUT_DIR, "xosmodel.txt"), "r").read()
+ vrouterport = open(os.path.join(OUTPUT_DIR, "vrouterport.txt"), "r").read()
self.assertIn("name: XOSModel", xosmodel)
self.assertIn("name: VRouterPort", vrouterport)
def test_skip_django(self):
- args = XOSProcessorArgs(files = [SKIP_DJANGO_XPROTO],
- target = 'django.xtarget',
- output = OUTPUT_DIR,
- dest_extension = 'py',
- write_to_file = 'model')
+ args = XOSProcessorArgs(
+ files=[SKIP_DJANGO_XPROTO],
+ target="django.xtarget",
+ output=OUTPUT_DIR,
+ dest_extension="py",
+ write_to_file="model",
+ )
output = XOSProcessor.process(args)
# should not print a file if options.skip_django = True
- file = OUTPUT_DIR + '/user.py'
+ file = OUTPUT_DIR + "/user.py"
self.assertFalse(os.path.isfile(file))
def test_service_order(self):
- args = XOSProcessorArgs(files = [BASE_XPROTO, TEST_XPROTO, VROUTER_XPROTO],
- target = 'service.xtarget',
- output = OUTPUT_DIR,
- write_to_file = 'target')
+ args = XOSProcessorArgs(
+ files=[BASE_XPROTO, TEST_XPROTO, VROUTER_XPROTO],
+ target="service.xtarget",
+ output=OUTPUT_DIR,
+ write_to_file="target",
+ )
output = XOSProcessor.process(args)
- model = OUTPUT_DIR + '/models.py'
+ model = OUTPUT_DIR + "/models.py"
self.assertTrue(os.path.isfile(model))
line_num = 0
for line in open(model).readlines():
line_num += 1
- if line.find('class XOSBase(models.Model, PlModelMixIn):') >= 0:
+ if line.find("class XOSBase(models.Model, PlModelMixIn):") >= 0:
base_line = line_num
- if line.find('XOSModel(XOSBase):') >= 0:
+ if line.find("XOSModel(XOSBase):") >= 0:
xosmodel_line = line_num
- if line.find('class VRouterPort(XOSBase):') >= 0:
+ if line.find("class VRouterPort(XOSBase):") >= 0:
vrouter_line = line_num
self.assertLess(base_line, xosmodel_line)
self.assertLess(xosmodel_line, vrouter_line)
def test_field_numbers(self):
- args = XOSProcessorArgs(files = [FIELDTEST_XPROTO],
- target = FIELDTEST_TARGET)
+ args = XOSProcessorArgs(files=[FIELDTEST_XPROTO], target=FIELDTEST_TARGET)
output = XOSProcessor.process(args)
def _assert_field(modelname, fieldname, id):
@@ -224,8 +259,9 @@
_assert_field("Slice", "site", 102)
def test_field_numbers(self):
- args = XOSProcessorArgs(files = [REVERSEFIELDTEST_XPROTO],
- target = FIELDTEST_TARGET)
+ args = XOSProcessorArgs(
+ files=[REVERSEFIELDTEST_XPROTO], target=FIELDTEST_TARGET
+ )
output = XOSProcessor.process(args)
def _assert_field(modelname, fieldname, id):
@@ -250,32 +286,31 @@
def test_unfiltered(self):
""" With no include_* args, should get all models """
- args = XOSProcessorArgs(files = [FILTERTEST_XPROTO],
- target = FILTERTEST_TARGET)
+ args = XOSProcessorArgs(files=[FILTERTEST_XPROTO], target=FILTERTEST_TARGET)
output = XOSProcessor.process(args)
self.assertEqual(output, "Model1,Model2,Model3,")
def test_filter_models(self):
""" Should only get models specified by include_models """
- args = XOSProcessorArgs(files = [FILTERTEST_XPROTO],
- target = FILTERTEST_TARGET,
- include_models = ["Model1", "Model3"])
+ args = XOSProcessorArgs(
+ files=[FILTERTEST_XPROTO],
+ target=FILTERTEST_TARGET,
+ include_models=["Model1", "Model3"],
+ )
output = XOSProcessor.process(args)
self.assertEqual(output, "Model1,Model3,")
def test_filter_apps(self):
""" Should only get models whose apps are specified by include_apps """
- args = XOSProcessorArgs(files = [FILTERTEST_XPROTO],
- target = FILTERTEST_TARGET,
- include_apps = ["core"])
+ args = XOSProcessorArgs(
+ files=[FILTERTEST_XPROTO], target=FILTERTEST_TARGET, include_apps=["core"]
+ )
output = XOSProcessor.process(args)
self.assertEqual(output, "Model1,Model2,")
-
-
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
diff --git a/lib/xos-genx/xos-genx-tests/test_graph.py b/lib/xos-genx/xos-genx-tests/test_graph.py
index fda3d99..c6cfea7 100644
--- a/lib/xos-genx/xos-genx-tests/test_graph.py
+++ b/lib/xos-genx/xos-genx-tests/test_graph.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,10 +17,11 @@
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import XProtoTestHelpers
+
class XProtoGraphTests(unittest.TestCase):
def test_cross_model(self):
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{% for m in proto.messages %}
{{ m.name }} {
{%- for l in m.links %}
@@ -34,10 +34,10 @@
{% endfor %}
}
{% endfor %}
-""")
-
- proto = \
"""
+ )
+
+ proto = """
message Port (PlCoreBase,ParameterMixin){
required manytoone network->Network:links = 1 [db_index = True, null = False, blank = False];
optional manytoone instance->Instance:ports = 2 [db_index = True, null = True, blank = True];
@@ -116,12 +116,13 @@
args.inputs = proto
args.target = target
output = XOSProcessor.process(args)
- num_semis = output.count(';')
- self.assertGreater(num_semis, 3) # 3 is the number of links, each of which contains at least one field
+ num_semis = output.count(";")
+ self.assertGreater(
+ num_semis, 3
+ ) # 3 is the number of links, each of which contains at least one field
def test_base_class_fields(self):
- target = \
-"""
+ target = """
{% for m in proto.messages %}
{{ m.name }} {
{%- for l in m.links %}
@@ -137,8 +138,7 @@
"""
xtarget = XProtoTestHelpers.write_tmp_target(target)
- proto = \
-"""
+ proto = """
message Port (PlCoreBase,ParameterMixin){
required manytoone network->Network:links = 1 [db_index = True, null = False, blank = False];
optional manytoone instance->Instance:ports = 2 [db_index = True, null = True, blank = True];
@@ -218,19 +218,17 @@
args.target = xtarget
output = XOSProcessor.process(args)
- num_semis = output.count(';')
+ num_semis = output.count(";")
self.assertGreater(num_semis, 3)
def test_from_base(self):
- target = \
-"""
+ target = """
{% for f in xproto_base_fields(proto.messages.3, proto.message_table) %}
{{ f.type }} {{ f.name }};
{% endfor %}
"""
xtarget = XProtoTestHelpers.write_tmp_target(target)
- proto = \
-"""
+ proto = """
message Port (PlCoreBase,ParameterMixin){
required string easter_egg = 1;
required manytoone network->Network:links = 1 [db_index = True, null = False, blank = False];
@@ -309,9 +307,8 @@
args.inputs = proto
args.target = xtarget
output = XOSProcessor.process(args)
- self.assertIn('easter_egg', output)
+ self.assertIn("easter_egg", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_jinja2_base.py b/lib/xos-genx/xos-genx-tests/test_jinja2_base.py
index 4f26ac9..859d640 100644
--- a/lib/xos-genx/xos-genx-tests/test_jinja2_base.py
+++ b/lib/xos-genx/xos-genx-tests/test_jinja2_base.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -29,6 +28,7 @@
f["options"]["plural"] = plural
return f
+
class Jinja2BaseTests(unittest.TestCase):
def test_xproto_is_true(self):
self.assertTrue(xproto_is_true(True))
@@ -68,14 +68,16 @@
self.assertEqual(xproto_singularize_pluralize(_field("sheep")), "sheep")
self.assertEqual(xproto_singularize_pluralize(_field("slices")), "slices")
self.assertEqual(xproto_singularize_pluralize(_field("networks")), "networks")
- self.assertEqual(xproto_singularize_pluralize(_field("omf_friendlies")), "omf_friendlies")
+ self.assertEqual(
+ xproto_singularize_pluralize(_field("omf_friendlies")), "omf_friendlies"
+ )
# invalid words, should usually return <word>-es
self.assertEqual(xproto_singularize_pluralize(_field("xxx")), "xxxes")
# if a field option is set, use that
- self.assertEqual(xproto_singularize(_field("sheep", singular="turtle")), "turtle")
+ self.assertEqual(
+ xproto_singularize(_field("sheep", singular="turtle")), "turtle"
+ )
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_jinja2_django.py b/lib/xos-genx/xos-genx-tests/test_jinja2_django.py
index ab47443..108ae4e 100644
--- a/lib/xos-genx/xos-genx-tests/test_jinja2_django.py
+++ b/lib/xos-genx/xos-genx-tests/test_jinja2_django.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,103 +16,70 @@
import unittest
from xosgenx.jinja2_extensions.django import *
+
class Jinja2BaseTests(unittest.TestCase):
def test_xproto_optioned_fields_to_list(self):
fields = [
- {
- 'name': 'has_feedback_1',
- 'options': {
- 'feedback_state': 'True',
- }
- },
- {
- 'name': 'has_feedback_2',
- 'options': {
- 'feedback_state': 'True',
- }
- },
- {
- 'name': 'no_feedback',
- 'options': {
- 'feedback_state': 'False',
- }
- }
+ {"name": "has_feedback_1", "options": {"feedback_state": "True"}},
+ {"name": "has_feedback_2", "options": {"feedback_state": "True"}},
+ {"name": "no_feedback", "options": {"feedback_state": "False"}},
]
- res = xproto_optioned_fields_to_list(fields, 'feedback_state', 'True')
+ res = xproto_optioned_fields_to_list(fields, "feedback_state", "True")
self.assertEqual(res, ["has_feedback_1", "has_feedback_2"])
def test_xproto_required_to_django(self):
- field = {
- 'name': 'foo',
- 'options': {
- 'modifier': 'required'
- }
- }
+ field = {"name": "foo", "options": {"modifier": "required"}}
res = map_xproto_to_django(field)
- self.assertEqual(res, {'blank': False, 'null': False})
+ self.assertEqual(res, {"blank": False, "null": False})
def test_xproto_optional_to_django(self):
- field = {
- 'name': 'foo',
- 'options': {
- 'modifier': 'optional'
- }
- }
+ field = {"name": "foo", "options": {"modifier": "optional"}}
res = map_xproto_to_django(field)
- self.assertEqual(res, {'blank': True, 'null': True})
-
+ self.assertEqual(res, {"blank": True, "null": True})
def test_map_xproto_to_django(self):
options = {
- 'help_text': 'bar',
- 'default': 'default_value',
- 'null': True,
- 'db_index': False,
- 'blank': False,
- 'min_value': 16,
- 'max_value': 16
+ "help_text": "bar",
+ "default": "default_value",
+ "null": True,
+ "db_index": False,
+ "blank": False,
+ "min_value": 16,
+ "max_value": 16,
}
- field = {
- 'name': 'foo',
- 'options': options
- }
+ field = {"name": "foo", "options": options}
res = map_xproto_to_django(field)
self.assertEqual(res, options)
def test_format_options_string(self):
- options = {
- 'null': True,
- 'min_value': 16,
- 'max_value': 16
- }
+ options = {"null": True, "min_value": 16, "max_value": 16}
res = format_options_string(options)
- self.assertEqual(res, "null = True, validators=[MaxValueValidator(16), MinValueValidator(16)]")
+ self.assertEqual(
+ res,
+ "null = True, validators=[MaxValueValidator(16), MinValueValidator(16)]",
+ )
- options = {
- 'min_value': 16,
- 'max_value': 16
- }
+ options = {"min_value": 16, "max_value": 16}
res = format_options_string(options)
- self.assertEqual(res, "validators=[MaxValueValidator(16), MinValueValidator(16)]")
+ self.assertEqual(
+ res, "validators=[MaxValueValidator(16), MinValueValidator(16)]"
+ )
- options = {
- 'null': True,
- }
+ options = {"null": True}
res = format_options_string(options)
self.assertEqual(res, "null = True")
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_optimize.py b/lib/xos-genx/xos-genx-tests/test_optimize.py
index e31deb8..c86b736 100644
--- a/lib/xos-genx/xos-genx-tests/test_optimize.py
+++ b/lib/xos-genx/xos-genx-tests/test_optimize.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -17,81 +16,120 @@
import unittest
from xosgenx.jinja2_extensions.fol2 import FOL2Python
+
class XProtoOptimizeTest(unittest.TestCase):
def setUp(self):
self.f2p = FOL2Python()
- self.maxDiff=None
+ self.maxDiff = None
def test_constant(self):
- input = 'True'
+ input = "True"
output = self.f2p.hoist_outer(input)
self.assertEqual(output, input)
def test_exists(self):
- input = {'exists': ['X',{'|':['X.foo','y']}]}
+ input = {"exists": ["X", {"|": ["X.foo", "y"]}]}
output = self.f2p.hoist_outer(input)
- expected = {'|': ['y', {'&': [{'not': 'y'}, {'exists': ['X', 'X.foo']}]}]}
+ expected = {"|": ["y", {"&": [{"not": "y"}, {"exists": ["X", "X.foo"]}]}]}
self.assertEqual(output, expected)
-
+
def test_exists_implies(self):
- input = {'exists': ['Foo', {'&': [{'=': ('Foo.a', '1')}, {'->': ['write_access', {'=': ('Foo.b', '1')}]}]}]}
+ input = {
+ "exists": [
+ "Foo",
+ {
+ "&": [
+ {"=": ("Foo.a", "1")},
+ {"->": ["write_access", {"=": ("Foo.b", "1")}]},
+ ]
+ },
+ ]
+ }
output = self.f2p.hoist_outer(input)
- expected = {'|': [{'&': ['write_access', {'exists': ['Foo', {'&': [{'=': ['Foo.a', '1']}, {'=': ['Foo.b', '1']}]}]}]}, {'&': [{'not': 'write_access'}, {'exists': ['Foo', {'=': ['Foo.a', '1']}]}]}]}
+ expected = {
+ "|": [
+ {
+ "&": [
+ "write_access",
+ {
+ "exists": [
+ "Foo",
+ {"&": [{"=": ["Foo.a", "1"]}, {"=": ["Foo.b", "1"]}]},
+ ]
+ },
+ ]
+ },
+ {
+ "&": [
+ {"not": "write_access"},
+ {"exists": ["Foo", {"=": ["Foo.a", "1"]}]},
+ ]
+ },
+ ]
+ }
self.assertEqual(output, expected)
def test_forall(self):
- input = {'forall': ['X',{'|':['X.foo','y']}]}
+ input = {"forall": ["X", {"|": ["X.foo", "y"]}]}
output = self.f2p.hoist_outer(input)
- expected = {'|': ['y', {'&': [{'not': 'y'}, {'forall': ['X', 'X.foo']}]}]}
+ expected = {"|": ["y", {"&": [{"not": "y"}, {"forall": ["X", "X.foo"]}]}]}
self.assertEqual(output, expected)
def test_exists_embedded(self):
- input = {'&':['True',{'exists': ['X',{'|':['X.foo','y']}]}]}
+ input = {"&": ["True", {"exists": ["X", {"|": ["X.foo", "y"]}]}]}
output = self.f2p.hoist_outer(input)
- expected = {'|': ['y', {'&': [{'not': 'y'}, {'exists': ['X', 'X.foo']}]}]}
+ expected = {"|": ["y", {"&": [{"not": "y"}, {"exists": ["X", "X.foo"]}]}]}
self.assertEqual(output, expected)
-
+
def test_exists_equals(self):
- input = {'&':['True',{'exists': ['X',{'|':['X.foo',{'=':['y','z']}]}]}]}
+ input = {"&": ["True", {"exists": ["X", {"|": ["X.foo", {"=": ["y", "z"]}]}]}]}
output = self.f2p.hoist_outer(input)
- expected = {'|': [{'=': ['y', 'z']}, {'&': [{'not': {'=': ['y', 'z']}}, {'exists': ['X', 'X.foo']}]}]}
+ expected = {
+ "|": [
+ {"=": ["y", "z"]},
+ {"&": [{"not": {"=": ["y", "z"]}}, {"exists": ["X", "X.foo"]}]},
+ ]
+ }
self.assertEqual(output, expected)
def test_exists_nested_constant(self):
- input = {'&':['True',{'exists': ['X',{'|':['y',{'=':['y','X.foo']}]}]}]}
+ input = {"&": ["True", {"exists": ["X", {"|": ["y", {"=": ["y", "X.foo"]}]}]}]}
output = self.f2p.hoist_outer(input)
- expected = {'|': ['y', {'&': [{'not': 'y'}, {'exists': ['X', {'=': ['False', 'X.foo']}]}]}]}
+ expected = {
+ "|": [
+ "y",
+ {"&": [{"not": "y"}, {"exists": ["X", {"=": ["False", "X.foo"]}]}]},
+ ]
+ }
self.assertEqual(output, expected)
def test_exists_nested(self):
- input = {'exists': ['X',{'exists':['Y',{'=':['Y.foo','X.foo']}]}]}
+ input = {"exists": ["X", {"exists": ["Y", {"=": ["Y.foo", "X.foo"]}]}]}
output = self.f2p.hoist_outer(input)
expected = input
self.assertEqual(input, output)
def test_exists_nested2(self):
- input = {'exists': ['X',{'exists':['Y',{'=':['Z','Y']}]}]}
+ input = {"exists": ["X", {"exists": ["Y", {"=": ["Z", "Y"]}]}]}
output = self.f2p.hoist_outer(input)
- expected = {'exists': ['Y', {'=': ['Z', 'Y']}]}
+ expected = {"exists": ["Y", {"=": ["Z", "Y"]}]}
self.assertEqual(output, expected)
def test_exists_nested3(self):
- input = {'exists': ['X',{'exists':['Y',{'=':['Z','X']}]}]}
+ input = {"exists": ["X", {"exists": ["Y", {"=": ["Z", "X"]}]}]}
output = self.f2p.hoist_outer(input)
- expected = {'exists': ['X', {'=': ['Z', 'X']}]}
+ expected = {"exists": ["X", {"=": ["Z", "X"]}]}
self.assertEqual(output, expected)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_package.py b/lib/xos-genx/xos-genx-tests/test_package.py
index f1cf426..03911bd 100644
--- a/lib/xos-genx/xos-genx-tests/test_package.py
+++ b/lib/xos-genx/xos-genx-tests/test_package.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -19,18 +18,19 @@
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import XProtoTestHelpers
+
class XProtoPackageTest(unittest.TestCase):
def test_package_fqn(self):
args = XOSProcessorArgs()
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{% for m in proto.messages %}
{{ m.name }},{{ m.package }},{{ m.fqn }}
{% endfor %}
-""")
-
- xproto =\
"""
+ )
+
+ xproto = """
package xos.core;
message Port (PlCoreBase,ParameterMixin) {
@@ -48,11 +48,11 @@
output = XOSProcessor.process(args)
- self.assertIn('Port,xos.core,xos.core.Port', output)
+ self.assertIn("Port,xos.core,xos.core.Port", output)
def test_cross_model(self):
- target = XProtoTestHelpers.write_tmp_target( \
-"""
+ target = XProtoTestHelpers.write_tmp_target(
+ """
{% for m in proto.messages %}
{{ m.fqn }} {
{%- for l in m.links %}
@@ -75,10 +75,10 @@
{% endfor %}
}
{% endfor %}
-""")
-
- xproto = \
"""
+ )
+
+ xproto = """
package xos.network;
message Port (PlCoreBase,ParameterMixin){
@@ -164,13 +164,17 @@
args.target = target
output = XOSProcessor.process(args)
- self.assertIn('numberCores', output) # Instance showed up via cross-package call
- self.assertIn('ip;', output) # Network showed up via cross-package call
- self.assertIn('max_instances', output) # Slice showed up via implicit in-package call
+ self.assertIn(
+ "numberCores", output
+ ) # Instance showed up via cross-package call
+ self.assertIn("ip;", output) # Network showed up via cross-package call
+ self.assertIn(
+ "max_instances", output
+ ) # Slice showed up via implicit in-package call
def test_base_class_fields(self):
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{% for m in proto.messages %}
{{ m.name }} {
{%- for b in m.bases %}
@@ -183,10 +187,10 @@
{% endfor %}
}
{% endfor %}
-""")
-
- xproto =\
"""
+ )
+
+ xproto = """
package xos.network;
message Port (PlCoreBase,ParameterMixin){
@@ -225,18 +229,18 @@
args.target = target
output = XOSProcessor.process(args)
- self.assertIn('xos_created', output)
+ self.assertIn("xos_created", output)
def test_from_base(self):
- target = XProtoTestHelpers.write_tmp_target( \
-"""
+ target = XProtoTestHelpers.write_tmp_target(
+ """
{% for f in xproto_base_fields(proto.messages.3, proto.message_table) %}
{{ f.type }} {{ f.name }};
{% endfor %}
-""")
-
- xproto =\
"""
+ )
+
+ xproto = """
option app_name = "firstapp";
message Port (PlCoreBase,ParameterMixin){
@@ -326,21 +330,21 @@
args.target = target
output = XOSProcessor.process(args)
- self.assertIn('easter_egg', output)
+ self.assertIn("easter_egg", output)
def test_model_options(self):
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
Options:
{{ proto.options }}
{% for m in proto.messages %}
{{ m.options.app_name }}
{% endfor %}
-""")
-
- xproto =\
"""
+ )
+
+ xproto = """
option app_name = "firstapp";
message Port (PlCoreBase,ParameterMixin){
@@ -426,17 +430,15 @@
required manytomany tags->Tag = 18 [db_index = False, null = False, blank = True];
}
"""
-
+
args = XOSProcessorArgs()
args.inputs = xproto
args.target = target
output = XOSProcessor.process(args)
- self.assertEqual(output.count('firstapp'), 2)
- self.assertEqual(output.count('networkapp'), 2)
+ self.assertEqual(output.count("firstapp"), 2)
+ self.assertEqual(output.count("networkapp"), 2)
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_parse.py b/lib/xos-genx/xos-genx-tests/test_parse.py
index d7edcb7..8d1ccf5 100644
--- a/lib/xos-genx/xos-genx-tests/test_parse.py
+++ b/lib/xos-genx/xos-genx-tests/test_parse.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,13 +17,13 @@
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import XProtoTestHelpers
+
class XProtoParseTests(unittest.TestCase):
def test_global_options(self):
xtarget = XProtoTestHelpers.write_tmp_target("{{ options }}")
- xproto = \
-"""
+ xproto = """
option kind = "vsg";
option verbose_name = "vSG Service";
"""
@@ -38,8 +37,7 @@
def test_basic_proto(self):
xtarget = XProtoTestHelpers.write_tmp_target("{{ proto }}")
- xproto = \
-"""
+ xproto = """
message Person {
required string name = 1;
required int32 id = 2; // Unique ID number for this person.
@@ -66,8 +64,7 @@
def test_link_extensions(self):
xtarget = XProtoTestHelpers.write_tmp_target("{{ proto.messages.0.links }}")
- xproto = \
-"""
+ xproto = """
message links {
required manytoone vrouter_service->VRouterService:device_ports = 4 [db_index = True, null = False, blank = False];
}
@@ -79,9 +76,10 @@
self.assertIn("VRouterService", output)
def test_through_extensions(self):
- xtarget = XProtoTestHelpers.write_tmp_target("{{ proto.messages.0.links.0.through }}")
- xproto = \
-"""
+ xtarget = XProtoTestHelpers.write_tmp_target(
+ "{{ proto.messages.0.links.0.through }}"
+ )
+ xproto = """
message links {
required manytomany vrouter_service->VRouterService/ServiceProxy:device_ports = 4 [db_index = True, null = False, blank = False];
}
@@ -93,9 +91,10 @@
self.assertIn("ServiceProxy", output)
def test_message_options(self):
- xtarget = XProtoTestHelpers.write_tmp_target("{{ proto.messages.0.options.type }}")
- xproto = \
-"""
+ xtarget = XProtoTestHelpers.write_tmp_target(
+ "{{ proto.messages.0.options.type }}"
+ )
+ xproto = """
message link {
option type = "e1000";
}
@@ -108,8 +107,7 @@
def test_message_base(self):
xtarget = XProtoTestHelpers.write_tmp_target("{{ proto.messages.0.bases }}")
- xproto = \
-"""
+ xproto = """
message base(Base) {
}
"""
@@ -120,7 +118,6 @@
output = XOSProcessor.process(args)
self.assertIn("Base", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_policy.py b/lib/xos-genx/xos-genx-tests/test_policy.py
index d83ab6c..e8b5a76 100644
--- a/lib/xos-genx/xos-genx-tests/test_policy.py
+++ b/lib/xos-genx/xos-genx-tests/test_policy.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -24,10 +23,10 @@
into Python, set up an appropriate environment and execute the Python.
"""
+
class XProtoPolicyTest(unittest.TestCase):
def test_annotation(self):
- xproto = \
-"""
+ xproto = """
policy true_policy < True >
message always::true_policy {
@@ -45,8 +44,7 @@
self.assertIn("true_policy", output)
def test_constant(self):
- xproto = \
-"""
+ xproto = """
policy true_policy < True >
"""
@@ -56,12 +54,11 @@
args.inputs = xproto
args.target = target
- output = XOSProcessor.process(args).replace('t','T')
- self.assertTrue(eval(output))
+ output = XOSProcessor.process(args).replace("t", "T")
+ self.assertTrue(eval(output))
def test_function_term(self):
- xproto = \
-"""
+ xproto = """
policy slice_user < slice.user.compute_is_admin() >
"""
@@ -71,7 +68,7 @@
args.target = target
output = XOSProcessor.process(args)
-
+
slice = FakeObject()
slice.user = FakeObject()
slice.user.compute_is_admin = lambda: True
@@ -80,8 +77,7 @@
self.assertTrue(expr)
def test_term(self):
- xproto = \
-"""
+ xproto = """
policy slice_user < slice.user.is_admin >
"""
@@ -91,7 +87,7 @@
args.target = target
output = XOSProcessor.process(args)
-
+
slice = FakeObject()
slice.user = FakeObject()
slice.user.is_admin = True
@@ -100,8 +96,7 @@
self.assertTrue(expr)
def test_num_constant(self):
- xproto = \
-"""
+ xproto = """
policy slice_user < slice.user.age = 57 >
"""
@@ -111,7 +106,7 @@
args.target = target
output = XOSProcessor.process(args)
-
+
slice = FakeObject()
slice.user = FakeObject()
slice.user.is_admin = True
@@ -120,8 +115,7 @@
self.assertTrue(expr)
def test_string_constant(self):
- xproto = \
-"""
+ xproto = """
policy slice_user < slice.user.email = "admin@opencord.org" >
"""
@@ -131,7 +125,7 @@
args.target = target
output = XOSProcessor.process(args)
-
+
slice = FakeObject()
slice.user = FakeObject()
slice.user.is_admin = True
@@ -140,8 +134,7 @@
self.assertTrue(expr)
def test_equal(self):
- xproto = \
-"""
+ xproto = """
policy slice_user < slice.user = obj.user >
"""
@@ -151,20 +144,19 @@
args.target = target
output = XOSProcessor.process(args)
-
+
slice = FakeObject()
- slice.user = 'twin'
+ slice.user = "twin"
obj = FakeObject()
- obj.user = 'twin'
+ obj.user = "twin"
(op, operands), = eval(output).items()
- expr = op.join(operands).replace('=','==')
+ expr = op.join(operands).replace("=", "==")
self.assertTrue(eval(expr))
def test_bin(self):
- xproto = \
-"""
+ xproto = """
policy slice_admin < slice.is_admin | obj.empty >
"""
target = XProtoTestHelpers.write_tmp_target("{{ proto.policies.slice_admin }}")
@@ -180,13 +172,12 @@
obj.empty = []
(op, operands), = eval(output).items()
- expr = op.join(operands).replace('|',' or ')
+ expr = op.join(operands).replace("|", " or ")
self.assertFalse(eval(expr))
def test_implies(self):
- xproto = \
-"""
+ xproto = """
policy implies < obj.name -> obj.creator >
"""
target = XProtoTestHelpers.write_tmp_target("{{ proto.policies.implies }}")
@@ -199,17 +190,16 @@
slice = FakeObject()
slice.is_admin = False
obj = FakeObject()
- obj.name = 'Thing 1'
+ obj.name = "Thing 1"
obj.creator = None
(op, operands), = eval(output).items()
- expr = 'not ' + op.join(operands).replace('->',' or ')
+ expr = "not " + op.join(operands).replace("->", " or ")
self.assertFalse(eval(expr))
-
+
def test_exists(self):
- xproto = \
-"""
+ xproto = """
policy privilege < exists Privilege: Privilege.object_id = obj.id >
"""
@@ -219,7 +209,7 @@
args.target = target
output = XOSProcessor.process(args)
-
+
Privilege = FakeObject()
Privilege.object_id = 1
obj = FakeObject()
@@ -227,49 +217,49 @@
(op, operands), = eval(output).items()
(op2, operands2), = operands[1].items()
- expr = op2.join(operands2).replace('=','==')
+ expr = op2.join(operands2).replace("=", "==")
self.assertTrue(eval(expr))
def test_policy_function(self):
- xproto = \
-"""
+ xproto = """
policy slice_policy < exists Privilege: Privilege.object_id = obj.id >
policy network_slice_policy < *slice_policy(slice) >
"""
- target = XProtoTestHelpers.write_tmp_target("{{ proto.policies.network_slice_policy }} ")
+ target = XProtoTestHelpers.write_tmp_target(
+ "{{ proto.policies.network_slice_policy }} "
+ )
args = XOSProcessorArgs()
args.inputs = xproto
args.target = target
output = XOSProcessor.process(args)
-
+
(op, operands), = eval(output).items()
- self.assertIn('slice_policy', operands)
- self.assertIn('slice', operands)
+ self.assertIn("slice_policy", operands)
+ self.assertIn("slice", operands)
def test_policy_missing_function(self):
- xproto = \
-"""
+ xproto = """
policy slice_policy < exists Privilege: Privilege.object_id = obj.id >
policy network_slice_policy < *slice_policyX(slice) >
"""
- target = XProtoTestHelpers.write_tmp_target("{{ proto.policies.network_slice_policy }} ")
+ target = XProtoTestHelpers.write_tmp_target(
+ "{{ proto.policies.network_slice_policy }} "
+ )
args = XOSProcessorArgs()
args.inputs = xproto
args.target = target
with self.assertRaises(Exception):
output = XOSProcessor.process(args)
-
def test_forall(self):
# This one we only parse
- xproto = \
-"""
+ xproto = """
policy instance < forall Instance: exists Credential: Credential.obj_id = Instance.obj_id >
"""
@@ -282,10 +272,8 @@
output = XOSProcessor.process(args)
(op, operands), = eval(output).items()
- self.assertEqual(op,'forall')
+ self.assertEqual(op, "forall")
-if __name__ == '__main__':
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_pure_proto.py b/lib/xos-genx/xos-genx-tests/test_pure_proto.py
index ade4957..c4f680d 100644
--- a/lib/xos-genx/xos-genx-tests/test_pure_proto.py
+++ b/lib/xos-genx/xos-genx-tests/test_pure_proto.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -14,16 +13,16 @@
# limitations under the License.
-
import unittest
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import XProtoTestHelpers
# Generate from xproto, then generate from equivalent proto
+
+
class XPureProtobufGenerator(unittest.TestCase):
def test_pure_proto(self):
- xproto = \
-"""
+ xproto = """
message VRouterPort (XOSBase){
optional string name = 1 [help_text = "port friendly name", max_length = 20, null = True, db_index = False, blank = True];
required string openflow_id = 2 [help_text = "port identifier in ONOS", max_length = 21, null = False, db_index = False, blank = False];
@@ -32,8 +31,7 @@
}
"""
- proto = \
-"""
+ proto = """
message VRouterPort {
option bases = "XOSBase";
optional string name = 1 [ null = "True", max_length = "20", blank = "True", help_text = "port friendly name", modifier = "optional", db_index = "False" ];
@@ -42,8 +40,8 @@
required int32 vrouter_service = 4 [ null = "False", blank = "False", model = "VRouterService", modifier = "required", type = "link", port = "device_ports", db_index = "True", link = "manytoone"];
}
"""
- target = XProtoTestHelpers.write_tmp_target(
-"""
+ target = XProtoTestHelpers.write_tmp_target(
+ """
from header import *
{% for m in proto.messages %}
{% if file_exists(xproto_base_name(m.name)|lower+'_header.py') -%}from {{xproto_base_name(m.name)|lower }}_header import *{% endif %}
@@ -81,53 +79,52 @@
{% if file_exists(xproto_base_name(m.name)|lower+'_bottom.py') -%}{{ include_file(xproto_base_name(m.name)|lower+'_bottom.py') }}{% endif %}
{% endfor %}
-""")
+"""
+ )
- args_xproto = XOSProcessorArgs()
- args_xproto.inputs = xproto
- args_xproto.target = target
- xproto_gen = XOSProcessor.process(args_xproto)
+ args_xproto = XOSProcessorArgs()
+ args_xproto.inputs = xproto
+ args_xproto.target = target
+ xproto_gen = XOSProcessor.process(args_xproto)
- count1 = len(xproto_gen.split('\n'))
+ count1 = len(xproto_gen.split("\n"))
- args_proto = XOSProcessorArgs()
- args_proto.inputs = proto
- args_proto.target = target
- args_proto.rev = True
- proto_gen = XOSProcessor.process(args_proto)
- count2 = len(proto_gen.split('\n'))
+ args_proto = XOSProcessorArgs()
+ args_proto.inputs = proto
+ args_proto.target = target
+ args_proto.rev = True
+ proto_gen = XOSProcessor.process(args_proto)
+ count2 = len(proto_gen.split("\n"))
- self.assertEqual(count1, count2)
+ self.assertEqual(count1, count2)
def test_pure_policies(self):
- xproto = \
-"""
+ xproto = """
policy my_policy < exists x:a=b >
"""
- proto = \
-"""
+ proto = """
option my_policy = "policy:< exists x:a=b >";
"""
- target = XProtoTestHelpers.write_tmp_target(
-"""
+ target = XProtoTestHelpers.write_tmp_target(
+ """
{{ policies }}
-""")
+"""
+ )
- args_xproto = XOSProcessorArgs()
- args_xproto.inputs = xproto
- args_xproto.target = target
- xproto_gen = XOSProcessor.process(args_xproto)
+ args_xproto = XOSProcessorArgs()
+ args_xproto.inputs = xproto
+ args_xproto.target = target
+ xproto_gen = XOSProcessor.process(args_xproto)
- args_proto = XOSProcessorArgs()
- args_proto.inputs = proto
- args_proto.target = target
- args_proto.rev = True
- proto_gen = XOSProcessor.process(args_proto)
+ args_proto = XOSProcessorArgs()
+ args_proto.inputs = proto
+ args_proto.target = target
+ args_proto.rev = True
+ proto_gen = XOSProcessor.process(args_proto)
- self.assertEqual(proto_gen, xproto_gen)
+ self.assertEqual(proto_gen, xproto_gen)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_rlinks.py b/lib/xos-genx/xos-genx-tests/test_rlinks.py
index 635c81f..c0ad406 100644
--- a/lib/xos-genx/xos-genx-tests/test_rlinks.py
+++ b/lib/xos-genx/xos-genx-tests/test_rlinks.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -18,18 +17,20 @@
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import XProtoTestHelpers
+
class XProtoRlinkTests(unittest.TestCase):
def test_proto_generator(self):
- target = XProtoTestHelpers.write_tmp_target("""
+ target = XProtoTestHelpers.write_tmp_target(
+ """
{% for m in proto.messages %}
{% for r in m.rlinks %}
{{ r }}
{% endfor %}
{% endfor %}
-""")
-
- xproto = \
"""
+ )
+
+ xproto = """
message VRouterPort (PlCoreBase){
optional string name = 1 [help_text = "port friendly name", max_length = 20, null = True, db_index = False, blank = True];
required string openflow_id = 2 [help_text = "port identifier in ONOS", max_length = 21, null = False, db_index = False, blank = False];
@@ -60,7 +61,6 @@
self.assertIn("'src_port': 'device_ports'", output)
self.assertIn("'src_port': 'ports'", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_swagger.py b/lib/xos-genx/xos-genx-tests/test_swagger.py
index 00b0684..3af997e 100644
--- a/lib/xos-genx/xos-genx-tests/test_swagger.py
+++ b/lib/xos-genx/xos-genx-tests/test_swagger.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,11 +19,12 @@
from xosgenx.generator import XOSProcessor, XOSProcessorArgs
from helpers import OUTPUT_DIR
+
class Args:
pass
-class XOSProcessorTest(unittest.TestCase):
+class XOSProcessorTest(unittest.TestCase):
def test_swagger_target(self):
"""
[XOS-GenX] The swagger xtarget should generate the appropriate json
@@ -32,10 +32,9 @@
# xosgenx --output . --target xosgenx/targets/swagger.xtarget --write-to-file single --dest-file swagger.yaml ../../xos/core/models/core.xproto
# http-server --cors Users/teone/Sites/opencord/orchestration/xos/lib/xos-genx/
- xproto = \
- """
+ xproto = """
option app_label = "core";
-
+
message Instance::instance_policy (XOSBase) {
option validators = "instance_creator:Instance has no creator, instance_isolation: Container instance {obj.name} must use container image, instance_isolation_container_vm_parent:Container-vm instance {obj.name} must have a parent, instance_parent_isolation_container_vm:Parent field can only be set on Container-vm instances ({obj.name}), instance_isolation_vm: VM Instance {obj.name} must use VM image, instance_creator_privilege: instance creator has no privileges on slice";
optional string instance_id = 1 [max_length = 200, content_type = "stripped", blank = True, help_text = "Nova instance id", null = True, db_index = False];
@@ -58,7 +57,7 @@
"""
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'swagger.xtarget'
+ args.target = "swagger.xtarget"
args.output = OUTPUT_DIR
args.write_to_file = "single"
args.dest_file = "swagger.yaml"
@@ -68,5 +67,6 @@
self.assertIn("/xosapi/v1/core/instances/{id}:", output)
self.assertIn("Instance:", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
diff --git a/lib/xos-genx/xos-genx-tests/test_target.py b/lib/xos-genx/xos-genx-tests/test_target.py
index d729be7..c468018 100644
--- a/lib/xos-genx/xos-genx-tests/test_target.py
+++ b/lib/xos-genx/xos-genx-tests/test_target.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -23,24 +22,25 @@
TEST_OUTPUT = "Do re mi fa so la ti do"
-class XProtoTargetTests(unittest.TestCase):
+class XProtoTargetTests(unittest.TestCase):
def setUp(self):
- test_file = open(os.path.join(OUTPUT_DIR, TEST_FILE), 'w')
+ test_file = open(os.path.join(OUTPUT_DIR, TEST_FILE), "w")
test_file.write(TEST_OUTPUT)
test_file.close()
def test_file_methods(self):
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{%% if file_exists("%s") %%}
{{ include_file("%s") }}
{%% endif %%}
-"""%(TEST_FILE, TEST_FILE)
+"""
+ % (TEST_FILE, TEST_FILE)
)
args = XOSProcessorArgs()
- args.inputs = ''
+ args.inputs = ""
args.target = target
args.attic = OUTPUT_DIR
output = XOSProcessor.process(args)
@@ -48,30 +48,31 @@
def test_xproto_lib(self):
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{{ xproto_first_non_empty([None, None, None, None, None, None, "Eureka"]) }}
-""")
+"""
+ )
args = XOSProcessorArgs()
- args.inputs = ''
+ args.inputs = ""
args.target = target
output = XOSProcessor.process(args)
self.assertIn("Eureka", output)
def test_context(self):
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{{ context.what }}
-""")
+"""
+ )
args = XOSProcessorArgs()
- args.inputs = ''
+ args.inputs = ""
args.target = target
- args.kv='what:what is what'
+ args.kv = "what:what is what"
output = XOSProcessor.process(args)
self.assertIn("what is what", output)
def test_singularize(self):
- proto = \
-"""
+ proto = """
message TestSingularize {
// The following field has an explicitly specified singular
required int many = 1 [singular = "one"];
@@ -84,20 +85,22 @@
"""
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{% for m in proto.messages.0.fields -%}
{{ xproto_singularize(m) }},
{%- endfor %}
-""")
+"""
+ )
args = XOSProcessorArgs()
args.inputs = proto
args.target = target
output = XOSProcessor.process(args)
- self.assertEqual("one,sheep,slice,network,omf_friendly", output.lstrip().rstrip().rstrip(','))
+ self.assertEqual(
+ "one,sheep,slice,network,omf_friendly", output.lstrip().rstrip().rstrip(",")
+ )
def test_pluralize(self):
- proto = \
-"""
+ proto = """
message TestPluralize {
// The following field has an explicitly specified plural
required int anecdote = 1 [plural = "data"];
@@ -110,18 +113,21 @@
"""
target = XProtoTestHelpers.write_tmp_target(
-"""
+ """
{% for m in proto.messages.0.fields -%}
{{ xproto_pluralize(m) }},
{%- endfor %}
-""")
+"""
+ )
args = XOSProcessorArgs()
args.inputs = proto
args.target = target
output = XOSProcessor.process(args)
- self.assertEqual("data,sheep,slices,networks,omf_friendlies", output.lstrip().rstrip().rstrip(','))
+ self.assertEqual(
+ "data,sheep,slices,networks,omf_friendlies",
+ output.lstrip().rstrip().rstrip(","),
+ )
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_tosca.py b/lib/xos-genx/xos-genx-tests/test_tosca.py
index 270d126..c5a0f17 100644
--- a/lib/xos-genx/xos-genx-tests/test_tosca.py
+++ b/lib/xos-genx/xos-genx-tests/test_tosca.py
@@ -18,7 +18,6 @@
class XProtoToscaTypeTest(unittest.TestCase):
-
def setUp(self):
self.target_tosca_type = XProtoTestHelpers.write_tmp_target(
"""
@@ -27,13 +26,14 @@
{{ xproto_tosca_field_type(f.type) }}
{% endfor -%}
{% endfor -%}
- """)
+ """
+ )
+
def test_tosca_fields(self):
"""
[XOS-GenX] should convert xproto types to tosca know types
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
message Foo {
@@ -47,26 +47,26 @@
args.inputs = xproto
args.target = self.target_tosca_type
output = XOSProcessor.process(args)
- self.assertIn('string', output)
- self.assertIn('boolean', output)
- self.assertIn('integer', output)
+ self.assertIn("string", output)
+ self.assertIn("boolean", output)
+ self.assertIn("integer", output)
+
class XProtoToscaKeyTest(unittest.TestCase):
-
def setUp(self):
self.target_tosca_keys = XProtoTestHelpers.write_tmp_target(
"""
{%- for m in proto.messages %}
{{ xproto_fields_to_tosca_keys(m.fields, m) }}
{% endfor -%}
- """)
+ """
+ )
def test_xproto_fields_to_tosca_keys_default(self):
"""
[XOS-GenX] if no "tosca_key" is specified, and a name attribute is present in the model, use that
"""
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -78,16 +78,15 @@
args.inputs = xproto
args.target = self.target_tosca_keys
output = XOSProcessor.process(args)
- self.assertIn('name', output)
+ self.assertIn("name", output)
def test_xproto_fields_to_tosca_keys_custom(self):
"""
[XOS-GenX] if "tosca_key" is specified, use it
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
-
+
message Foo {
required string name = 1 [ null = "False", blank="False"];
required string key_1 = 2 [ null = "False", blank="False", tosca_key=True];
@@ -99,16 +98,15 @@
args.inputs = xproto
args.target = self.target_tosca_keys
output = XOSProcessor.process(args)
- self.assertNotIn('name', output)
- self.assertIn('key_1', output)
- self.assertIn('key_2', output)
+ self.assertNotIn("name", output)
+ self.assertIn("key_1", output)
+ self.assertIn("key_2", output)
def test_xproto_fields_link_to_tosca_keys_custom(self):
"""
[XOS-GenX] if "tosca_key" is specified, use it
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
message Foo {
@@ -121,21 +119,20 @@
args.inputs = xproto
args.target = self.target_tosca_keys
output = XOSProcessor.process(args)
- self.assertNotIn('name', output)
- self.assertIn('provider_service_instance_id', output)
+ self.assertNotIn("name", output)
+ self.assertIn("provider_service_instance_id", output)
def test_xproto_model_to_oneof_key(self):
"""
[XOS-GenX] in some models we need to have a combine key on variable fields, for example, keys can be subscriber_service_id + oneof(provider_service_id, provider_network_id)
"""
- xproto = \
- """
+ xproto = """
option app_label = "test";
message Foo {
-
+
option tosca_key = "key1, oneof(key_2, key_3)";
-
+
required string name = 1 [ null = "False", blank="False"];
required string key_1 = 2 [ null = "False", blank="False", tosca_key_one_of = "key_2"];
required string key_2 = 3 [ null = "False", blank="False", tosca_key_one_of = "key_1"];
@@ -150,8 +147,7 @@
output = XOSProcessor.process(args)
self.assertIn("['name', ['key_4', 'key_3'], ['key_1', 'key_2']]", output)
- xproto = \
- """
+ xproto = """
option app_label = "test";
message Foo {
diff --git a/lib/xos-genx/xos-genx-tests/test_translator.py b/lib/xos-genx/xos-genx-tests/test_translator.py
index f3476cd..320021b 100644
--- a/lib/xos-genx/xos-genx-tests/test_translator.py
+++ b/lib/xos-genx/xos-genx-tests/test_translator.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -28,20 +27,23 @@
required int32 vrouter_service = 4 [ null = "False", blank = "False", model = "VRouterService", modifier = "required", type = "link", port = "device_ports", link_type = "manytoone", db_index = "True" ];
}
"""
-VROUTER_XPROTO = os.path.abspath(os.path.dirname(os.path.realpath(__file__)) + "/xproto/vrouterport.xproto")
+VROUTER_XPROTO = os.path.abspath(
+ os.path.dirname(os.path.realpath(__file__)) + "/xproto/vrouterport.xproto"
+)
# Generate other formats from xproto
+
+
class XProtoTranslatorTest(unittest.TestCase):
def _test_proto_generator(self):
args = XOSProcessorArgs()
args.files = [VROUTER_XPROTO]
- args.target = 'proto.xtarget'
+ args.target = "proto.xtarget"
output = XOSProcessor.process(args)
self.assertEqual(output, PROTO_EXPECTED_OUTPUT)
def test_yaml_generator(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Port (PlCoreBase,ParameterMixin){
@@ -120,15 +122,14 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
yaml_ir = yaml.load(output)
- self.assertEqual(len(yaml_ir['items']), 4)
+ self.assertEqual(len(yaml_ir["items"]), 4)
def test_gui_hidden_models(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -143,16 +144,15 @@
"""
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
yaml_ir = yaml.load(output)
- self.assertEqual(len(yaml_ir['items']), 1)
- self.assertIn('Bar', output)
- self.assertNotIn('Foo', output)
+ self.assertEqual(len(yaml_ir["items"]), 1)
+ self.assertIn("Bar", output)
+ self.assertNotIn("Foo", output)
def test_gui_hidden_model_fields(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -162,16 +162,15 @@
"""
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
yaml_ir = yaml.load(output)
- self.assertEqual(len(yaml_ir['items']), 1)
- self.assertIn('name', output)
- self.assertNotIn('secret', output)
+ self.assertEqual(len(yaml_ir["items"]), 1)
+ self.assertIn("name", output)
+ self.assertNotIn("secret", output)
def test_static_options(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -182,14 +181,13 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
self.assertIn("options:", output)
self.assertIn(" {'id': 'container_vm', 'label': 'Container In VM'}", output)
def test_not_static_options(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -199,13 +197,12 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
self.assertNotIn("options:", output)
def test_default_value_in_modeldef(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -219,7 +216,7 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
self.assertIn('default: "bar"', output)
self.assertIn('default: "false"', output)
@@ -228,8 +225,7 @@
self.assertIn('default: "0"', output)
def test_not_default_value_in_modeldef(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -239,13 +235,12 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
- self.assertNotIn('default:', output)
+ self.assertNotIn("default:", output)
def test_one_to_many_in_modeldef(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message ServiceDependency {
@@ -260,19 +255,28 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
# Service deps model
- self.assertIn('{model: Service, type: manytoone, on_field: provider_service}', output)
- self.assertIn('{model: Service, type: manytoone, on_field: provider_service}', output)
+ self.assertIn(
+ "{model: Service, type: manytoone, on_field: provider_service}", output
+ )
+ self.assertIn(
+ "{model: Service, type: manytoone, on_field: provider_service}", output
+ )
# Service model
- self.assertIn('{model: ServiceDependency, type: onetomany, on_field: provider_service}', output)
- self.assertIn('{model: ServiceDependency, type: onetomany, on_field: provider_service}', output)
+ self.assertIn(
+ "{model: ServiceDependency, type: onetomany, on_field: provider_service}",
+ output,
+ )
+ self.assertIn(
+ "{model: ServiceDependency, type: onetomany, on_field: provider_service}",
+ output,
+ )
def test_model_description(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -288,13 +292,12 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
self.assertIn('description: "This is the Foo model"', output)
def test_model_verbose_name(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message Foo {
@@ -310,13 +313,12 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
self.assertIn('verbose_name: "Verbose Foo Name"', output)
def test_feedback_field(self):
- xproto = \
-"""
+ xproto = """
option app_label = "test";
message ParentFoo {
@@ -330,13 +332,12 @@
args = XOSProcessorArgs()
args.inputs = xproto
- args.target = 'modeldefs.xtarget'
+ args.target = "modeldefs.xtarget"
output = XOSProcessor.process(args)
- read_only = filter(lambda s: 'read_only: True' in s, output.splitlines())
- self.assertEqual(len(read_only), 3) # readonly is 1 for ParentFoo and 2 for Foo
+ read_only = filter(lambda s: "read_only: True" in s, output.splitlines())
+ self.assertEqual(len(read_only), 3) # readonly is 1 for ParentFoo and 2 for Foo
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
-
-
diff --git a/lib/xos-genx/xos-genx-tests/test_xos_security.py b/lib/xos-genx/xos-genx-tests/test_xos_security.py
index 766e102..3bd4653 100644
--- a/lib/xos-genx/xos-genx-tests/test_xos_security.py
+++ b/lib/xos-genx/xos-genx-tests/test_xos_security.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,25 +20,32 @@
"""The function below is for eliminating warnings arising due to the missing policy_output_enforcer,
which is generated and loaded dynamically.
"""
+
+
def policy_output_enforcer(x, y):
raise Exception("Security enforcer not generated. Test failed.")
return False
+
"""
-The tests below use the Python code target to generate
+The tests below use the Python code target to generate
Python security policies, set up an appropriate environment and execute the Python.
The security policies here deliberately made complex in order to stress the processor.
"""
+
+
class XProtoXOSSecurityTest(unittest.TestCase):
def setUp(self):
- self.target = XProtoTestHelpers.write_tmp_target("{{ xproto_fol_to_python_test('output',proto.policies.test_policy, None, '0') }}")
+ self.target = XProtoTestHelpers.write_tmp_target(
+ "{{ xproto_fol_to_python_test('output',proto.policies.test_policy, None, '0') }}"
+ )
"""
This is the security policy for controllers
"""
+
def test_controller_policy(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < ctx.user.is_admin | exists Privilege: Privilege.accessor_id = ctx.user.id & Privilege.object_type = "Deployment" & Privilege.permission = "role:admin" & Privilege.object_id = obj.id >
"""
args = XOSProcessorArgs()
@@ -48,7 +54,7 @@
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_enforcer(obj, ctx):
@@ -64,10 +70,10 @@
"""
This is the security policy for ControllerNetworks
"""
+
def test_controller_network_policy(self):
- xproto = \
-"""
- policy test_policy <
+ xproto = """
+ policy test_policy <
ctx.user.is_admin
| (exists Privilege:
Privilege.accessor_id = ctx.user.id
@@ -86,7 +92,7 @@
args.target = self.target
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_enforcer(obj, ctx):
@@ -104,9 +110,9 @@
"""
This is the security policy for Slices
"""
+
def test_slice_policy(self):
- xproto = \
-"""
+ xproto = """
policy site_policy <
ctx.user.is_admin
| (ctx.write_access -> exists Privilege: Privilege.object_type = "Site" & Privilege.object_id = obj.id & Privilege.accessor_id = ctx.user.id & Privilege.permission_id = "role:admin") >
@@ -127,7 +133,7 @@
& Privilege.object_id = obj.site.id
& Privilege.permission = "role:admin"))
)>
-
+
"""
args = XOSProcessorArgs()
args.inputs = xproto
@@ -135,25 +141,25 @@
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_enforcer(obj, ctx):
- i2 = ctx.user.is_admin
- i4 = policy_site_policy_enforcer(obj.site, ctx)
- i10 = ctx.write_access
- i11 = (not (not Privilege.objects.filter(Q(accessor_id=ctx.user.id), Q(accessor_type='User'), Q(object_type='Slice'), Q(object_id=obj.id), Q(permission='role:admin'))))
- i8 = (i10 and i11)
- i14 = ctx.write_access
- i12 = (not i14)
- i13 = (not (not Privilege.objects.filter(Q(accessor_id=ctx.user.id), Q(accessor_type='User'), Q(object_type='Slice'), Q(object_id=obj.id))))
- i9 = (i12 and i13)
- i6 = (i8 or i9)
- i7 = (not (not Privilege.objects.filter(Q(accessor_id=ctx.user.id), Q(accessor_type='User'), Q(object_type='Site'), Q(object_id=obj.site.id), Q(permission='role:admin'))))
- i5 = (i6 or i7)
- i3 = (i4 and i5)
- i1 = (i2 or i3)
- return i1
+ i2 = ctx.user.is_admin
+ i4 = policy_site_policy_enforcer(obj.site, ctx)
+ i10 = ctx.write_access
+ i11 = (not (not Privilege.objects.filter(Q(accessor_id=ctx.user.id), Q(accessor_type='User'), Q(object_type='Slice'), Q(object_id=obj.id), Q(permission='role:admin'))))
+ i8 = (i10 and i11)
+ i14 = ctx.write_access
+ i12 = (not i14)
+ i13 = (not (not Privilege.objects.filter(Q(accessor_id=ctx.user.id), Q(accessor_type='User'), Q(object_type='Slice'), Q(object_id=obj.id))))
+ i9 = (i12 and i13)
+ i6 = (i8 or i9)
+ i7 = (not (not Privilege.objects.filter(Q(accessor_id=ctx.user.id), Q(accessor_type='User'), Q(object_type='Site'), Q(object_id=obj.site.id), Q(permission='role:admin'))))
+ i5 = (i6 or i7)
+ i3 = (i4 and i5)
+ i1 = (i2 or i3)
+ return i1
"""
# FIXME: Test this policy by executing it
@@ -162,13 +168,13 @@
"""
This is the security policy for Users
"""
+
def test_user_policy(self):
- xproto = \
-"""
+ xproto = """
policy test_policy <
ctx.user.is_admin
| ctx.user.id = obj.id
- | (exists Privilege:
+ | (exists Privilege:
Privilege.accessor_id = ctx.user.id
& Privilege.accessor_type = "User"
& Privilege.permission = "role:admin"
@@ -181,7 +187,7 @@
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_enforcer(obj, ctx):
@@ -196,5 +202,6 @@
# FIXME: Test this policy by executing it
self.assertTrue(policy_output_enforcer is not None)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()
diff --git a/lib/xos-genx/xos-genx-tests/test_xos_validation.py b/lib/xos-genx/xos-genx-tests/test_xos_validation.py
index f2f8ce3..257eb4d 100644
--- a/lib/xos-genx/xos-genx-tests/test_xos_validation.py
+++ b/lib/xos-genx/xos-genx-tests/test_xos_validation.py
@@ -1,4 +1,3 @@
-
# Copyright 2017-present Open Networking Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
@@ -21,21 +20,27 @@
"""The function below is for eliminating warnings arising due to the missing policy_output_validator,
which is generated and loaded dynamically.
"""
+
+
def policy_output_validator(x, y):
raise Exception("Validator not generated. Test failed.")
return False
+
"""
-The tests below use the Python code target to generate
+The tests below use the Python code target to generate
Python validation policies, set up an appropriate environment and execute the Python.
"""
+
+
class XProtoXOSModelValidationTest(unittest.TestCase):
def setUp(self):
- self.target = XProtoTestHelpers.write_tmp_target("{{ xproto_fol_to_python_validator('output', proto.policies.test_policy, None, 'Necessary Failure') }}")
+ self.target = XProtoTestHelpers.write_tmp_target(
+ "{{ xproto_fol_to_python_validator('output', proto.policies.test_policy, None, 'Necessary Failure') }}"
+ )
def test_instance_container(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < (obj.isolation = "container" | obj.isolation = "container_vm" ) -> (obj.image.kind = "container") >
"""
args = XOSProcessorArgs()
@@ -45,10 +50,10 @@
output = XOSProcessor.process(args)
obj = FakeObject()
- obj.isolation = 'container'
- obj.kind = 'not a container'
+ obj.isolation = "container"
+ obj.kind = "not a container"
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -61,11 +66,10 @@
"""
with self.assertRaises(Exception):
- policy_output_validator(obj, {})
-
+ policy_output_validator(obj, {})
+
def test_slice_name_validation(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < not obj.id -> {{ obj.name.startswith(obj.site.login_base) }} >
"""
args = XOSProcessorArgs()
@@ -75,10 +79,10 @@
output = XOSProcessor.process(args)
obj = FakeObject()
- obj.isolation = 'container'
- obj.kind = 'not a container'
+ obj.isolation = "container"
+ obj.kind = "not a container"
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -91,11 +95,10 @@
"""
with self.assertRaises(Exception):
- policy_output_validator(obj, {})
+ policy_output_validator(obj, {})
def test_equal(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < not (ctx.user = obj.user) >
"""
@@ -105,7 +108,7 @@
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -121,11 +124,10 @@
ctx.user = 1
with self.assertRaises(Exception):
- policy_output_validator(obj, ctx)
+ policy_output_validator(obj, ctx)
def test_bin(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < not (ctx.is_admin = True | obj.empty = True) | False>
"""
@@ -134,7 +136,7 @@
args.target = self.target
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -154,10 +156,8 @@
with self.assertRaises(Exception):
verdict = policy_output_validator(obj, ctx)
-
def test_exists(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < exists Privilege: Privilege.object_id = obj.id >
"""
args = XOSProcessorArgs()
@@ -165,7 +165,7 @@
args.target = self.target
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -175,17 +175,16 @@
"""
self.assertTrue(policy_output_validator is not None)
-
+
def test_python(self):
- xproto = \
-"""
+ xproto = """
policy test_policy < {{ "jack" in ["the", "box"] }} = True >
"""
args = XOSProcessorArgs()
args.inputs = xproto
args.target = self.target
output = XOSProcessor.process(args)
- exec(output) # This loads the generated function, which should look like this:
+ exec(output) # This loads the generated function, which should look like this:
"""
def policy_output_validator(obj, ctx):
@@ -200,8 +199,7 @@
def test_forall(self):
# This one we only parse
- xproto = \
-"""
+ xproto = """
policy test_policy < forall Credential: Credential.obj_id = obj_id >
"""
@@ -218,7 +216,8 @@
return i1
"""
- self.assertIn('policy_output_validator', output)
+ self.assertIn("policy_output_validator", output)
-if __name__ == '__main__':
+
+if __name__ == "__main__":
unittest.main()