diff options
author | Thomas Duval <thomas.duval@orange.com> | 2020-06-03 10:06:52 +0200 |
---|---|---|
committer | Thomas Duval <thomas.duval@orange.com> | 2020-06-03 10:06:52 +0200 |
commit | 7bb53c64da2dcf88894bfd31503accdd81498f3d (patch) | |
tree | 4310e12366818af27947b5e2c80cb162da93a4b5 /moon_manager/tests/unit_python | |
parent | cbea4e360e9bfaa9698cf7c61c83c96a1ba89b8c (diff) |
Update to new version 5.4HEADstable/jermamaster
Signed-off-by: Thomas Duval <thomas.duval@orange.com>
Change-Id: Idcd868133d75928a1ffd74d749ce98503e0555ea
Diffstat (limited to 'moon_manager/tests/unit_python')
43 files changed, 5478 insertions, 3364 deletions
diff --git a/moon_manager/tests/unit_python/api/__init__.py b/moon_manager/tests/unit_python/api/__init__.py new file mode 100644 index 00000000..1856aa2c --- /dev/null +++ b/moon_manager/tests/unit_python/api/__init__.py @@ -0,0 +1,12 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + diff --git a/moon_manager/tests/unit_python/api/import_export_utilities.py b/moon_manager/tests/unit_python/api/import_export_utilities.py deleted file mode 100644 index 2ee2627d..00000000 --- a/moon_manager/tests/unit_python/api/import_export_utilities.py +++ /dev/null @@ -1,202 +0,0 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. - -import api.test_unit_models as test_models -import api.test_policies as test_policies -import api.test_perimeter as test_perimeter -import api.test_meta_data as test_categories -import api.test_data as test_data -import api.test_meta_rules as test_meta_rules -import api.test_assignement as test_assignments -import api.test_rules as test_rules -import logging - -logger = logging.getLogger("moon.manager.test.api." + __name__) - - -def clean_models(client): - req, models = test_models.get_models(client) - for key in models["models"]: - client.delete("/models/{}".format(key)) - - -def clean_policies(client): - req, policies = test_policies.get_policies(client) - for key in policies["policies"]: - req = client.delete("/policies/{}".format(key)) - assert req.status_code == 200 - - -def clean_subjects(client): - subjects = test_perimeter.get_subjects(client) - logger.info("subjects {}".format(subjects)) - for key in subjects[1]["subjects"]: - subject = subjects[1]["subjects"][key] - policy_keys = subject["policy_list"] - logger.info("subjects policy_keys {}".format(policy_keys)) - for policy_key in policy_keys: - client.delete("/policies/{}/subjects/{}".format(policy_key, key)) - - -def clean_objects(client): - objects = test_perimeter.get_objects(client) - logger.info("objects {}".format(objects)) - for key in objects[1]["objects"]: - object_ = objects[1]["objects"][key] - policy_keys = object_["policy_list"] - logger.info("objects policy_keys {}".format(policy_keys)) - for policy_key in policy_keys: - client.delete("/policies/{}/objects/{}".format(policy_key, key)) - - -def clean_actions(client): - actions = test_perimeter.get_actions(client) - actions = test_perimeter.get_actions(client) - logger.info("actions {}".format(actions)) - for key in actions[1]["actions"]: - action = actions[1]["actions"][key] - policy_keys = action["policy_list"] - logger.info("action policy_keys {}".format(policy_keys)) - for policy_key in policy_keys: - client.delete("/policies/{}/actions/{}".format(policy_key, key)) - - -def clean_subject_categories(client): - req, categories = test_categories.get_subject_categories(client) - logger.info(categories) - for key in categories["subject_categories"]: - client.delete("/subject_categories/{}".format(key)) - - -def clean_object_categories(client): - req, categories = test_categories.get_object_categories(client) - logger.info(categories) - for key in categories["object_categories"]: - client.delete("/object_categories/{}".format(key)) - - -def clean_action_categories(client): - req, categories = test_categories.get_action_categories(client) - logger.info(categories) - for key in categories["action_categories"]: - client.delete("/action_categories/{}".format(key)) - - -def clean_subject_data(client): - req, policies = test_policies.get_policies(client) - logger.info("clean_subject_data on {}".format(policies)) - for policy_key in policies["policies"]: - req, data = test_data.get_subject_data(client, policy_id=policy_key) - logger.info("============= data {}".format(data)) - for data_item in data["subject_data"]: - if data_item["data"]: - for data_id in data_item["data"]: - logger.info("============= Deleting {}/{}".format(policy_key, data_id)) - client.delete("/policies/{}/subject_data/{}/{}".format(policy_key, data_item['category_id'], data_id)) - - -def clean_object_data(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, data = test_data.get_object_data(client, policy_id=policy_key) - for data_item in data["object_data"]: - if data_item["data"]: - for data_id in data_item["data"]: - logger.info("============= object_data {}/{}".format(policy_key, data_id)) - client.delete("/policies/{}/object_data/{}/{}".format(policy_key, data_item['category_id'], data_id)) - - -def clean_action_data(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, data = test_data.get_action_data(client, policy_id=policy_key) - for data_item in data["action_data"]: - if data_item["data"]: - for data_id in data_item["data"]: - logger.info("============= action_data {}/{}".format(policy_key, data_id)) - client.delete("/policies/{}/action_data/{}/{}".format(policy_key, data_item['category_id'], data_id)) - - -def clean_meta_rule(client): - req, meta_rules = test_meta_rules.get_meta_rules(client) - meta_rules = meta_rules["meta_rules"] - for meta_rule_key in meta_rules: - logger.info("clean_meta_rule.meta_rule_key={}".format(meta_rule_key)) - logger.info("clean_meta_rule.meta_rule={}".format(meta_rules[meta_rule_key])) - client.delete("/meta_rules/{}".format(meta_rule_key)) - - -def clean_subject_assignments(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, assignments = test_assignments.get_subject_assignment(client, policy_key) - for key in assignments["subject_assignments"]: - subject_key = assignments["subject_assignments"][key]["subject_id"] - cat_key = assignments["subject_assignments"][key]["category_id"] - data_keys = assignments["subject_assignments"][key]["assignments"] - for data_key in data_keys: - client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_key, subject_key, - cat_key, data_key)) - - -def clean_object_assignments(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, assignments = test_assignments.get_object_assignment(client, policy_key) - for key in assignments["object_assignments"]: - object_key = assignments["object_assignments"][key]["object_id"] - cat_key = assignments["object_assignments"][key]["category_id"] - data_keys = assignments["object_assignments"][key]["assignments"] - for data_key in data_keys: - client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_key, object_key, - cat_key, data_key)) - - -def clean_action_assignments(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, assignments = test_assignments.get_action_assignment(client, policy_key) - for key in assignments["action_assignments"]: - action_key = assignments["action_assignments"][key]["action_id"] - cat_key = assignments["action_assignments"][key]["category_id"] - data_keys = assignments["action_assignments"][key]["assignments"] - for data_key in data_keys: - client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_key, action_key, - cat_key, data_key)) - - -def clean_rules(client): - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, rules = test_rules.get_rules(client, policy_key) - rules = rules["rules"]["rules"] - for rule_key in rules: - req = client.delete("/policies/{}/rules/{}".format(policy_key, rule_key["id"])) - - -def clean_all(client): - clean_rules(client) - - clean_subject_assignments(client) - clean_object_assignments(client) - clean_action_assignments(client) - - - clean_subject_data(client) - clean_object_data(client) - clean_action_data(client) - - clean_actions(client) - clean_objects(client) - clean_subjects(client) - - clean_subject_categories(client) - clean_object_categories(client) - clean_action_categories(client) - - - clean_policies(client) - clean_models(client) - clean_meta_rule(client)
\ No newline at end of file diff --git a/moon_manager/tests/unit_python/api/meta_data_test.py b/moon_manager/tests/unit_python/api/meta_data_test.py deleted file mode 100644 index 8609f0b5..00000000 --- a/moon_manager/tests/unit_python/api/meta_data_test.py +++ /dev/null @@ -1,238 +0,0 @@ -import json -import api.utilities as utilities - -#subject_categories_test - - -def get_subject_categories(client): - req = client.get("/subject_categories") - subject_categories = utilities.get_json(req.data) - return req, subject_categories - - -def add_subject_categories(client, name): - data = { - "name": name, - "description": "description of {}".format(name) - } - req = client.post("/subject_categories", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - subject_categories = utilities.get_json(req.data) - return req, subject_categories - - -def delete_subject_categories(client, name): - request, subject_categories = get_subject_categories(client) - for key, value in subject_categories['subject_categories'].items(): - if value['name'] == name: - req = client.delete("/subject_categories/{}".format(key)) - break - return req - - -def delete_subject_categories_without_id(client): - req = client.delete("/subject_categories/{}".format("")) - return req - - -def test_get_subject_categories(): - client = utilities.register_client() - req, subject_categories = get_subject_categories(client) - assert req.status_code == 200 - assert isinstance(subject_categories, dict) - assert "subject_categories" in subject_categories - - -def test_add_subject_categories(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "testuser") - assert req.status_code == 200 - assert isinstance(subject_categories, dict) - value = list(subject_categories["subject_categories"].values())[0] - assert "subject_categories" in subject_categories - assert value['name'] == "testuser" - assert value['description'] == "description of {}".format("testuser") - - -def test_add_subject_categories_with_empty_user(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "Empty String" - - -def test_add_subject_categories_with_user_contain_space(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "test user") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "String contains space" - - -def test_delete_subject_categories(): - client = utilities.register_client() - req = delete_subject_categories(client, "testuser") - assert req.status_code == 200 - - -def test_delete_subject_categories_without_id(): - client = utilities.register_client() - req = delete_subject_categories_without_id(client) - assert req.status_code == 500 - - -#--------------------------------------------------------------------------- -#object_categories_test - -def get_object_categories(client): - req = client.get("/object_categories") - object_categories = utilities.get_json(req.data) - return req, object_categories - - -def add_object_categories(client, name): - data = { - "name": name, - "description": "description of {}".format(name) - } - req = client.post("/object_categories", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - object_categories = utilities.get_json(req.data) - return req, object_categories - - -def delete_object_categories(client, name): - request, object_categories = get_object_categories(client) - for key, value in object_categories['object_categories'].items(): - if value['name'] == name: - req = client.delete("/object_categories/{}".format(key)) - break - return req - - -def delete_object_categories_without_id(client): - req = client.delete("/object_categories/{}".format("")) - return req - - -def test_get_object_categories(): - client = utilities.register_client() - req, object_categories = get_object_categories(client) - assert req.status_code == 200 - assert isinstance(object_categories, dict) - assert "object_categories" in object_categories - - -def test_add_object_categories(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "testuser") - assert req.status_code == 200 - assert isinstance(object_categories, dict) - value = list(object_categories["object_categories"].values())[0] - assert "object_categories" in object_categories - assert value['name'] == "testuser" - assert value['description'] == "description of {}".format("testuser") - - -def test_add_object_categories_with_empty_user(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "Empty String" - - -def test_add_object_categories_with_user_contain_space(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "test user") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "String contains space" - - -def test_delete_object_categories(): - client = utilities.register_client() - req = delete_object_categories(client, "testuser") - assert req.status_code == 200 - - -def test_delete_object_categories_without_id(): - client = utilities.register_client() - req = delete_object_categories_without_id(client) - assert req.status_code == 500 - - -#--------------------------------------------------------------------------- -#action_categories_test - -def get_action_categories(client): - req = client.get("/action_categories") - action_categories = utilities.get_json(req.data) - return req, action_categories - - -def add_action_categories(client, name): - data = { - "name": name, - "description": "description of {}".format(name) - } - req = client.post("/action_categories", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - action_categories = utilities.get_json(req.data) - return req, action_categories - - -def delete_action_categories(client, name): - request, action_categories = get_action_categories(client) - for key, value in action_categories['action_categories'].items(): - if value['name'] == name: - req = client.delete("/action_categories/{}".format(key)) - break - return req - - -def delete_action_categories_without_id(client): - req = client.delete("/action_categories/{}".format("")) - return req - - -def test_get_action_categories(): - client = utilities.register_client() - req, action_categories = get_action_categories(client) - assert req.status_code == 200 - assert isinstance(action_categories, dict) - assert "action_categories" in action_categories - - -def test_add_action_categories(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "testuser") - assert req.status_code == 200 - assert isinstance(action_categories, dict) - value = list(action_categories["action_categories"].values())[0] - assert "action_categories" in action_categories - assert value['name'] == "testuser" - assert value['description'] == "description of {}".format("testuser") - - -def test_add_action_categories_with_empty_user(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "Empty String" - - -def test_add_action_categories_with_user_contain_space(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "test user") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "String contains space" - - -def test_delete_action_categories(): - client = utilities.register_client() - req = delete_action_categories(client, "testuser") - assert req.status_code == 200 - - -def test_delete_action_categories_without_id(): - client = utilities.register_client() - req = delete_action_categories_without_id(client) - assert req.status_code == 500 diff --git a/moon_manager/tests/unit_python/api/meta_rules_test.py b/moon_manager/tests/unit_python/api/meta_rules_test.py deleted file mode 100644 index a87c16f3..00000000 --- a/moon_manager/tests/unit_python/api/meta_rules_test.py +++ /dev/null @@ -1,162 +0,0 @@ -import json -import api.utilities as utilities - - -def get_meta_rules(client): - req = client.get("/meta_rules") - meta_rules = utilities.get_json(req.data) - return req, meta_rules - - -def add_meta_rules(client, name): - data = { - "name": name, - "subject_categories": ["subject_category_id1", - "subject_category_id2"], - "object_categories": ["object_category_id1"], - "action_categories": ["action_category_id1"] - } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - meta_rules = utilities.get_json(req.data) - return req, meta_rules - - -def add_meta_rules_without_subject_category_ids(client, name): - data = { - "name": name, - "subject_categories": [], - "object_categories": ["object_category_id1"], - "action_categories": ["action_category_id1"] - } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - meta_rules = utilities.get_json(req.data) - return req, meta_rules - - -def update_meta_rules(client, name, metaRuleId): - data = { - "name": name, - "subject_categories": ["subject_category_id1_update", - "subject_category_id2_update"], - "object_categories": ["object_category_id1_update"], - "action_categories": ["action_category_id1_update"] - } - req = client.patch("/meta_rules/{}".format(metaRuleId), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - meta_rules = utilities.get_json(req.data) - return req, meta_rules - - -def update_meta_rules_without_subject_category_ids(client, name): - data = { - "name": name, - "subject_categories": [], - "object_categories": ["object_category_id1"], - "action_categories": ["action_category_id1"] - } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - meta_rules = utilities.get_json(req.data) - return req, meta_rules - - -def delete_meta_rules(client, name): - request, meta_rules = get_meta_rules(client) - for key, value in meta_rules['meta_rules'].items(): - if value['name'] == name: - req = client.delete("/meta_rules/{}".format(key)) - break - return req - - -def delete_meta_rules_without_id(client): - req = client.delete("/meta_rules/{}".format("")) - return req - - -def test_get_meta_rules(): - client = utilities.register_client() - req, meta_rules = get_meta_rules(client) - assert req.status_code == 200 - assert isinstance(meta_rules, dict) - assert "meta_rules" in meta_rules - - -def test_add_meta_rules(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "testuser") - assert req.status_code == 200 - assert isinstance(meta_rules, dict) - value = list(meta_rules["meta_rules"].values())[0] - assert "meta_rules" in meta_rules - assert value['name'] == "testuser" - assert value["subject_categories"][0] == "subject_category_id1" - assert value["object_categories"][0] == "object_category_id1" - assert value["action_categories"][0] == "action_category_id1" - - -def test_add_meta_rules_with_empty_user(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "Empty String" - - -def test_add_meta_rules_with_user_contain_space(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "test user") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == "String contains space" - - -def test_add_meta_rules_without_subject_categories(): - client = utilities.register_client() - req, meta_rules = add_meta_rules_without_subject_category_ids(client, "testuser") - assert req.status_code == 500 - assert json.loads(req.data)["message"] == 'Empty Container' - - -def test_delete_meta_rules(): - client = utilities.register_client() - req = delete_meta_rules(client, "testuser") - assert req.status_code == 200 - - -def test_delete_meta_rules_without_id(): - client = utilities.register_client() - req = delete_meta_rules_without_id(client) - assert req.status_code == 500 - - -def test_update_meta_rules(): - client = utilities.register_client() - req = add_meta_rules(client, "testuser") - meta_rule_id = list(req[1]['meta_rules'])[0] - req_update = update_meta_rules(client, "testuser", meta_rule_id) - assert req_update[0].status_code == 200 - value = list(req_update[1]["meta_rules"].values())[0] - assert value["subject_categories"][0] == "subject_category_id1_update" - delete_meta_rules(client, "testuser") - get_meta_rules(client) - - -def test_update_meta_rules_without_id(): - client = utilities.register_client() - req_update = update_meta_rules(client, "testuser", "") - assert req_update[0].status_code == 500 - - -def test_update_meta_rules_without_user(): - client = utilities.register_client() - req_update = update_meta_rules(client, "", "") - assert req_update[0].status_code == 500 - assert json.loads(req_update[0].data)["message"] == "Empty String" - - -def test_update_meta_rules_without_subject_categories(): - client = utilities.register_client() - req_update = update_meta_rules_without_subject_category_ids(client, "testuser") - assert req_update[0].status_code == 500 - assert json.loads(req_update[0].data)["message"] == "Empty Container" diff --git a/moon_manager/tests/unit_python/api/test_assignement.py b/moon_manager/tests/unit_python/api/test_assignement.py index b56fb420..3a127477 100644 --- a/moon_manager/tests/unit_python/api/test_assignement.py +++ b/moon_manager/tests/unit_python/api/test_assignement.py @@ -1,19 +1,60 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug +from uuid import uuid4 +import pytest import api.utilities as utilities -import json from helpers import data_builder as builder -from uuid import uuid4 +from moon_utilities import exceptions + + +def delete_assignment_based_on_parameters(type, policy_id, pre_id=None, cat_id=None, data_id=None): + if type in ["subject_assignments", "object_assignments", "action_assignments"] and policy_id: + url = "/policies/" + policy_id + "/" + type + if pre_id: + url += "/" + pre_id + if cat_id: + url += "/" + cat_id + if data_id: + url += "/" + data_id + else: + return "" + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, url, headers=auth_headers) + return req # subject_categories_test -def get_subject_assignment(client, policy_id): - req = client.get("/policies/{}/subject_assignments".format(policy_id)) +def get_subject_assignment(policy_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(assignments, "/policies/{}/subject_assignments".format(policy_id), headers=auth_headers) subject_assignment = utilities.get_json(req.data) return req, subject_assignment -def add_subject_assignment(client): +def add_subject_assignment(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -27,34 +68,41 @@ def add_subject_assignment(client): "category_id": subject_category_id, "data_id": data_id } - req = client.post("/policies/{}/subject_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/subject_assignments/".format(policy_id), + body=data, headers=auth_headers) subject_assignment = utilities.get_json(req.data) return req, subject_assignment -def add_subject_assignment_without_cat_id(client): +def add_subject_assignment_without_cat_id(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} data = { "id": "subject_id", "category_id": "", "data_id": "data_id" } - req = client.post("/policies/{}/subject_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/subject_assignments".format("1111"), body=data, + headers=auth_headers) subject_assignment = utilities.get_json(req.data) return req, subject_assignment -def delete_subject_assignment(client, policy_id, sub_id, cat_id,data_id): - req = client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_id, sub_id, cat_id,data_id)) +def delete_subject_assignment(policy_id, sub_id, cat_id, data_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, "/policies/{}/subject_assignments/{}/{}/{}".format( + policy_id, sub_id, cat_id, data_id), headers=auth_headers) return req def test_add_subject_assignment(): - client = utilities.register_client() - req, subject_assignment = add_subject_assignment(client) - assert req.status_code == 200 + req, subject_assignment = add_subject_assignment() + assert req.status == hug.HTTP_200 assert isinstance(subject_assignment, dict) assert "subject_assignments" in subject_assignment @@ -62,50 +110,97 @@ def test_add_subject_assignment(): # def test_add_subject_assignment_without_cat_id(): # client = utilities.register_client() # req, subject_assignment = add_subject_assignment_without_cat_id(client) -# assert req.status_code == 400 +# assert req.status == hug.HTTP_400 # assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" def test_get_subject_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_subject_assignment() - req, subject_assignment = get_subject_assignment(client, policy_id) - assert req.status_code == 200 + req, subject_assignment = get_subject_assignment(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(subject_assignment, dict) assert "subject_assignments" in subject_assignment def test_delete_subject_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_subject_assignment() - req, subject_assignment = get_subject_assignment(client, policy_id) + req, subject_assignment = get_subject_assignment(policy_id) + value = subject_assignment["subject_assignments"] + _id = list(value.keys())[0] + success_req = delete_subject_assignment( + policy_id, + value[_id]['subject_id'], + value[_id]['category_id'], + value[_id]['assignments'][0]) + assert success_req.status == hug.HTTP_200 + + +def test_delete_subject_assignment_using_policy(): + policy_id = builder.get_policy_id_with_subject_assignment() + req, subject_assignment = get_subject_assignment(policy_id) value = subject_assignment["subject_assignments"] _id = list(value.keys())[0] - success_req = delete_subject_assignment(client, - policy_id, - value[_id]['subject_id'], - value[_id]['category_id'], - value[_id]['assignments'][0]) - assert success_req.status_code == 200 + success_req = delete_assignment_based_on_parameters( + "subject_assignments", + policy_id) + assert success_req.status == hug.HTTP_200 + + +def test_delete_subject_assignment_using_policy_perimeter_id(): + policy_id = builder.get_policy_id_with_subject_assignment() + req, subject_assignment = get_subject_assignment(policy_id) + value = subject_assignment["subject_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "subject_assignments", + policy_id, + value[_id]['subject_id']) + assert success_req.status == hug.HTTP_200 + + +def test_delete_subject_assignment_using_policy_perimeter_id_category_id(): + policy_id = builder.get_policy_id_with_subject_assignment() + req, subject_assignment = get_subject_assignment(policy_id) + value = subject_assignment["subject_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "subject_assignments", + policy_id, + value[_id]['subject_id'], + value[_id]['category_id']) + assert success_req.status == hug.HTTP_200 def test_delete_subject_assignment_without_policy_id(): - client = utilities.register_client() - success_req = delete_subject_assignment(client, "", "id1", "111", "data_id1") - assert success_req.status_code == 404 + + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + success_req = delete_subject_assignment("", "id1", "111", "data_id1") + + assert '400: Policy Unknown' == str(exception_info.value) + + # assert success_req.status == hug.HTTP_400 + # assert success_req.data["message"] == "400: Policy Unknown" # --------------------------------------------------------------------------- # object_categories_test -def get_object_assignment(client, policy_id): - req = client.get("/policies/{}/object_assignments".format(policy_id)) +def get_object_assignment(policy_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(assignments, "/policies/{}/object_assignments".format(policy_id), headers=auth_headers) object_assignment = utilities.get_json(req.data) return req, object_assignment -def add_object_assignment(client): +def add_object_assignment(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -120,84 +215,135 @@ def add_object_assignment(client): "data_id": data_id } - req = client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/object_assignments".format(policy_id), + body=data, headers=auth_headers) object_assignment = utilities.get_json(req.data) return req, object_assignment -def add_object_assignment_without_cat_id(client): +def add_object_assignment_without_cat_id(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} data = { "id": "object_id", "category_id": "", "data_id": "data_id" } - req = client.post("/policies/{}/object_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/object_assignments".format("1111"), + body=data, headers=auth_headers) object_assignment = utilities.get_json(req.data) return req, object_assignment -def delete_object_assignment(client, policy_id, obj_id, cat_id, data_id): - req = client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_id, obj_id, cat_id, data_id)) +def delete_object_assignment(policy_id, obj_id, cat_id, data_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, "/policies/{}/object_assignments/{}/{}/{}".format( + policy_id, obj_id, cat_id, data_id), headers=auth_headers) return req def test_get_object_assignment(): policy_id = builder.get_policy_id_with_object_assignment() - client = utilities.register_client() - req, object_assignment = get_object_assignment(client, policy_id) - assert req.status_code == 200 + + req, object_assignment = get_object_assignment(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(object_assignment, dict) assert "object_assignments" in object_assignment def test_add_object_assignment(): - client = utilities.register_client() - req, object_assignment = add_object_assignment(client) - assert req.status_code == 200 + req, object_assignment = add_object_assignment() + assert req.status == hug.HTTP_200 assert "object_assignments" in object_assignment # def test_add_object_assignment_without_cat_id(): # client = utilities.register_client() # req, object_assignment = add_object_assignment_without_cat_id(client) -# assert req.status_code == 400 +# assert req.status == hug.HTTP_400 # assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" def test_delete_object_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_object_assignment() - req, object_assignment = get_object_assignment(client, policy_id) + req, object_assignment = get_object_assignment(policy_id) value = object_assignment["object_assignments"] _id = list(value.keys())[0] - success_req = delete_object_assignment(client, - policy_id, + success_req = delete_object_assignment(policy_id, value[_id]['object_id'], value[_id]['category_id'], value[_id]['assignments'][0]) - assert success_req.status_code == 200 + assert success_req.status == hug.HTTP_200 + + +def test_delete_object_assignment_using_policy(): + policy_id = builder.get_policy_id_with_object_assignment() + req, object_assignment = get_object_assignment(policy_id) + value = object_assignment["object_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "object_assignments", + policy_id) + assert success_req.status == hug.HTTP_200 + + +def test_delete_object_assignment_using_policy_perimeter_id(): + policy_id = builder.get_policy_id_with_object_assignment() + req, object_assignment = get_object_assignment(policy_id) + value = object_assignment["object_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "object_assignments", + policy_id, + value[_id]['object_id']) + assert success_req.status == hug.HTTP_200 + + +def test_delete_object_assignment_using_policy_perimeter_id_category_id(): + policy_id = builder.get_policy_id_with_object_assignment() + req, object_assignment = get_object_assignment(policy_id) + value = object_assignment["object_assignments"] + _id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "object_assignments", + policy_id, + value[_id]['object_id'], + value[_id]['category_id']) + assert success_req.status == hug.HTTP_200 def test_delete_object_assignment_without_policy_id(): - client = utilities.register_client() - success_req = delete_object_assignment(client, "", "id1", "111", "data_id1") - assert success_req.status_code == 404 + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + success_req = delete_object_assignment("", "id1", "111", "data_id1") + # assert success_req.status == hug.HTTP_400 + # assert success_req.data["message"] == "400: Policy Unknown" + assert '400: Policy Unknown' == str(exception_info.value) # --------------------------------------------------------------------------- # action_categories_test -def get_action_assignment(client, policy_id): - req = client.get("/policies/{}/action_assignments".format(policy_id)) +def get_action_assignment(policy_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(assignments, "/policies/{}/action_assignments".format(policy_id), headers=auth_headers) action_assignment = utilities.get_json(req.data) return req, action_assignment -def add_action_assignment(client): +def add_action_assignment(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -211,70 +357,113 @@ def add_action_assignment(client): "category_id": action_category_id, "data_id": data_id } - req = client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/action_assignments".format(policy_id), + body=data, + headers=auth_headers) action_assignment = utilities.get_json(req.data) return req, action_assignment -def add_action_assignment_without_cat_id(client): +def add_action_assignment_without_cat_id(): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} data = { "id": "action_id", "category_id": "", "data_id": "data_id" } - req = client.post("/policies/{}/action_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(assignments, "/policies/{}/action_assignments".format("1111"), + body=data, headers=auth_headers) action_assignment = utilities.get_json(req.data) return req, action_assignment -def delete_action_assignment(client, policy_id, action_id, cat_id, data_id): - req = client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_id, action_id, cat_id, data_id)) +def delete_action_assignment(policy_id, action_id, cat_id, data_id): + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(assignments, "/policies/{}/action_assignments/{}/{}/{}".format( + policy_id, action_id, cat_id, data_id), headers=auth_headers) return req def test_get_action_assignment(): policy_id = builder.get_policy_id_with_action_assignment() - client = utilities.register_client() - req, action_assignment = get_action_assignment(client, policy_id) - assert req.status_code == 200 + req, action_assignment = get_action_assignment(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(action_assignment, dict) assert "action_assignments" in action_assignment def test_add_action_assignment(): - client = utilities.register_client() - req, action_assignment = add_action_assignment(client) - assert req.status_code == 200 + req, action_assignment = add_action_assignment() + assert req.status == hug.HTTP_200 assert "action_assignments" in action_assignment # def test_add_action_assignment_without_cat_id(): # client = utilities.register_client() # req, action_assignment = add_action_assignment_without_cat_id(client) -# assert req.status_code == 400 +# assert req.status == hug.HTTP_400 # assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" def test_delete_action_assignment(): - client = utilities.register_client() policy_id = builder.get_policy_id_with_action_assignment() - req, action_assignment = get_action_assignment(client, policy_id) + req, action_assignment = get_action_assignment(policy_id) value = action_assignment["action_assignments"] id = list(value.keys())[0] - success_req = delete_action_assignment(client, - policy_id, + success_req = delete_action_assignment(policy_id, value[id]['action_id'], value[id]['category_id'], value[id]['assignments'][0]) - assert success_req.status_code == 200 + assert success_req.status == hug.HTTP_200 + + +def test_delete_action_assignment_policy(): + policy_id = builder.get_policy_id_with_action_assignment() + req, action_assignment = get_action_assignment(policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "action_assignments", + policy_id) + assert success_req.status == hug.HTTP_200 + + +def test_delete_action_assignment_policy_perimeter_id(): + policy_id = builder.get_policy_id_with_action_assignment() + req, action_assignment = get_action_assignment(policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "action_assignments", + policy_id, + value[id]['action_id']) + assert success_req.status == hug.HTTP_200 + + +def test_delete_action_assignment_policy_perimeter_id_category_id(): + policy_id = builder.get_policy_id_with_action_assignment() + req, action_assignment = get_action_assignment(policy_id) + value = action_assignment["action_assignments"] + id = list(value.keys())[0] + success_req = delete_assignment_based_on_parameters( + "action_assignments", + policy_id, + value[id]['action_id'], + value[id]['category_id']) + assert success_req.status == hug.HTTP_200 def test_delete_action_assignment_without_policy_id(): - client = utilities.register_client() - success_req = delete_action_assignment(client, "", "id1", "111", "data_id1") - assert success_req.status_code == 404 + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + success_req = delete_action_assignment("", "id1", "111", "data_id1") + # assert success_req.status == hug.HTTP_400 + # assert success_req.data["message"] == "400: Policy Unknown" + assert '400: Policy Unknown' == str(exception_info.value) # --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_assignemnt.py b/moon_manager/tests/unit_python/api/test_assignemnt.py deleted file mode 100644 index 22c727af..00000000 --- a/moon_manager/tests/unit_python/api/test_assignemnt.py +++ /dev/null @@ -1,270 +0,0 @@ -import api.utilities as utilities -import json -from helpers import data_builder as builder -from uuid import uuid4 - - -# subject_categories_test - - -def get_subject_assignment(client, policy_id): - req = client.get("/policies/{}/subject_assignments".format(policy_id)) - subject_assignment = utilities.get_json(req.data) - return req, subject_assignment - - -def add_subject_assignment(client): - subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( - subject_category_name="subject_category1" + uuid4().hex, - object_category_name="object_category1" + uuid4().hex, - action_category_name="action_category1" + uuid4().hex, - meta_rule_name="meta_rule_1" + uuid4().hex) - subject_id = builder.create_subject(policy_id) - data_id = builder.create_subject_data(policy_id=policy_id, category_id=subject_category_id) - - data = { - "id": subject_id, - "category_id": subject_category_id, - "data_id": data_id - } - req = client.post("/policies/{}/subject_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - subject_assignment = utilities.get_json(req.data) - return req, subject_assignment - - -def add_subject_assignment_without_cat_id(client): - - data = { - "id": "subject_id", - "category_id": "", - "data_id": "data_id" - } - req = client.post("/policies/{}/subject_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - subject_assignment = utilities.get_json(req.data) - return req, subject_assignment - - -def delete_subject_assignment(client, policy_id, sub_id, cat_id,data_id): - req = client.delete("/policies/{}/subject_assignments/{}/{}/{}".format(policy_id, sub_id, cat_id,data_id)) - return req - - -def test_add_subject_assignment(): - client = utilities.register_client() - req, subject_assignment = add_subject_assignment(client) - assert req.status_code == 200 - assert isinstance(subject_assignment, dict) - assert "subject_assignments" in subject_assignment - - -def test_add_subject_assignment_without_cat_id(): - client = utilities.register_client() - req, subject_assignment = add_subject_assignment_without_cat_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" - - -def test_get_subject_assignment(): - client = utilities.register_client() - policy_id = builder.get_policy_id_with_subject_assignment() - req, subject_assignment = get_subject_assignment(client, policy_id) - assert req.status_code == 200 - assert isinstance(subject_assignment, dict) - assert "subject_assignments" in subject_assignment - - -def test_delete_subject_assignment(): - client = utilities.register_client() - policy_id = builder.get_policy_id_with_subject_assignment() - req, subject_assignment = get_subject_assignment(client, policy_id) - value = subject_assignment["subject_assignments"] - id = list(value.keys())[0] - success_req = delete_subject_assignment(client, policy_id, value[id]['subject_id'], value[id]['category_id'],value[id]['assignments'][0]) - assert success_req.status_code == 200 - - -def test_delete_subject_assignment_without_policy_id(): - client = utilities.register_client() - success_req = delete_subject_assignment(client, "", "id1", "111" ,"data_id1") - assert success_req.status_code == 404 - - -# --------------------------------------------------------------------------- - -# object_categories_test - - -def get_object_assignment(client, policy_id): - req = client.get("/policies/{}/object_assignments".format(policy_id)) - object_assignment = utilities.get_json(req.data) - return req, object_assignment - - -def add_object_assignment(client): - subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( - subject_category_name="subject_category1" + uuid4().hex, - object_category_name="object_category1" + uuid4().hex, - action_category_name="action_category1" + uuid4().hex, - meta_rule_name="meta_rule_1" + uuid4().hex) - object_id = builder.create_object(policy_id) - data_id = builder.create_object_data(policy_id=policy_id, category_id=object_category_id) - - data = { - "id": object_id, - "category_id": object_category_id, - "data_id": data_id - } - - req = client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - object_assignment = utilities.get_json(req.data) - return req, object_assignment - - -def add_object_assignment_without_cat_id(client): - - data = { - "id": "object_id", - "category_id": "", - "data_id": "data_id" - } - req = client.post("/policies/{}/object_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - object_assignment = utilities.get_json(req.data) - return req, object_assignment - - -def delete_object_assignment(client, policy_id, obj_id, cat_id, data_id): - req = client.delete("/policies/{}/object_assignments/{}/{}/{}".format(policy_id, obj_id, cat_id, data_id)) - return req - - -def test_get_object_assignment(): - policy_id = builder.get_policy_id_with_object_assignment() - client = utilities.register_client() - req, object_assignment = get_object_assignment(client, policy_id) - assert req.status_code == 200 - assert isinstance(object_assignment, dict) - assert "object_assignments" in object_assignment - - -def test_add_object_assignment(): - client = utilities.register_client() - req, object_assignment = add_object_assignment(client) - assert req.status_code == 200 - assert "object_assignments" in object_assignment - - -def test_add_object_assignment_without_cat_id(): - client = utilities.register_client() - req, object_assignment = add_object_assignment_without_cat_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" - - -def test_delete_object_assignment(): - client = utilities.register_client() - policy_id = builder.get_policy_id_with_object_assignment() - req, object_assignment = get_object_assignment(client, policy_id) - value = object_assignment["object_assignments"] - id = list(value.keys())[0] - success_req = delete_object_assignment(client, policy_id, value[id]['object_id'], value[id]['category_id'],value[id]['assignments'][0]) - assert success_req.status_code == 200 - - -def test_delete_object_assignment_without_policy_id(): - client = utilities.register_client() - success_req = delete_object_assignment(client, "", "id1", "111","data_id1") - assert success_req.status_code == 404 - - -# --------------------------------------------------------------------------- - -# action_categories_test - - -def get_action_assignment(client, policy_id): - req = client.get("/policies/{}/action_assignments".format(policy_id)) - action_assignment = utilities.get_json(req.data) - return req, action_assignment - - -def add_action_assignment(client): - subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( - subject_category_name="subject_category1" + uuid4().hex, - object_category_name="object_category1" + uuid4().hex, - action_category_name="action_category1" + uuid4().hex, - meta_rule_name="meta_rule_1" + uuid4().hex) - action_id = builder.create_action(policy_id) - data_id = builder.create_action_data(policy_id=policy_id, category_id=action_category_id) - - data = { - "id": action_id, - "category_id": action_category_id, - "data_id": data_id - } - req = client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - action_assignment = utilities.get_json(req.data) - return req, action_assignment - - -def add_action_assignment_without_cat_id(client): - - data = { - "id": "action_id", - "category_id": "", - "data_id": "data_id" - } - req = client.post("/policies/{}/action_assignments".format("1111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - action_assignment = utilities.get_json(req.data) - return req, action_assignment - - -def delete_action_assignment(client, policy_id, action_id, cat_id, data_id): - req = client.delete("/policies/{}/action_assignments/{}/{}/{}".format(policy_id, action_id, cat_id, data_id)) - return req - - -def test_get_action_assignment(): - policy_id = builder.get_policy_id_with_action_assignment() - client = utilities.register_client() - req, action_assignment = get_action_assignment(client, policy_id) - assert req.status_code == 200 - assert isinstance(action_assignment, dict) - assert "action_assignments" in action_assignment - - -def test_add_action_assignment(): - client = utilities.register_client() - req, action_assignment = add_action_assignment(client) - assert req.status_code == 200 - assert "action_assignments" in action_assignment - - -def test_add_action_assignment_without_cat_id(): - client = utilities.register_client() - req, action_assignment = add_action_assignment_without_cat_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'category_id', [Empty String]" - - -def test_delete_action_assignment(): - client = utilities.register_client() - policy_id = builder.get_policy_id_with_action_assignment() - req, action_assignment = get_action_assignment(client, policy_id) - value = action_assignment["action_assignments"] - id = list(value.keys())[0] - success_req = delete_action_assignment(client, policy_id, value[id]['action_id'], value[id]['category_id'],value[id]['assignments'][0]) - assert success_req.status_code == 200 - - -def test_delete_action_assignment_without_policy_id(): - client = utilities.register_client() - success_req = delete_action_assignment(client, "", "id1", "111" ,"data_id1") - assert success_req.status_code == 404 - -# --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_auth.py b/moon_manager/tests/unit_python/api/test_auth.py new file mode 100644 index 00000000..ee59bf5e --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_auth.py @@ -0,0 +1,71 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from falcon import HTTP_200, HTTP_204, HTTP_401 +import hug +import base64 +from uuid import uuid4 +from helpers import data_builder as builder + + +def test_get_auth(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import auth + from moon_manager.api import policy + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + key = req.data + assert get_api_key_for_user("admin") == req.data + headers = {"x-api-key": key} + req = hug.test.get(policy, 'policies/', headers=headers) + assert req.status == HTTP_200 + + +def test_del_auth(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import auth + from moon_manager.api import policy + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + key = req.data + headers = {"x-api-key": key} + req = hug.test.delete(auth, 'auth/', headers=headers) + assert req.status == HTTP_204 + req = hug.test.get(policy, 'policies/', headers=headers) + assert req.status == HTTP_401 + assert not get_api_key_for_user("admin") + + +def test_readd_auth(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import auth + from moon_manager.api import policy + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + key = req.data + headers = {"x-api-key": key} + req = hug.test.delete(auth, 'auth/', headers=headers) + assert req.status == HTTP_204 + headers = {"Authorization": "Basic {}".format(base64.b64encode(b"admin:admin").decode("utf-8"))} + req = hug.test.get(auth, 'auth/', headers=headers) + assert req.status == HTTP_200 + new_key = req.data + headers = {"x-api-key": new_key} + req = hug.test.get(policy, 'policies/', headers=headers) + assert req.status == HTTP_200 + assert get_api_key_for_user("admin") + assert get_api_key_for_user("admin") == new_key + assert get_api_key_for_user("admin") != key + diff --git a/moon_manager/tests/unit_python/api/test_data.py b/moon_manager/tests/unit_python/api/test_data.py index 433f69e6..019a8b45 100644 --- a/moon_manager/tests/unit_python/api/test_data.py +++ b/moon_manager/tests/unit_python/api/test_data.py @@ -1,59 +1,83 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + -import api.utilities as utilities import json -from helpers import data_builder as builder from uuid import uuid4 +import hug +import pytest +from helpers import data_builder as builder +from helpers import policy_helper +from moon_utilities import exceptions + + # subject_categories_test -def get_subject_data(client, policy_id, category_id=None): +def get_subject_data(policy_id, category_id=None): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if category_id is None: - req = client.get("/policies/{}/subject_data".format(policy_id)) + req = hug.test.get(data, "/policies/{}/subject_data".format(policy_id), headers=auth_headers) else: - req = client.get("/policies/{}/subject_data/{}".format(policy_id, category_id)) - subject_data = utilities.get_json(req.data) + req = hug.test.get(data, "/policies/{}/subject_data/{}".format(policy_id, category_id), headers=auth_headers) + subject_data = req.data return req, subject_data -def add_subject_data(client, name): +def add_subject_data(name): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, action_category_name="action_category1" + uuid4().hex, meta_rule_name="meta_rule_1" + uuid4().hex) - data = { + body = { "name": name, "description": "description of {}".format(name) } - req = client.post("/policies/{}/subject_data/{}".format(policy_id, subject_category_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - subject_data = utilities.get_json(req.data) + req = hug.test.post(data, "/policies/{}/subject_data/{}".format(policy_id, subject_category_id), + body=json.dumps(body), + headers={'Content-Type': 'application/json', "X-Api-Key": get_api_key_for_user("admin")}) + subject_data = req.data return req, subject_data -def delete_subject_data(client, policy_id, category_id, data_id): - req = client.delete("/policies/{}/subject_data/{}/{}".format(policy_id,category_id,data_id)) +def delete_subject_data(policy_id, category_id, data_id): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(data, "/policies/{}/subject_data/{}/{}".format(policy_id, category_id, + data_id), headers=auth_headers) return req def test_get_subject_data(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, subject_data = get_subject_data(client, policy_id) - assert req.status_code == 200 + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + req, subject_data = get_subject_data(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(subject_data, dict) assert "subject_data" in subject_data def test_add_subject_data(): - client = utilities.register_client() - req, subject_data = add_subject_data(client, "testuser") - assert req.status_code == 200 + req, subject_data = add_subject_data("testuser") + assert req.status == hug.HTTP_200 assert isinstance(subject_data, dict) value = subject_data["subject_data"]['data'] assert "subject_data" in subject_data @@ -62,73 +86,97 @@ def test_add_subject_data(): assert value[id]['description'] == "description of {}".format("testuser") +def test_add_subject_data_invalid_name(): + with pytest.raises(exceptions.DataContentError) as exception_info: + req, subject_data = add_subject_data(" ") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + with pytest.raises(exceptions.DataContentError) as exception_info: + req, subject_data = add_subject_data("") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + + def test_delete_subject_data(): - client = utilities.register_client() - subject_category_id, object_category_id, action_category_id, meta_rule_id,policy_id = builder.create_new_policy() - data_id = builder.create_subject_data(policy_id,subject_category_id) - success_req = delete_subject_data(client, policy_id, subject_category_id, data_id ) - assert success_req.status_code == 200 + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + data_id = builder.create_subject_data(policy_id, subject_category_id) + success_req = delete_subject_data(policy_id, subject_category_id, data_id) + assert success_req.status == hug.HTTP_200 def test_add_subject_data_with_forbidden_char_in_user(): - client = utilities.register_client() - req, subject_data = add_subject_data(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_data = add_subject_data("<a>") + # assert '400: Invalid Content' == str(exception_info.value) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_delete_subject_data_without_policy_id(): - client = utilities.register_client() - success_req = delete_subject_data(client, "", "", "") - assert success_req.status_code == 404 + success_req = delete_subject_data("", "", "") + assert success_req.status == hug.HTTP_405 + # --------------------------------------------------------------------------- # object_categories_test -def get_object_data(client, policy_id, category_id=None): +def get_object_data(policy_id, category_id=None): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if category_id is None: - req = client.get("/policies/{}/object_data".format(policy_id)) + req = hug.test.get(data, "/policies/{}/object_data".format(policy_id), headers=auth_headers) else: - req = client.get("/policies/{}/object_data/{}".format(policy_id, category_id)) - object_data = utilities.get_json(req.data) + req = hug.test.get(data, "/policies/{}/object_data/{}".format(policy_id, category_id), headers=auth_headers) + object_data = req.data return req, object_data -def add_object_data(client, name): +def add_object_data(name): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, action_category_name="action_category1" + uuid4().hex, meta_rule_name="meta_rule_1" + uuid4().hex) - data = { + body = { "name": name, "description": "description of {}".format(name) } - req = client.post("/policies/{}/object_data/{}".format(policy_id, object_category_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - object_data = utilities.get_json(req.data) + req = hug.test.post(data, "/policies/{}/object_data/{}".format(policy_id, object_category_id), + body=json.dumps(body), headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + object_data = req.data return req, object_data -def delete_object_data(client, policy_id, category_id, data_id): - req = client.delete("/policies/{}/object_data/{}/{}".format(policy_id, category_id, data_id)) +def delete_object_data(policy_id, category_id, data_id): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(data, "/policies/{}/object_data/{}/{}".format(policy_id, category_id, + data_id), headers=auth_headers) return req def test_get_object_data(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, object_data = get_object_data(client, policy_id) - assert req.status_code == 200 + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + req, object_data = get_object_data(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(object_data, dict) assert "object_data" in object_data def test_add_object_data(): - client = utilities.register_client() - req, object_data = add_object_data(client, "testuser") - assert req.status_code == 200 + req, object_data = add_object_data("testuser") + assert req.status == hug.HTTP_200 assert isinstance(object_data, dict) value = object_data["object_data"]['data'] assert "object_data" in object_data @@ -137,75 +185,100 @@ def test_add_object_data(): assert value[_id]['description'] == "description of {}".format("testuser") -def test_delete_object_data(): - client = utilities.register_client() +def test_add_object_data_invalid_name(): + with pytest.raises(exceptions.DataContentError) as exception_info: + req, object_data = add_object_data(" ") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + with pytest.raises(exceptions.DataContentError): + req, object_data = add_object_data("") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + +def test_delete_object_data(): subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() data_id = builder.create_object_data(policy_id, object_category_id) - - success_req = delete_object_data(client, policy_id, data_id, object_category_id) - assert success_req.status_code == 200 + success_req = delete_object_data(policy_id, data_id, object_category_id) + assert success_req.status == hug.HTTP_200 def test_add_object_data_with_forbidden_char_in_user(): - client = utilities.register_client() - req, subject_data = add_object_data(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_data = add_object_data("<a>") + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + # assert '400: Invalid Content' == str(exception_info.value) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) def test_delete_object_data_without_policy_id(): - client = utilities.register_client() - success_req = delete_object_data(client, "", "", "") - assert success_req.status_code == 404 + success_req = delete_object_data("", "", "") + assert success_req.status == hug.HTTP_405 + # --------------------------------------------------------------------------- # action_categories_test -def get_action_data(client, policy_id, category_id=None): +def get_action_data(policy_id, category_id=None): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if category_id is None: - req = client.get("/policies/{}/action_data".format(policy_id)) + req = hug.test.get(data, "/policies/{}/action_data".format(policy_id), + headers=auth_headers) else: - req = client.get("/policies/{}/action_data/{}".format(policy_id, category_id)) - action_data = utilities.get_json(req.data) + req = hug.test.get(data, "/policies/{}/action_data/{}".format(policy_id, category_id), + headers=auth_headers) + action_data = req.data return req, action_data -def add_action_data(client, name): +def add_action_data(name): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, action_category_name="action_category1" + uuid4().hex, meta_rule_name="meta_rule_1" + uuid4().hex) - data = { + body = { "name": name, "description": "description of {}".format(name) } - req = client.post("/policies/{}/action_data/{}".format(policy_id, action_category_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - action_data = utilities.get_json(req.data) + req = hug.test.post(data, "/policies/{}/action_data/{}".format(policy_id, action_category_id), + body=json.dumps(body), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + action_data = req.data return req, action_data -def delete_action_data(client, policy_id, categorgy_id, data_id): - req = client.delete("/policies/{}/action_data/{}/{}".format(policy_id, categorgy_id, data_id)) +def delete_action_data(policy_id, categorgy_id, data_id): + from moon_manager.api import data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.delete(data, "/policies/{}/action_data/{}/{}".format(policy_id, categorgy_id, + data_id), headers=auth_headers) return req def test_get_action_data(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, action_data = get_action_data(client, policy_id) - assert req.status_code == 200 + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + req, action_data = get_action_data(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(action_data, dict) assert "action_data" in action_data def test_add_action_data(): - client = utilities.register_client() - req, action_data = add_action_data(client, "testuser") - assert req.status_code == 200 + req, action_data = add_action_data("testuser") + assert req.status == hug.HTTP_200 assert isinstance(action_data, dict) value = action_data["action_data"]['data'] assert "action_data" in action_data @@ -214,26 +287,35 @@ def test_add_action_data(): assert value[id]['description'] == "description of {}".format("testuser") -def test_delete_action_data(): - client = utilities.register_client() +def test_add_action_data_invalid_name(): - subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() - data_id = builder.create_action_data(policy_id, action_category_id) + with pytest.raises(exceptions.DataContentError)as exception_info: + req, action_data = add_action_data(" ") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) + with pytest.raises(exceptions.DataContentError) as exception_info: + req, action_data = add_action_data("") + # assert req.status == hug.HTTP_400 + assert '400: Data Content Error' == str(exception_info.value) - success_req = delete_action_data(client, policy_id, data_id, action_category_id) - assert success_req.status_code == 200 +def test_delete_action_data(): + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + data_id = builder.create_action_data(policy_id, action_category_id) + success_req = delete_action_data(policy_id, data_id, action_category_id) + assert success_req.status == hug.HTTP_200 def test_add_action_data_with_forbidden_char_in_user(): - client = utilities.register_client() - req, action_data = add_action_data(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, action_data = add_action_data("<a>") + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + # assert '400: Invalid Content' == str(exception_info.value) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) def test_delete_action_data_without_policy_id(): - client = utilities.register_client() - success_req = delete_action_data(client, "", "", "") - assert success_req.status_code == 404 + success_req = delete_action_data("", "", "") + assert success_req.status == hug.HTTP_405 # --------------------------------------------------------------------------- diff --git a/moon_manager/tests/unit_python/api/test_import.py b/moon_manager/tests/unit_python/api/test_import.py deleted file mode 100644 index af5f753a..00000000 --- a/moon_manager/tests/unit_python/api/test_import.py +++ /dev/null @@ -1,510 +0,0 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. - -import api.utilities as utilities -import api.test_unit_models as test_models -import api.test_policies as test_policies -import api.test_meta_data as test_categories -import api.test_data as test_data -import api.test_meta_rules as test_meta_rules -import api.test_assignement as test_assignments -import api.test_rules as test_rules -import api.import_export_utilities as import_export_utilities - -import json - - -MODEL_WITHOUT_META_RULES = [ - {"models": [{"name": "test model", "description": "", "meta_rules": []}]}, - {"models": [{"name": "test model", "description": "new description", "meta_rules": [], "override": True}]}, - {"models": [{"name": "test model", "description": "description not taken into account", "meta_rules": [], "override": False}]} - ] - -POLICIES = [ - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "new description not taken into account", "model": {"name" : "test model"}, "mandatory": True}]}, - {"policies": [{"name": "test policy", "genre": "not authz ?", "description": "generates an exception", "model": {"name" : "test model"}, "override": True}]}, - {"models": [{"name": "test model", "description": "", "meta_rules": []}], "policies": [{"name": "test policy", "genre": "not authz ?", "description": "changes taken into account", "model": {"name" : "test model"}, "override": True}]}, -] - -SUBJECTS = [{"subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": []}]}, - {"subjects": [{"name": "testuser", "description": "new description of the subject", "extra": {"email": "new-email@test.com"}, "policies": [{"name": "test other policy"}]}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": [{"name": "test policy"}]}]}] - - -OBJECTS = [ - {"objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], - "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}], - "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": []}]}, - {"objects": [{"name": "test object", "description": "new description of the object", - "extra": {"test": "test extra"}, - "policies": [{"name": "test other policy"}]}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], - "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": [{"name": "test policy"}]}]}, -] - - -ACTIONS = [{"actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]}, - {"policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {}, "mandatory": True}], "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": []}]}, - {"actions": [{"name": "test action", "description": "new description of the action", "extra": {"test": "test extra"}, "policies": [{"name": "test other policy"}]}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {}, "mandatory": False}], "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": [{"name": "test policy"}]}]}] - - -SUBJECT_CATEGORIES = [{"subject_categories": [{"name": "test subject categories", "description": "subject category description"}]}, - {"subject_categories": [{"name": "test subject categories", "description": "new subject category description"}]}] - - -OBJECT_CATEGORIES = [{"object_categories": [{"name": "test object categories", "description": "object category description"}]}, - {"object_categories": [{"name": "test object categories", "description": "new object category description"}]}] - - -ACTION_CATEGORIES = [{"action_categories": [{"name": "test action categories", "description": "action category description"}]}, - {"action_categories": [{"name": "test action categories", "description": "new action category description"}]}] - -# meta_rules import is needed otherwise the search for data do not work !!! -PRE_DATA = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "good meta rule"}, {"name": "other good meta rule"}]}], - "policies": [{"name": "test other policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}, {"name": "other test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}, {"name": "other test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}, {"name": "other test action categories", "description": "action category description"}], - "meta_rules": [{"name": "good meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}, - {"name": "other good meta rule", "description": "valid meta rule", "subject_categories": [{"name": "other test subject categories"}], "object_categories": [{"name": "other test object categories"}], "action_categories": [{"name": "other test action categories"}]}]} - -SUBJECT_DATA = [{"subject_data": [{"name": "not valid subject data", "description": "", "policies": [{}], "category": {}}]}, - {"subject_data": [{"name": "not valid subject data", "description": "", "policies": [{}], "category": {"name": "test subject categories"}}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], "subject_data": [{"name": "one valid subject data", "description": "description", "policies": [{}], "category": {"name": "test subject categories"}}]}, - {"subject_data": [{"name": "valid subject data", "description": "description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}]}, - {"subject_data": [{"name": "valid subject data", "description": "new description", "policies": [{"name": "test other policy"}], "category": {"name": "test subject categories"}}]}] - -OBJECT_DATA = [{"object_data": [{"name": "not valid object data", "description": "", "policies": [{}], "category": {}}]}, - {"object_data": [{"name": "not valid object data", "description": "", "policies": [{}], "category": {"name": "test object categories"}}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], "object_data": [{"name": "one valid object data", "description": "description", "policies": [{}], "category": {"name": "test object categories"}}]}, - {"object_data": [{"name": "valid object data", "description": "description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}]}, - {"object_data": [{"name": "valid object data", "description": "new description", "policies": [{"name": "test other policy"}], "category": {"name": "test object categories"}}]}] - - -ACTION_DATA = [{"action_data": [{"name": "not valid action data", "description": "", "policies": [{}], "category": {}}]}, - {"action_data": [{"name": "not valid action data", "description": "", "policies": [{}], "category": {"name": "test action categories"}}]}, - {"policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name": "test model"}, "mandatory": True}], "action_data": [{"name": "one valid action data", "description": "description", "policies": [{}], "category": {"name": "test action categories"}}]}, - {"action_data": [{"name": "valid action data", "description": "description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}]}, - {"action_data": [{"name": "valid action data", "description": "new description", "policies": [{"name": "test other policy"}], "category": {"name": "test action categories"}}]}] - - -PRE_META_RULES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "object action description"}]} - -META_RULES = [{"meta_rules" :[{"name": "bad meta rule", "description": "not valid meta rule", "subject_categories": [{"name": "not valid category"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]}, - {"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "not valid category"}], "action_categories": [{"name": "test action categories"}]}]}, - {"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "not valid category"}]}]}, - {"meta_rules": [{"name": "good meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]}] - - -PRE_ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "good meta rule"}]}], - "policies": [{"name": "test policy", "genre": "authz", "description": "description", "model": {"name" : "test model"}, "mandatory": True}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "object action description"}], - "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {}, "policies": [{"name": "test policy"}]}], - "objects": [{"name": "test object", "description": "description of the object", "extra": {}, "policies": [{"name": "test policy"}]}], - "actions": [{"name": "test action", "description": "description of the action", "extra": {}, "policies": [{"name": "test policy"}]}], - "meta_rules": [{"name": "good meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}], - "subject_data": [{"name": "subject data", "description": "test subject data", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "object data", "description": "test object data", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "action_data": [{"name": "action data", "description": "test action data", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}]} - - -SUBJECT_ASSIGNMENTS = [{"subject_assignments": [{"subject": {"name": "unknonw"}, "category" : {"name": "test subject categories"}, "assignments": [{"name": "subject data"}]}]}, - {"subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "unknown"}, "assignments": [{"name": "subject data"}]}]}, - {"subject_assignments": [{"subject": {"name": "testuser"}, "category" : {"name": "test subject categories"}, "assignments": [{"name": "unknwon"}]}]}, - {"subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "test subject categories"}, "assignments": [{"name": "subject data"}]}]}] - -OBJECT_ASSIGNMENTS = [{"object_assignments": [{"object": {"name": "unknown"}, "category" : {"name": "test object categories"}, "assignments": [{"name": "object data"}]}]}, - {"object_assignments": [{"object": {"name": "test object"}, "category" : {"name": "unknown"}, "assignments": [{"name": "object data"}]}]}, - {"object_assignments": [{"object": {"name": "test object"}, "category" : {"name": "test object categories"}, "assignments": [{"name": "unknown"}]}]}, - {"object_assignments": [{"object": {"name": "test object"}, "category" : {"name": "test object categories"}, "assignments": [{"name": "object data"}]}]}] - -ACTION_ASSIGNMENTS = [{"action_assignments": [{"action": {"name": "unknown"}, "category" : {"name": "test action categories"}, "assignments": [{"name": "action data"}]}]}, - {"action_assignments": [{"action": {"name": "test action"}, "category" : {"name": "unknown"}, "assignments": [{"name": "action data"}]}]}, - {"action_assignments": [{"action": {"name": "test action"}, "category" : {"name": "test action categories"}, "assignments": [{"name": "unknown"}]}]}, - {"action_assignments": [{"action": {"name": "test action"}, "category" : {"name": "test action categories"}, "assignments": [{"name": "action data"}]}]}] - -RULES = [{"rules": [{"meta_rule": {"name": "unknown meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "unknown policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "unknown subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "unknown object data"}], "action_data": [{"name": "action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "unknown action data"}]}}]}, - {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, "instructions": {"decision": "grant"}, "enabled": True, "rule": {"subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], "action_data": [{"name": "action data"}]}}]}] - - -def test_import_models_without_new_meta_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - counter = 0 - for models_description in MODEL_WITHOUT_META_RULES: - req = client.post("/import", content_type='application/json', data=json.dumps(models_description)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - req, models = test_models.get_models(client) - models = models["models"] - assert len(list(models.keys())) == 1 - values = list(models.values()) - assert values[0]["name"] == "test model" - if counter == 0: - assert len(values[0]["description"]) == 0 - if counter == 1 or counter == 2: - assert values[0]["description"] == "new description" - counter = counter + 1 - import_export_utilities.clean_all(client) - - -def test_import_policies(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - counter = -1 - for policy_description in POLICIES: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(policy_description)) - try: - data = utilities.get_json(req.data) - assert data == "Import ok !" - except Exception: - assert counter == 2 # this is an expected failure - continue - - req, policies = test_policies.get_policies(client) - policies = policies["policies"] - assert len(list(policies.keys())) == 1 - values = list(policies.values()) - assert values[0]["name"] == "test policy" - if counter < 3: - assert values[0]["genre"] == "authz" - assert values[0]["description"] == "description" - else: - assert values[0]["genre"] == "not authz ?" - assert values[0]["description"] == "changes taken into account" - assert len(values[0]["model_id"]) > 0 - import_export_utilities.clean_all(client) - - -def test_import_subject_object_action(): - client = utilities.register_client() - type_elements = ["object", "action"] - - for type_element in type_elements: - import_export_utilities.clean_all(client) - counter = -1 - # set the getters and the comparison values - if type_element == "subject": - elements = SUBJECTS - clean_method = import_export_utilities.clean_subjects - name = "testuser" - key_extra = "email" - value_extra = "new-email@test.com" - elif type_element == "object": - elements = OBJECTS - clean_method = import_export_utilities.clean_objects - name = "test object" - key_extra = "test" - value_extra = "test extra" - else: - elements = ACTIONS - clean_method = import_export_utilities.clean_actions - name = "test action" - key_extra = "test" - value_extra = "test extra" - - for element in elements: - counter = counter + 1 - if counter == 2 or counter == 4: - clean_method(client) - - - if counter == 3: - req = client.patch("/{}s/{}".format(type_element,perimeter_id), content_type='application/json', - data=json.dumps( - element["{}s".format(type_element)][0])) - else : - req = client.post("/import", content_type='application/json', - data=json.dumps(element)) - if counter < 2: - assert req.status_code == 500 - continue - - try: - data = utilities.get_json(req.data) - except Exception as e: - assert False - #assert counter < 2 # Â this is an expected failure - #continue - - if counter != 3: - assert data == "Import ok !" - get_elements = utilities.get_json(client.get("/"+type_element + "s").data) - get_elements = get_elements[type_element + "s"] - - perimeter_id = list(get_elements.keys())[0] - - assert len(list(get_elements.keys())) == 1 - values = list(get_elements.values()) - assert values[0]["name"] == name - if counter == 2 or counter == 4: - assert values[0]["description"] == "description of the " + type_element - #assert not values[0]["extra"] - if counter == 3: - assert values[0]["description"] == "new description of the " + type_element - assert values[0]["extra"][key_extra] == value_extra - - #Â assert len(values[0]["policy_list"]) == 1 - import_export_utilities.clean_all(client) - - -def test_import_subject_object_action_categories(): - client = utilities.register_client() - type_elements = ["subject", "object", "action"] - - for type_element in type_elements: - import_export_utilities.clean_all(client) - counter = -1 - # set the getters and the comparison values - if type_element == "subject": - elements = SUBJECT_CATEGORIES - get_method = test_categories.get_subject_categories - elif type_element == "object": - elements = OBJECT_CATEGORIES - get_method = test_categories.get_object_categories - else: - elements = ACTION_CATEGORIES - get_method = test_categories.get_action_categories - - for element in elements: - req = client.post("/import", content_type='application/json', data=json.dumps(element)) - counter = counter + 1 - data = utilities.get_json(req.data) - assert data == "Import ok !" - req, get_elements = get_method(client) - get_elements = get_elements[type_element + "_categories"] - assert len(list(get_elements.keys())) == 1 - values = list(get_elements.values()) - assert values[0]["name"] == "test " + type_element + " categories" - assert values[0]["description"] == type_element + " category description" - - -def test_import_meta_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - # import some categories - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_META_RULES)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - - counter = -1 - for meta_rule in META_RULES: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(meta_rule)) - if counter != 3: - assert req.status_code == 500 - continue - else: - data = utilities.get_json(req.data) - assert data == "Import ok !" - assert req.status_code == 200 - - req, meta_rules = test_meta_rules.get_meta_rules(client) - meta_rules = meta_rules["meta_rules"] - key = list(meta_rules.keys())[0] - assert isinstance(meta_rules,dict) - assert meta_rules[key]["name"] == "good meta rule" - assert meta_rules[key]["description"] == "valid meta rule" - assert len(meta_rules[key]["subject_categories"]) == 1 - assert len(meta_rules[key]["object_categories"]) == 1 - assert len(meta_rules[key]["action_categories"]) == 1 - - subject_category_key = meta_rules[key]["subject_categories"][0] - object_category_key = meta_rules[key]["object_categories"][0] - action_category_key = meta_rules[key]["action_categories"][0] - - req, sub_cat = test_categories.get_subject_categories(client) - sub_cat = sub_cat["subject_categories"] - assert sub_cat[subject_category_key]["name"] == "test subject categories" - - req, ob_cat = test_categories.get_object_categories(client) - ob_cat = ob_cat["object_categories"] - assert ob_cat[object_category_key]["name"] == "test object categories" - - req, ac_cat = test_categories.get_action_categories(client) - ac_cat = ac_cat["action_categories"] - assert ac_cat[action_category_key]["name"] == "test action categories" - - import_export_utilities.clean_all(client) - - -def test_import_subject_object_action_assignments(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_ASSIGNMENTS)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - - type_elements = ["subject", "object", "action"] - - for type_element in type_elements: - counter = -1 - if type_element == "subject": - datas = SUBJECT_ASSIGNMENTS - get_method = test_assignments.get_subject_assignment - elif type_element == "object": - datas = OBJECT_ASSIGNMENTS - get_method = test_assignments.get_object_assignment - else: - datas = ACTION_ASSIGNMENTS - get_method = test_assignments.get_action_assignment - - for assignments in datas: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(assignments)) - if counter != 3: - assert req.status_code == 500 - continue - else: - assert data == "Import ok !" - assert req.status_code == 200 - req, policies = test_policies.get_policies(client) - for policy_key in policies["policies"]: - req, get_assignments = get_method(client, policy_key) - get_assignments = get_assignments[type_element+"_assignments"] - assert len(get_assignments) == 1 - - -def test_import_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_ASSIGNMENTS)) - data = utilities.get_json(req.data) - assert data == "Import ok !" - - counter = -1 - for rule in RULES: - counter = counter + 1 - req = client.post("/import", content_type='application/json', data=json.dumps(rule)) - - if counter < 5: - assert req.status_code == 500 - continue - - assert req.status_code == 200 - - req, rules = test_rules.test_get_rules() - rules = rules["rules"] - rules = rules["rules"] - assert len(rules) == 1 - rules = rules[0] - assert rules["enabled"] - assert rules["instructions"]["decision"] == "grant" - - req, meta_rules = test_meta_rules.get_meta_rules(client) - assert meta_rules["meta_rules"][list(meta_rules["meta_rules"].keys())[0]]["name"] == "good meta rule" - - -def test_import_subject_object_action_data(): - client = utilities.register_client() - type_elements = ["subject", "object", "action"] - - for type_element in type_elements: - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(PRE_DATA)) - counter = -1 - # set the getters and the comparison values - if type_element == "subject": - elements = SUBJECT_DATA - get_method = test_data.get_subject_data - get_categories = test_categories.get_subject_categories - elif type_element == "object": - elements = OBJECT_DATA - get_method = test_data.get_object_data - get_categories = test_categories.get_object_categories - else: - elements = ACTION_DATA - get_method = test_data.get_action_data - get_categories = test_categories.get_action_categories - - for element in elements: - req = client.post("/import", content_type='application/json', data=json.dumps(element)) - counter = counter + 1 - if counter == 0 or counter == 1: - assert req.status_code == 500 - continue - assert req.status_code == 200 - data = utilities.get_json(req.data) - assert data == "Import ok !" - - req, policies = test_policies.get_policies(client) - policies = policies["policies"] - req, categories = get_categories(client) - categories = categories[type_element + "_categories"] - case_tested = False - for policy_key in policies.keys(): - policy = policies[policy_key] - for category_key in categories: - req, get_elements = get_method(client, policy_id=policy_key, category_id=category_key) - if len(get_elements[type_element+"_data"]) == 0: - continue - - # do this because the backend gives an element with empty data if the policy_key, - # category_key couple does not have any data... - get_elements = get_elements[type_element+"_data"] - if len(get_elements[0]["data"]) == 0: - continue - - if policy["name"] == "test policy": - assert len(get_elements) == 1 - el = get_elements[0] - assert isinstance(el["data"], dict) - if counter == 2: - assert len(el["data"].keys()) == 1 - el = el["data"][list(el["data"].keys())[0]] - if "value" in el: - el = el["value"] - assert el["name"] == "one valid " + type_element + " data" - if counter == 3: - assert len(el["data"].keys()) == 2 - el1 = el["data"][list(el["data"].keys())[0]] - el2 = el["data"][list(el["data"].keys())[1]] - if "value" in el1: - el1 = el1["value"] - el2 = el2["value"] - assert (el1["name"] == "one valid " + type_element + " data" and el2["name"] == "valid " + type_element + " data") or (el2["name"] == "one valid " + type_element + " data" and el1["name"] == "valid " + type_element + " data") - assert el1["description"] == "description" - assert el2["description"] == "description" - - case_tested = True - - if policy["name"] == "test other policy": - if counter == 4: - assert len(get_elements) == 1 - el = get_elements[0] - assert isinstance(el["data"], dict) - assert len(el["data"].keys()) == 1 - el = el["data"][list(el["data"].keys())[0]] - if "value" in el: - el = el["value"] - assert el["name"] == "valid " + type_element + " data" - assert el["description"] == "new description" - case_tested = True - - assert case_tested is True - - -def test_clean(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - #restore the database as previously - utilities.get_policy_id() diff --git a/moon_manager/tests/unit_python/api/test_export.py b/moon_manager/tests/unit_python/api/test_json_export.py index ac8e8d17..8de394c9 100644 --- a/moon_manager/tests/unit_python/api/test_export.py +++ b/moon_manager/tests/unit_python/api/test_json_export.py @@ -1,55 +1,55 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + import json import api.utilities as utilities -import api.import_export_utilities as import_export_utilities - +import helpers.import_export_helper as import_export_helper +import hug MODEL_WITHOUT_META_RULES = {"models": [{"name": "test model", "description": "model description", "meta_rules": []}]} -POLICIES = {"models": [{"name": "test model", "description": "", "meta_rules": []}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}]} +DATA = {"subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], + "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], + "action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}] + } -SUBJECTS_OBJECTS_ACTIONS = {"models": [{"name": "test model", "description": "", "meta_rules": []}], +META_RULES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], + "object_categories": [{"name": "test object categories", "description": "object category description"}], + "action_categories": [{"name": "test action categories", "description": "action action description"}], + "meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]} + + +SUBJECTS_OBJECTS_ACTIONS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name":"meta rule"}]}], "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "policies": [{"name": "test policy"}]}], "objects": [{"name": "test object", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}], - "actions": [{"name": "test action", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}]} - + "actions": [{"name": "test action", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}], + **META_RULES + } SUBJECT_OBJECT_ACTION_CATEGORIES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], "object_categories": [{"name": "test object categories", "description": "object category description"}], "action_categories": [{"name": "test action categories", "description": "action category description"}]} -SUBJECT_OBJECT_ACTION_DATA = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}], - "subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}], - "meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]} - - -META_RULES = {"subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "object action description"}], - "meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}]} - +SUBJECT_OBJECT_ACTION_DATA = {**SUBJECTS_OBJECTS_ACTIONS, + **DATA + } +POLICIES = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], + "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], + **META_RULES, + } -ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}], - "subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}], - "meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}], +ASSIGNMENTS = {**POLICIES, + **DATA, "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "policies": [{"name": "test policy"}]}], "objects": [{"name": "test object e0", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}], "actions": [{"name": "test action e0", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}], @@ -57,34 +57,37 @@ ASSIGNMENTS = {"models": [{"name": "test model", "description": "", "meta_rules" "object_assignments": [{"object": {"name": "test object e0"}, "category": {"name": "test object categories"}, "assignments": [{"name": "test object data"}]}], "action_assignments": [{"action": {"name": "test action e0"}, "category": {"name": "test action categories"}, "assignments": [{"name": "test action data"}]}]} -RULES = {"models": [{"name": "test model", "description": "", "meta_rules": [{"name": "meta rule"}]}], - "policies": [{"name": "test policy", "genre": "authz", "description": "policy description", "model": {"name" : "test model"}}], - "subject_categories": [{"name": "test subject categories", "description": "subject category description"}], - "object_categories": [{"name": "test object categories", "description": "object category description"}], - "action_categories": [{"name": "test action categories", "description": "action category description"}], - "subject_data": [{"name": "test subject data", "description": "subject data description", "policies": [{"name": "test policy"}], "category": {"name": "test subject categories"}}], - "object_data": [{"name": "test object data", "description": "object data description", "policies": [{"name": "test policy"}], "category": {"name": "test object categories"}}], - "action_data": [{"name": "test action data", "description": "action data description", "policies": [{"name": "test policy"}], "category": {"name": "test action categories"}}], - "meta_rules": [{"name": "meta rule", "description": "valid meta rule", "subject_categories": [{"name": "test subject categories"}], "object_categories": [{"name": "test object categories"}], "action_categories": [{"name": "test action categories"}]}], +RULES = {**POLICIES, + **DATA, "subjects": [{"name": "testuser", "description": "description of the subject", "extra": {"field_extra_subject": "value extra subject"}, "policies": [{"name": "test policy"}]}], "objects": [{"name": "test object e1", "description": "description of the object", "extra": {"field_extra_object": "value extra object"}, "policies": [{"name": "test policy"}]}], "actions": [{"name": "test action e1", "description": "description of the action", "extra": {"field_extra_action": "value extra action"}, "policies": [{"name": "test policy"}]}], "subject_assignments": [{"subject": {"name": "testuser"}, "category": {"name": "test subject categories"}, "assignments": [{"name": "test subject data"}]}], "object_assignments": [{"object": {"name": "test object e1"}, "category": {"name": "test object categories"}, "assignments": [{"name": "test object data"}]}], "action_assignments": [{"action": {"name": "test action e1"}, "category": {"name": "test action categories"}, "assignments": [{"name": "test action data"}]}], - "rules": [{"meta_rule": {"name": "meta rule"}, "rule": {"subject_data": [{"name": "test subject data"}], "object_data": [{"name": "test object data"}], "action_data": [{"name": "test action data"}]}, "policy": {"name":"test policy"}, "instructions": {"decision": "grant"}, "enabled": True}] + "rules": [{"meta_rule": {"name": "meta rule"}, "rule": {"subject_data": [{"name": "test " + "subject data"}], + "object_data": [{"name": "test object data"}], + "action_data": [{"name": "test action data"}]}, "policy": {"name":"test policy"}, "instructions": [{"decision": "grant"}], "enabled": True}] } def test_export_models(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(MODEL_WITHOUT_META_RULES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + # import_export_helper.clean_all() + + req = hug.test.post(json_import, "/import", body=json.dumps( + MODEL_WITHOUT_META_RULES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")} ) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in MODEL_WITHOUT_META_RULES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data @@ -99,14 +102,20 @@ def test_export_models(): def test_export_policies(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(POLICIES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + POLICIES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in POLICIES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data @@ -124,14 +133,20 @@ def test_export_policies(): def test_export_subject_object_action(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(SUBJECTS_OBJECTS_ACTIONS)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + SUBJECTS_OBJECTS_ACTIONS) ,headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in SUBJECTS_OBJECTS_ACTIONS.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data @@ -160,14 +175,20 @@ def test_export_subject_object_action(): def test_export_subject_object_action_categories(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(SUBJECT_OBJECT_ACTION_CATEGORIES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + SUBJECT_OBJECT_ACTION_CATEGORIES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in SUBJECT_OBJECT_ACTION_CATEGORIES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data type_elements = ["subject", "object", "action"] @@ -182,14 +203,20 @@ def test_export_subject_object_action_categories(): def test_export_subject_object_action_data(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(SUBJECT_OBJECT_ACTION_DATA)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + SUBJECT_OBJECT_ACTION_DATA), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in SUBJECT_OBJECT_ACTION_DATA.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data type_elements = ["subject", "object", "action"] @@ -208,14 +235,20 @@ def test_export_subject_object_action_data(): def test_export_assignments(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(ASSIGNMENTS)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + ASSIGNMENTS), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in ASSIGNMENTS.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data type_elements = ["subject", "object", "action"] @@ -239,18 +272,24 @@ def test_export_assignments(): assert len(assignment_elt["assignments"]) == 1 assert assignment_elt["assignments"][0]["name"] == "test " + type_element + " data" - import_export_utilities.clean_all(client) + import_export_helper.clean_all() def test_export_rules(): - client = utilities.register_client() - import_export_utilities.clean_all(client) - req = client.post("/import", content_type='application/json', data=json.dumps(RULES)) + from moon_manager.api import json_import + from moon_manager.api import json_export + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + req = hug.test.post(json_import, "/import", body=json.dumps( + RULES), headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) data = utilities.get_json(req.data) - assert data == "Import ok !" + assert all(e in data for e in RULES.keys()) - req = client.get("/export") - assert req.status_code == 200 + req = hug.test.get(json_export, "/export", headers=auth_headers) + assert req.status == hug.HTTP_200 data = utilities.get_json(req.data) assert "content" in data assert "rules" in data["content"] @@ -258,8 +297,8 @@ def test_export_rules(): assert len(data["content"]["rules"]) == 1 rule = data["content"]["rules"][0] assert "instructions" in rule - assert "decision" in rule["instructions"] - assert rule["instructions"]["decision"] == "grant" + assert "decision" in rule["instructions"][0] + assert rule["instructions"][0]["decision"] == "grant" assert "enabled" in rule assert rule["enabled"] assert "meta_rule" in rule diff --git a/moon_manager/tests/unit_python/api/test_json_import.py b/moon_manager/tests/unit_python/api/test_json_import.py new file mode 100644 index 00000000..3195eca3 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_json_import.py @@ -0,0 +1,832 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import api.test_models as test_models +import api.test_policies as test_policies +import api.test_meta_data as test_categories +import api.test_data as test_data +import api.test_meta_rules as test_meta_rules +import api.test_assignement as test_assignments +import api.test_rules as test_rules +import helpers.import_export_helper as import_export_helper +import helpers.policy_helper as policy_helper +import hug +import json +import pytest +from moon_utilities import exceptions + + +MODEL_WITHOUT_META_RULES = [ + {"models": [{"name": "test model", "description": "", "meta_rules": []}]}, + {"models": [{"name": "test model", "description": "new description", "meta_rules": [], + "override": True}]}, + {"models": [{"name": "test model", "description": "description not taken into account", + "meta_rules": [], "override": False}]} +] + +POLICIES = [ + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}]}, + {"policies": [{"name": "test policy", "genre": "authz", + "description": "new description not taken into account", + "model": {"name": "test model"}, "mandatory": True}]}, + {"policies": [ + {"name": "test policy", "genre": "not authz ?", "description": "generates an exception", + "model": {"name": "test model"}, "override": True}]}, + {"models": [{"name": "test model", "description": "", "meta_rules": []}], "policies": [ + {"name": "test policy", "genre": "not authz ?", "description": "changes taken into account", + "model": {"name": "test model"}, "override": True}]}, +] + +SUBJECTS = [{"subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", + "model": {}, "mandatory": True}], "subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": []}]}, + {"subjects": [{"name": "testuser", "description": "new description of the subject", + "extra": {"email": "new-email@test.com"}, + "policies": [{"name": "test other policy"}]}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "subjects": [ + {"name": "testuser", "description": "description of the subject", "extra": {}, + "policies": [{"name": "test policy"}]}]}] + +OBJECTS = [ + {"objects": [{"name": "test object", "description": "description of the object", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], + "objects": [{"name": "test object", "description": "description of the object", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": True}], + "objects": [{"name": "test object", "description": "description of the object", "extra": {}, + "policies": []}]}, + {"objects": [{"name": "test object", "description": "new description of the object", + "extra": {"test": "test extra"}, + "policies": [{"name": "test other policy"}]}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], + "objects": [{"name": "test object", "description": "description of the object", "extra": {}, + "policies": [{"name": "test policy"}]}]}, +] + +ACTIONS = [{"actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": []}]}, + {"policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", + "model": {}, "mandatory": True}], "actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": []}]}, + {"actions": [{"name": "test action", "description": "new description of the action", + "extra": {"test": "test extra"}, + "policies": [{"name": "test other policy"}]}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", "model": {}, + "mandatory": False}], "actions": [ + {"name": "test action", "description": "description of the action", "extra": {}, + "policies": [{"name": "test policy"}]}]}] + +SUBJECT_CATEGORIES = [{"subject_categories": [ + {"name": "test subject categories", "description": "subject category description"}]}, + {"subject_categories": [{"name": "test subject categories", + "description": "new subject category description"}]}] + +OBJECT_CATEGORIES = [{"object_categories": [ + {"name": "test object categories", "description": "object category description"}]}, + {"object_categories": [{"name": "test object categories", + "description": "new object category description"}]}] + +ACTION_CATEGORIES = [{"action_categories": [ + {"name": "test action categories", "description": "action category description"}]}, + {"action_categories": [{"name": "test action categories", + "description": "new action category description"}]}] + +# meta_rules import is needed otherwise the search for data do not work !!! +PRE_DATA = {"models": [{"name": "test model", "description": "", + "meta_rules": [{"name": "good meta rule"}, + {"name": "other good meta rule"}]}], + "policies": [ + {"name": "test other policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], + "subject_categories": [ + {"name": "test subject categories", "description": "subject category description"}, + {"name": "other test subject categories", + "description": "subject category description"}], + "object_categories": [ + {"name": "test object categories", "description": "object category description"}, + {"name": "other test object categories", + "description": "object category description"}], + "action_categories": [ + {"name": "test action categories", "description": "action category description"}, + {"name": "other test action categories", + "description": "action category description"}], + "meta_rules": [{"name": "good meta rule", "description": "valid meta rule", + "subject_categories": [{"name": "test subject categories"}], + "object_categories": [{"name": "test object categories"}], + "action_categories": [{"name": "test action categories"}]}, + {"name": "other good meta rule", "description": "valid meta rule", + "subject_categories": [{"name": "other test subject categories"}], + "object_categories": [{"name": "other test object categories"}], + "action_categories": [{"name": "other test action categories"}]}]} + +SUBJECT_DATA = [{"subject_data": [ + {"name": "not valid subject data", "description": "", "policies": [{}], "category": {}}]}, + {"subject_data": [ + {"name": "not valid subject data", "description": "", "policies": [{}], + "category": {"name": "test subject categories"}}]}, + {"policies": [ + {"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], "subject_data": [ + {"name": "one valid subject data", "description": "description", + "policies": [{}], "category": {"name": "test subject categories"}}]}, + {"subject_data": [{"name": "valid subject data", "description": "description", + "policies": [{"name": "test policy"}], + "category": {"name": "test subject categories"}}]}, + {"subject_data": [{"name": "valid subject data", "description": "new description", + "policies": [{"name": "test other policy"}], + "category": {"name": "test subject categories"}}]}] + +OBJECT_DATA = [{"object_data": [ + {"name": "not valid object data", "description": "", "policies": [{}], "category": {}}]}, + {"object_data": [ + {"name": "not valid object data", "description": "", "policies": [{}], + "category": {"name": "test object categories"}}]}, + {"policies": [{"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], "object_data": [ + {"name": "one valid object data", "description": "description", "policies": [{}], + "category": {"name": "test object categories"}}]}, + {"object_data": [{"name": "valid object data", "description": "description", + "policies": [{"name": "test policy"}], + "category": {"name": "test object categories"}}]}, + {"object_data": [{"name": "valid object data", "description": "new description", + "policies": [{"name": "test other policy"}], + "category": {"name": "test object categories"}}]}] + +ACTION_DATA = [{"action_data": [ + {"name": "not valid action data", "description": "", "policies": [{}], "category": {}}]}, + {"action_data": [ + {"name": "not valid action data", "description": "", "policies": [{}], + "category": {"name": "test action categories"}}]}, + {"policies": [{"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], "action_data": [ + {"name": "one valid action data", "description": "description", "policies": [{}], + "category": {"name": "test action categories"}}]}, + {"action_data": [{"name": "valid action data", "description": "description", + "policies": [{"name": "test policy"}], + "category": {"name": "test action categories"}}]}, + {"action_data": [{"name": "valid action data", "description": "new description", + "policies": [{"name": "test other policy"}], + "category": {"name": "test action categories"}}]}] + +PRE_META_RULES = {"subject_categories": [ + {"name": "test subject categories", "description": "subject category description"}], + "object_categories": [{"name": "test object categories", + "description": "object category description"}], + "action_categories": [{"name": "test action categories", + "description": "object action description"}]} + +META_RULES = [{"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", + "subject_categories": [{"name": "not valid category"}], + "object_categories": [{"name": "test object categories"}], + "action_categories": [{"name": "test action categories"}]}]}, + {"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", + "subject_categories": [{"name": "test subject categories"}], + "object_categories": [{"name": "not valid category"}], + "action_categories": [{"name": "test action categories"}]}]}, + {"meta_rules": [{"name": "bad meta rule", "description": "not valid meta rule", + "subject_categories": [{"name": "test subject categories"}], + "object_categories": [{"name": "test object categories"}], + "action_categories": [{"name": "not valid category"}]}]}, + {"meta_rules": [{"name": "good meta rule", "description": "valid meta rule", + "subject_categories": [{"name": "test subject categories"}], + "object_categories": [{"name": "test object categories"}], + "action_categories": [{"name": "test action categories"}]}]}] + +PRE_ASSIGNMENTS = {"models": [ + {"name": "test model", "description": "", "meta_rules": [{"name": "good meta rule"}]}], + "policies": [ + {"name": "test policy", "genre": "authz", "description": "description", + "model": {"name": "test model"}, "mandatory": True}], + "subject_categories": [{"name": "test subject categories", + "description": "subject category description"}], + "object_categories": [{"name": "test object categories", + "description": "object category description"}], + "action_categories": [{"name": "test action categories", + "description": "object action description"}], + "subjects": [{"name": "testuser", "description": "description of the subject", + "extra": {}, "policies": [{"name": "test policy"}]}], + "objects": [{"name": "test object", "description": "description of the object", + "extra": {}, "policies": [{"name": "test policy"}]}], + "actions": [{"name": "test action", "description": "description of the action", + "extra": {}, "policies": [{"name": "test policy"}]}], + "meta_rules": [{"name": "good meta rule", "description": "valid meta rule", + "subject_categories": [{"name": "test subject categories"}], + "object_categories": [{"name": "test object categories"}], + "action_categories": [{"name": "test action categories"}]}], + "subject_data": [{"name": "subject data", "description": "test subject data", + "policies": [{"name": "test policy"}], + "category": {"name": "test subject categories"}}], + "object_data": [{"name": "object data", "description": "test object data", + "policies": [{"name": "test policy"}], + "category": {"name": "test object categories"}}], + "action_data": [{"name": "action data", "description": "test action data", + "policies": [{"name": "test policy"}], + "category": {"name": "test action categories"}}]} + +SUBJECT_ASSIGNMENTS = [ + {"subject_assignments": [ + {"subject": {"name": "unknown"}, + "category": {"name": "test subject categories"}, + "assignments": [{"name": "subject data"}]}], + "exception": exceptions.InvalidJson + }, + {"subject_assignments": [ + {"subject": {"name": "testuser"}, + "category": {"name": "unknown"}, + "assignments": [{"name": "subject data"}]}], + "exception": exceptions.UnknownName + }, + {"subject_assignments": [ + {"subject": {"name": "testuser"}, + "category": {"name": "test subject categories"}, + "assignments": [{"name": "unknown"}]}], + "exception": exceptions.InvalidJson + }, + {"subject_assignments": [ + {"subject": {"name": "testuser"}, + "category": {"name": "test subject categories"}, + "assignments": [{"name": "subject data"}]}], + "exception": None + }] + +OBJECT_ASSIGNMENTS = [ + {"object_assignments": [ + {"object": {"name": "unknown"}, + "category": {"name": "test object categories"}, + "assignments": [{"name": "object data"}]}], + "exception": exceptions.InvalidJson + }, + {"object_assignments": [ + {"object": {"name": "test object"}, + "category": {"name": "unknown"}, + "assignments": [{"name": "object data"}]}], + "exception": exceptions.UnknownName + }, + {"object_assignments": [ + {"object": {"name": "test object"}, + "category": {"name": "test object categories"}, + "assignments": [{"name": "unknown"}]}], + "exception": exceptions.InvalidJson + }, + {"object_assignments": [ + {"object": {"name": "test object"}, + "category": {"name": "test object categories"}, + "assignments": [{"name": "object data"}]}], + "exception": None + }] + +ACTION_ASSIGNMENTS = [ + {"action_assignments": [ + {"action": {"name": "unknown"}, + "category": {"name": "test action categories"}, + "assignments": [{"name": "action data"}]}], + "exception": exceptions.InvalidJson + }, + {"action_assignments": [ + {"action": {"name": "test action"}, + "category": {"name": "unknown"}, + "assignments": [{"name": "action data"}]}], + "exception": exceptions.UnknownName + }, + {"action_assignments": [ + {"action": {"name": "test action"}, + "category": {"name": "test action categories"}, + "assignments": [{"name": "unknown"}]}], + "exception": exceptions.InvalidJson + }, + {"action_assignments": [ + {"action": {"name": "test action"}, + "category": {"name": "test action categories"}, + "assignments": [{"name": "action data"}]}], + "exception": None + }] + +RULES = [{"rules": [{"meta_rule": {"name": "unknown meta rule"}, "policy": {"name": "test " + "policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "unknown " + "policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "unknown subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "unknown object data"}], + "action_data": [{"name": "action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "unknown action data"}]}}]}, + {"rules": [{"meta_rule": {"name": "good meta rule"}, "policy": {"name": "test policy"}, + "instructions": [{"decision": "grant"}], "enabled": True, "rule": { + "subject_data": [{"name": "subject data"}], + "object_data": [{"name": "object data"}], + "action_data": [{"name": "action data"}]}}]}] + + +def test_import_models_without_new_meta_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + counter = 0 + for models_description in MODEL_WITHOUT_META_RULES: + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(models_description) + , headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in models_description.keys()) + req, models = test_models.get_models() + models = models["models"] + assert len(list(models.keys())) == 1 + values = list(models.values()) + assert values[0]["name"] == "test model" + if counter == 0: + assert len(values[0]["description"]) == 0 + if counter == 1 or counter == 2: + assert values[0]["description"] == "new description" + counter = counter + 1 + import_export_helper.clean_all() + + +def test_import_policies(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + counter = -1 + for policy_description in POLICIES: + counter = counter + 1 + from moon_manager.api import json_import + if counter == 2: + with pytest.raises(exceptions.UnknownName): + req = hug.test.post(json_import, "/import", body=json.dumps(policy_description), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + continue + else: + req = hug.test.post(json_import, "/import", body=json.dumps(policy_description), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in policy_description.keys()) + + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers) + policies = req.data + policies = policies["policies"] + assert len(list(policies.keys())) == 1 + values = list(policies.values()) + assert values[0]["name"] == "test policy" + if counter < 3: + assert values[0]["genre"] == "authz" + assert values[0]["description"] == "description" + else: + assert values[0]["genre"] == "not authz ?" + assert values[0]["description"] == "changes taken into account" + assert len(values[0]["model_id"]) > 0 + import_export_helper.clean_all() + + +def test_import_subject_object_action(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + type_elements = ["object", "action"] + perimeter_id = None + + for type_element in type_elements: + import_export_helper.clean_all() + counter = -1 + # set the getters and the comparison values + if type_element == "subject": + elements = SUBJECTS + clean_method = import_export_helper.clean_subjects + name = "testuser" + key_extra = "email" + value_extra = "new-email@test.com" + elif type_element == "object": + elements = OBJECTS + clean_method = import_export_helper.clean_objects + name = "test object" + key_extra = "test" + value_extra = "test extra" + else: + elements = ACTIONS + clean_method = import_export_helper.clean_actions + name = "test action" + key_extra = "test" + value_extra = "test extra" + + for element in elements: + counter = counter + 1 + if counter == 2 or counter == 4: + clean_method() + + from moon_manager.api import perimeter + if counter == 3: + req = hug.test.patch(perimeter, "/{}s/{}".format(type_element, perimeter_id), + body=json.dumps(element["{}s".format(type_element)][0]), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + elif counter < 2: + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/{}s/{}".format(type_element, perimeter_id), + body=json.dumps(element["{}s".format(type_element)][0]), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + # assert req.status == hug.HTTP_400 + assert '400: Perimeter content is invalid.' == str(exception_info.value) + continue + else: + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(element), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + + try: + data = req.data + except Exception as e: + assert False + # assert counter < 2 # Â this is an expected failure + # continue + + if counter != 3: + assert any(e in data for e in element["{}s".format(type_element)][0].keys()) #NOTE: logs are skipped for some elements + + from moon_manager.api import perimeter + get_elements = hug.test.get(perimeter, "/" + type_element + "s", headers=auth_headers ).data + get_elements = get_elements[type_element + "s"] + + perimeter_id = list(get_elements.keys())[0] + + assert len(list(get_elements.keys())) == 1 + values = list(get_elements.values()) + assert values[0]["name"] == name + if counter == 2 or counter == 4: + assert values[0]["description"] == "description of the " + type_element + # assert not values[0]["extra"] + if counter == 3: + assert values[0]["description"] == "new description of the " + type_element + assert values[0]["extra"][key_extra] == value_extra + + # Â assert len(values[0]["policy_list"]) == 1 + import_export_helper.clean_all() + + +def test_import_subject_object_action_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + type_elements = ["subject", "object", "action"] + + for type_element in type_elements: + import_export_helper.clean_all() + counter = -1 + # set the getters and the comparison values + if type_element == "subject": + elements = SUBJECT_CATEGORIES + get_method = test_categories.get_subject_categories + elif type_element == "object": + elements = OBJECT_CATEGORIES + get_method = test_categories.get_object_categories + else: + elements = ACTION_CATEGORIES + get_method = test_categories.get_action_categories + + for element in elements: + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(element), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")} ) + counter = counter + 1 + data = req.data + assert all(e in data for e in element.keys()) + req, get_elements = get_method() + get_elements = get_elements[type_element + "_categories"] + assert len(list(get_elements.keys())) == 1 + values = list(get_elements.values()) + assert values[0]["name"] == "test " + type_element + " categories" + assert values[0]["description"] == type_element + " category description" + + +def test_import_meta_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + # import some categories + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_META_RULES), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in PRE_META_RULES.keys()) + + counter = -1 + for meta_rule in META_RULES: + counter = counter + 1 + if counter != 3: + with pytest.raises(exceptions.UnknownName) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(meta_rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + # assert req.status == hug.HTTP_400 + assert '400: Unknown Name.' == str(exception_info.value) + continue + else: + req = hug.test.post(json_import, "/import", body=json.dumps(meta_rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in meta_rule.keys()) + assert req.status == hug.HTTP_200 + + req, meta_rules = test_meta_rules.get_meta_rules() + meta_rules = meta_rules["meta_rules"] + key = list(meta_rules.keys())[0] + assert isinstance(meta_rules, dict) + assert meta_rules[key]["name"] == "good meta rule" + assert meta_rules[key]["description"] == "valid meta rule" + assert len(meta_rules[key]["subject_categories"]) == 1 + assert len(meta_rules[key]["object_categories"]) == 1 + assert len(meta_rules[key]["action_categories"]) == 1 + + subject_category_key = meta_rules[key]["subject_categories"][0] + object_category_key = meta_rules[key]["object_categories"][0] + action_category_key = meta_rules[key]["action_categories"][0] + + req, sub_cat = test_categories.get_subject_categories() + sub_cat = sub_cat["subject_categories"] + assert sub_cat[subject_category_key]["name"] == "test subject categories" + + req, ob_cat = test_categories.get_object_categories() + ob_cat = ob_cat["object_categories"] + assert ob_cat[object_category_key]["name"] == "test object categories" + + req, ac_cat = test_categories.get_action_categories() + ac_cat = ac_cat["action_categories"] + assert ac_cat[action_category_key]["name"] == "test action categories" + + import_export_helper.clean_all() + + +def test_import_subject_object_action_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + import_export_helper.clean_all() + + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_ASSIGNMENTS), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")} ) + data = req.data + assert any(e in data for e in PRE_ASSIGNMENTS.keys()) #NOTE: note assignment logs are skipped + + type_elements = ["subject", "object", "action"] + + for type_element in type_elements: + counter = -1 + if type_element == "subject": + datas = SUBJECT_ASSIGNMENTS + get_method = test_assignments.get_subject_assignment + elif type_element == "object": + datas = OBJECT_ASSIGNMENTS + get_method = test_assignments.get_object_assignment + else: + datas = ACTION_ASSIGNMENTS + get_method = test_assignments.get_action_assignment + + for assignments in datas: + counter = counter + 1 + my_exception = assignments.pop("exception") + if my_exception: + with pytest.raises(my_exception) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(assignments), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + assert '400:' in str(exception_info.value) + else: + req = hug.test.post(json_import, "/import", body=json.dumps(assignments), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + assert len(assignments.keys()) > 0 #NOTE logs for assignments are skipped + assert req.status == hug.HTTP_200 + req = test_policies.get_policies(auth_headers=auth_headers) + policies = req.data + for policy_key in policies["policies"]: + req, get_assignments = get_method(policy_key) + get_assignments = get_assignments[type_element + "_assignments"] + assert len(get_assignments) == 1 + + +def test_import_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + + import_export_helper.clean_all() + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_ASSIGNMENTS), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + data = req.data + assert all(e in data for e in PRE_ASSIGNMENTS.keys()) + + counter = -1 + for rule in RULES: + counter = counter + 1 + from moon_manager.api import json_import + if counter < 5: + with pytest.raises(exceptions.UnknownName) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + + # assert req.status == hug.HTTP_400 + assert '400: Unknown Name.' == str(exception_info.value) + continue + req = hug.test.post(json_import, "/import", body=json.dumps(rule), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + + assert req.status == hug.HTTP_200 + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + policies = test_policies.get_policies(auth_headers=auth_headers).data + for policy in policies['policies']: + if policies['policies'][policy]['name'] == rule['rules'][0]['policy']['name']: + policy_id = policy + break + + req, rules = test_rules.test_get_rules(policy_id) + rules = rules["rules"] + rules = rules["rules"] + assert len(rules) == 1 + rules = rules[0] + assert rules["enabled"] + assert rules["instructions"][0]["decision"] == "grant" + + req, meta_rules = test_meta_rules.get_meta_rules() + assert meta_rules["meta_rules"][list(meta_rules["meta_rules"].keys())[0]][ + "name"] == "good meta rule" + + +def test_import_subject_object_action_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + type_elements = ["subject", "object", "action"] + + for type_element in type_elements: + import_export_helper.clean_all() + from moon_manager.api import json_import + req = hug.test.post(json_import, "/import", body=json.dumps(PRE_DATA), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + counter = -1 + # set the getters and the comparison values + if type_element == "subject": + elements = SUBJECT_DATA + get_method = test_data.get_subject_data + get_categories = test_categories.get_subject_categories + elif type_element == "object": + elements = OBJECT_DATA + get_method = test_data.get_object_data + get_categories = test_categories.get_object_categories + else: + elements = ACTION_DATA + get_method = test_data.get_action_data + get_categories = test_categories.get_action_categories + + for element in elements: + from moon_manager.api import json_import + counter = counter + 1 + if counter == 0 or counter == 1: + with pytest.raises(exceptions.MissingIdOrName) as exception_info: + req = hug.test.post(json_import, "/import", body=json.dumps(element), headers={ + 'Content-Type': 'application/json', "X-Api-Key": get_api_key_for_user("admin")}) + # assert req.status == hug.HTTP_400 + assert '400: Missing ID or Name.' == str(exception_info.value) + continue + else: + req = hug.test.post(json_import, "/import", body=json.dumps(element), headers={ + 'Content-Type': 'application/json', "X-Api-Key": get_api_key_for_user("admin")}) + assert req.status == hug.HTTP_200 + data = req.data + assert all(e in data for e in element.keys()) + + req = test_policies.get_policies(auth_headers=auth_headers) + policies = req.data + policies = policies["policies"] + req, categories = get_categories() + categories = categories[type_element + "_categories"] + case_tested = False + for policy_key in policies.keys(): + policy = policies[policy_key] + for category_key in categories: + req, get_elements = get_method(policy_id=policy_key, + category_id=category_key) + if len(get_elements[type_element + "_data"]) == 0: + continue + + # do this because the backend gives an element with empty data if the policy_key, + # category_key couple does not have any data... + get_elements = get_elements[type_element + "_data"] + if len(get_elements[0]["data"]) == 0: + continue + + if policy["name"] == "test policy": + assert len(get_elements) == 1 + el = get_elements[0] + assert isinstance(el["data"], dict) + if counter == 2: + assert len(el["data"].keys()) == 1 + el = el["data"][list(el["data"].keys())[0]] + if "value" in el: + el = el["value"] + assert el["name"] == "one valid " + type_element + " data" + if counter == 3: + assert len(el["data"].keys()) == 2 + el1 = el["data"][list(el["data"].keys())[0]] + el2 = el["data"][list(el["data"].keys())[1]] + if "value" in el1: + el1 = el1["value"] + el2 = el2["value"] + assert (el1["name"] == "one valid " + type_element + " data" and el2[ + "name"] == "valid " + type_element + " data") or (el2[ + "name"] == "one valid " + type_element + " data" and + el1[ + "name"] == "valid " + type_element + " data") + assert el1["description"] == "description" + assert el2["description"] == "description" + + case_tested = True + + if policy["name"] == "test other policy": + if counter == 4: + assert len(get_elements) == 1 + el = get_elements[0] + assert isinstance(el["data"], dict) + assert len(el["data"].keys()) == 1 + el = el["data"][list(el["data"].keys())[0]] + if "value" in el: + el = el["value"] + assert el["name"] == "valid " + type_element + " data" + assert el["description"] == "new description" + case_tested = True + + assert case_tested is True + + +def test_clean(): + import_export_helper.clean_all() + # restore the database as previously + policy_helper.add_policies() diff --git a/moon_manager/tests/unit_python/api/test_keystone.py b/moon_manager/tests/unit_python/api/test_keystone.py new file mode 100644 index 00000000..5ed08ca7 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_keystone.py @@ -0,0 +1,63 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + + +def create_project(tenant_dict): + from moon_manager.pip_driver import InformationManager + return InformationManager["subjects"][0].create_project(**tenant_dict) + + +def list_projects(): + from moon_manager.pip_driver import InformationManager + return InformationManager["subjects"][0].get_projects() + + +def create_user(subject_dict): + from moon_manager.pip_driver import InformationManager + return InformationManager["subjects"][0].add_item(**subject_dict) + + +def test_create_project(): + tenant_dict = { + "description": "test_project", + "domain": ['domain_id_1'], + "enabled": True, + "is_domain": False, + "name": 'project_1' + } + project = create_project(tenant_dict) + assert project + assert project.get('name') == tenant_dict.get('name') + +# TODO TO BE UPDATED +# def test_create_project_without_name(): +# tenant_dict = { +# "description": "test_project", +# "domain_id": ['domain_id_1'], +# "enabled": True, +# "is_domain": False, +# } +# with pytest.raises(Exception) as exception_info: +# create_project(tenant_dict) +# assert '400: Keystone project error' == str(exception_info.value) + + +def test_create_user(): + subject_dict = { + "password": "password", + "domain": ['domain_id_1'], + "enabled": True, + "project": 'test_project', + "name": 'user_id_1' + } + user = create_user(subject_dict) + assert user diff --git a/moon_manager/tests/unit_python/api/test_meta_data.py b/moon_manager/tests/unit_python/api/test_meta_data.py index e6cb0833..1d37ab70 100644 --- a/moon_manager/tests/unit_python/api/test_meta_data.py +++ b/moon_manager/tests/unit_python/api/test_meta_data.py @@ -1,305 +1,370 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug import json -import api.utilities as utilities from helpers import data_builder from uuid import uuid4 - +import pytest +from moon_utilities import exceptions # subject_categories_test -def get_subject_categories(client): - req = client.get("/subject_categories") - subject_categories = utilities.get_json(req.data) +def get_subject_categories(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(meta_data, "/subject_categories", headers=auth_headers ) + subject_categories = req.data return req, subject_categories -def add_subject_categories(client, name): +def add_subject_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + data = { "name": name, "description": "description of {}".format(name) } - req = client.post("/subject_categories", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - subject_categories = utilities.get_json(req.data) + req = hug.test.post(meta_data, "/subject_categories", body=json.dumps(data), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")}) + + subject_categories = req.data return req, subject_categories -def delete_subject_categories(client, name): - request, subject_categories = get_subject_categories(client) +def delete_subject_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, subject_categories = get_subject_categories() for key, value in subject_categories['subject_categories'].items(): if value['name'] == name: - return client.delete("/subject_categories/{}".format(key)) - - -def delete_subject_categories_without_id(client): - req = client.delete("/subject_categories/{}".format("")) - return req + return hug.test.delete(meta_data, "/subject_categories/{}".format(key), headers=auth_headers ) + return hug.test.delete(meta_data, "/subject_categories/{}".format(name), headers=auth_headers ) def test_get_subject_categories(): - client = utilities.register_client() - req, subject_categories = get_subject_categories(client) - assert req.status_code == 200 + req, subject_categories = get_subject_categories() + assert req.status == hug.HTTP_200 assert isinstance(subject_categories, dict) assert "subject_categories" in subject_categories def test_add_subject_categories(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "testuser") - assert req.status_code == 200 + name = "testuser" + uuid4().hex + req, subject_categories = add_subject_categories(name) + assert req.status == hug.HTTP_200 assert isinstance(subject_categories, dict) value = list(subject_categories["subject_categories"].values())[0] assert "subject_categories" in subject_categories - assert value['name'] == "testuser" - assert value['description'] == "description of {}".format("testuser") + assert value['name'] == name + assert value['description'] == "description of {}".format(name) def test_add_subject_categories_with_existed_name(): - client = utilities.register_client() name = uuid4().hex - req, subject_categories = add_subject_categories(client, name) - assert req.status_code == 200 - req, subject_categories = add_subject_categories(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Subject Category Existing' + req, subject_categories = add_subject_categories(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.SubjectCategoryExisting) as exception_info: + req, subject_categories = add_subject_categories(name) + assert '409: Subject Category Existing' == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Subject Category Existing' def test_add_subject_categories_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Category Name Invalid' + with pytest.raises(exceptions.CategoryNameInvalid) as exception_info: + req, subject_categories = add_subject_categories(" ") + assert '400: Category Name Invalid' == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Category Name Invalid' def test_add_subject_categories_with_empty_name(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_categories = add_subject_categories("<a>") + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) def test_add_subject_categories_with_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_subject_categories(client, "test<z>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, subject_categories = add_subject_categories("test<z>user") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_delete_subject_categories(): - client = utilities.register_client() - req = delete_subject_categories(client, "testuser") - assert req.status_code == 200 + name = "testuser" + uuid4().hex + add_subject_categories(name) + req = delete_subject_categories(name) + assert req.status == hug.HTTP_200 def test_delete_subject_categories_without_id(): - client = utilities.register_client() - req = delete_subject_categories_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Subject Category Unknown" + with pytest.raises(exceptions.SubjectCategoryUnknown) as exception_info: + req = delete_subject_categories(uuid4().hex) + assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "400: Subject Category Unknown" # --------------------------------------------------------------------------- # object_categories_test -def get_object_categories(client): - req = client.get("/object_categories") - object_categories = utilities.get_json(req.data) +def get_object_categories(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(meta_data, "/object_categories", headers=auth_headers ) + object_categories = req.data return req, object_categories -def add_object_categories(client, name): +def add_object_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + data = { "name": name, "description": "description of {}".format(name) } - req = client.post("/object_categories", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - object_categories = utilities.get_json(req.data) + req = hug.test.post(meta_data, "/object_categories", body=json.dumps(data), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")} ) + object_categories = req.data return req, object_categories -def delete_object_categories(client, name): - request, object_categories = get_object_categories(client) +def delete_object_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, object_categories = get_object_categories() for key, value in object_categories['object_categories'].items(): if value['name'] == name: - return client.delete("/object_categories/{}".format(key)) - - -def delete_object_categories_without_id(client): - req = client.delete("/object_categories/{}".format("")) - return req + return hug.test.delete(meta_data, "/object_categories/{}".format(key), + headers=auth_headers ) + return hug.test.delete(meta_data, "/object_categories/{}".format(name), headers=auth_headers ) def test_get_object_categories(): - client = utilities.register_client() - req, object_categories = get_object_categories(client) - assert req.status_code == 200 + req, object_categories = get_object_categories() + assert req.status == hug.HTTP_200 assert isinstance(object_categories, dict) assert "object_categories" in object_categories def test_add_object_categories(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "testuser") - assert req.status_code == 200 + name="testuser"+uuid4().hex + req, object_categories = add_object_categories(name) + assert req.status == hug.HTTP_200 assert isinstance(object_categories, dict) value = list(object_categories["object_categories"].values())[0] assert "object_categories" in object_categories - assert value['name'] == "testuser" - assert value['description'] == "description of {}".format("testuser") + assert value['name'] == name + assert value['description'] == "description of {}".format(name) def test_add_object_categories_with_existed_name(): - client = utilities.register_client() name = uuid4().hex - req, object_categories = add_object_categories(client, name) - assert req.status_code == 200 - req, object_categories = add_object_categories(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Object Category Existing' + req, object_categories = add_object_categories(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.ObjectCategoryExisting) as exception_info: + req, object_categories = add_object_categories(name) + assert "409: Object Category Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Object Category Existing' def test_add_object_categories_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_object_categories(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Category Name Invalid' + with pytest.raises(exceptions.CategoryNameInvalid) as exception_info: + req, subject_categories = add_object_categories(" ") + assert "400: Category Name Invalid" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Category Name Invalid' def test_add_object_categories_with_empty_name(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, object_categories = add_object_categories("<a>") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_add_object_categories_with_name_contain_space(): - client = utilities.register_client() - req, object_categories = add_object_categories(client, "test<a>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, object_categories = add_object_categories("test<a>user") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_delete_object_categories(): - client = utilities.register_client() - req = delete_object_categories(client, "testuser") - assert req.status_code == 200 + name = uuid4().hex + add_object_categories(name) + req = delete_object_categories(name) + assert req.status == hug.HTTP_200 def test_delete_object_categories_without_id(): - client = utilities.register_client() - req = delete_object_categories_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Object Category Unknown" + with pytest.raises(exceptions.ObjectCategoryUnknown) as exception_info: + req = delete_object_categories(uuid4().hex) + assert "400: Object Category Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "400: Object Category Unknown" # --------------------------------------------------------------------------- # action_categories_test -def get_action_categories(client): - req = client.get("/action_categories") - action_categories = utilities.get_json(req.data) +def get_action_categories(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(meta_data, "/action_categories", headers=auth_headers ) + action_categories = req.data return req, action_categories -def add_action_categories(client, name): +def add_action_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + data = { "name": name, "description": "description of {}".format(name) } - req = client.post("/action_categories", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - action_categories = utilities.get_json(req.data) + req = hug.test.post(meta_data, "/action_categories", body=json.dumps(data), + headers={'Content-Type': 'application/json', "X-Api-Key": + get_api_key_for_user("admin")} ) + action_categories = req.data return req, action_categories -def delete_action_categories(client, name): - request, action_categories = get_action_categories(client) +def delete_action_categories(name): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, action_categories = get_action_categories() for key, value in action_categories['action_categories'].items(): if value['name'] == name: - return client.delete("/action_categories/{}".format(key)) - - -def delete_action_categories_without_id(client): - req = client.delete("/action_categories/{}".format("")) - return req + return hug.test.delete(meta_data, "/action_categories/{}".format(key), headers=auth_headers ) + return hug.test.delete(meta_data, "/action_categories/{}".format(name), headers=auth_headers ) def test_get_action_categories(): - client = utilities.register_client() - req, action_categories = get_action_categories(client) - assert req.status_code == 200 + req, action_categories = get_action_categories() + assert req.status == hug.HTTP_200 assert isinstance(action_categories, dict) assert "action_categories" in action_categories def test_add_action_categories(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "testuser") - assert req.status_code == 200 + name = "testuser" + uuid4().hex + req, action_categories = add_action_categories(name) + assert req.status == hug.HTTP_200 assert isinstance(action_categories, dict) value = list(action_categories["action_categories"].values())[0] assert "action_categories" in action_categories - assert value['name'] == "testuser" - assert value['description'] == "description of {}".format("testuser") + assert value['name'] == name + assert value['description'] == "description of {}".format(name) def test_add_action_categories_with_existed_name(): - client = utilities.register_client() name = uuid4().hex - req, action_categories = add_action_categories(client, name) - assert req.status_code == 200 - req, action_categories = add_action_categories(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Action Category Existing' + req, action_categories = add_action_categories(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.ActionCategoryExisting) as exception_info: + req, action_categories = add_action_categories(name) + assert "409: Action Category Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Action Category Existing' def test_add_action_categories_name_contain_space(): - client = utilities.register_client() - req, subject_categories = add_action_categories(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Category Name Invalid' + with pytest.raises(exceptions.CategoryNameInvalid) as exception_info: + req, subject_categories = add_action_categories(" ") + assert "400: Category Name Invalid" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Category Name Invalid' def test_add_action_categories_with_empty_name(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, action_categories = add_action_categories("<a>") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_add_action_categories_with_name_contain_space(): - client = utilities.register_client() - req, action_categories = add_action_categories(client, "test<a>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, action_categories = add_action_categories("test<a>user") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "Key: 'name', [Forbidden characters in string]" def test_delete_action_categories(): - client = utilities.register_client() - req = delete_action_categories(client, "testuser") - assert req.status_code == 200 + name = "testuser" + uuid4().hex + add_action_categories(name) + req = delete_action_categories(name) + assert req.status == hug.HTTP_200 def test_delete_action_categories_without_id(): - client = utilities.register_client() - req = delete_action_categories_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Action Category Unknown" + with pytest.raises(exceptions.ActionCategoryUnknown) as exception_info: + req = delete_action_categories(uuid4().hex) + assert "400: Action Category Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == "400: Action Category Unknown" def test_delete_data_categories_connected_to_meta_rule(): + from moon_manager.api import meta_data + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() - client = utilities.register_client() - req = client.delete("/subject_categories/{}".format(subject_category_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Subject Category With Meta Rule Error' - - req = client.delete("/object_categories/{}".format(object_category_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Object Category With Meta Rule Error' - - req = client.delete("/action_categories/{}".format(action_category_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Action Category With Meta Rule Error' + + with pytest.raises(exceptions.DeleteSubjectCategoryWithMetaRule) as exception_info: + req = hug.test.delete(meta_data, "/subject_categories/{}".format(subject_category_id), + headers=auth_headers ) + assert "400: Subject Category With Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Subject Category With Meta Rule Error' + + with pytest.raises(exceptions.DeleteObjectCategoryWithMetaRule) as exception_info: + req = hug.test.delete(meta_data, "/object_categories/{}".format(object_category_id), headers=auth_headers) + assert "400: Object Category With Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Object Category With Meta Rule Error' + + with pytest.raises(exceptions.DeleteActionCategoryWithMetaRule) as exception_info: + req = hug.test.delete(meta_data, "/action_categories/{}".format(action_category_id), headers=auth_headers) + assert "400: Action Category With Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data['message'] == '400: Action Category With Meta Rule Error' diff --git a/moon_manager/tests/unit_python/api/test_meta_rules.py b/moon_manager/tests/unit_python/api/test_meta_rules.py index 634f19da..6c6797f5 100644 --- a/moon_manager/tests/unit_python/api/test_meta_rules.py +++ b/moon_manager/tests/unit_python/api/test_meta_rules.py @@ -1,17 +1,42 @@ -import json +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug import api.utilities as utilities from helpers import category_helper from helpers import data_builder +from helpers import policy_helper +from helpers import model_helper +from helpers import meta_rule_helper from uuid import uuid4 +import pytest +from moon_utilities import exceptions + +def get_meta_rules(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def get_meta_rules(client): - req = client.get("/meta_rules") + req = hug.test.get(meta_rules, "/meta_rules", headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def add_meta_rules(client, name, data=None): +def add_meta_rules(name, data=None): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if not data: subject_category = category_helper.add_subject_category( value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) @@ -29,26 +54,34 @@ def add_meta_rules(client, name, data=None): "object_categories": [object_category_id], "action_categories": [action_category_id] } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(meta_rules, "/meta_rules", body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def add_meta_rules_without_category_ids(client, name): +def add_meta_rules_without_category_ids(name): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + data = { "name": name + uuid4().hex, "subject_categories": [], "object_categories": [], "action_categories": [] } - req = client.post("/meta_rules", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(meta_rules, "/meta_rules", body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def update_meta_rules(client, name, metaRuleId, data=None): +def update_meta_rules(name, metaRuleId, data=None): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if not data: subject_category = category_helper.add_subject_category( value={"name": "subject category name update" + uuid4().hex, @@ -69,13 +102,17 @@ def update_meta_rules(client, name, metaRuleId, data=None): "action_categories": [action_category_id] } - req = client.patch("/meta_rules/{}".format(metaRuleId), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(meta_rules, "/meta_rules/{}".format(metaRuleId), body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def update_meta_rules_with_categories(client, name, data=None, meta_rule_id=None): +def update_meta_rules_with_categories(name, data=None, meta_rule_id=None): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + if not meta_rule_id: subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { @@ -85,63 +122,87 @@ def update_meta_rules_with_categories(client, name, data=None, meta_rule_id=None "action_categories": [action_category_id] } - req = client.patch("/meta_rules/{}".format(meta_rule_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(meta_rules, "/meta_rules/{}".format(meta_rule_id), body=data, + headers=auth_headers) meta_rules = utilities.get_json(req.data) return req, meta_rules -def delete_meta_rules(client, name): - request, meta_rules = get_meta_rules(client) - for key, value in meta_rules['meta_rules'].items(): +def delete_meta_rules(name): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + request, meta_rules_data = get_meta_rules() + for key, value in meta_rules_data['meta_rules'].items(): if value['name'] == name: - return client.delete("/meta_rules/{}".format(key)) + return hug.test.delete(meta_rules, "/meta_rules/{}".format(key), headers=auth_headers) + +def delete_meta_rules_without_id(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def delete_meta_rules_without_id(client): - req = client.delete("/meta_rules/{}".format("")) + req = hug.test.delete(meta_rules, "/meta_rules/{}".format(""), headers=auth_headers) return req def test_get_meta_rules(): - client = utilities.register_client() - req, meta_rules = get_meta_rules(client) - assert req.status_code == 200 + req, meta_rules = get_meta_rules() + assert req.status == hug.HTTP_200 assert isinstance(meta_rules, dict) assert "meta_rules" in meta_rules def test_add_meta_rules(): - client = utilities.register_client() meta_rule_name = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name) + assert req.status == hug.HTTP_200 assert isinstance(meta_rules, dict) value = list(meta_rules["meta_rules"].values())[0] assert "meta_rules" in meta_rules assert value['name'] == meta_rule_name +def test_add_meta_rules_space_name(): + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req, meta_rules = add_meta_rules(" ") + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Error' + + +def test_add_meta_rules_empty_name(): + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req, meta_rules = add_meta_rules("") + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Error' + + def test_add_two_meta_rules_with_same_categories_combination(): - client = utilities.register_client() meta_rule_name = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name) + data = None + assert req.status == hug.HTTP_200 for meta_rule_id in meta_rules['meta_rules']: if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name: data = meta_rules['meta_rules'][meta_rule_id] + assert data data['name'] = uuid4().hex - req, meta_rules = add_meta_rules(client, name=data['name'], data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Meta Rule Existing' + with pytest.raises(exceptions.MetaRuleExisting) as exception_info: + req, meta_rules = add_meta_rules(name=data['name'], data=data) + assert "409: Meta Rule Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Meta Rule Existing' def test_add_three_meta_rules_with_different_combination_but_similar_items(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name1) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1) + assert req.status == hug.HTTP_200 for meta_rule_id in meta_rules['meta_rules']: if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name1: data = meta_rules['meta_rules'][meta_rule_id] @@ -149,7 +210,7 @@ def test_add_three_meta_rules_with_different_combination_but_similar_items(): meta_rule_name2 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name2) + req, meta_rules = add_meta_rules(meta_rule_name2) for meta_rule_id in meta_rules['meta_rules']: if meta_rules['meta_rules'][meta_rule_id]['name'] == meta_rule_name2: @@ -161,12 +222,11 @@ def test_add_three_meta_rules_with_different_combination_but_similar_items(): data['name'] = uuid4().hex - req, meta_rules = add_meta_rules(client, name=data['name'], data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(name=data['name'], data=data) + assert req.status == hug.HTTP_200 def test_add_two_meta_rules_with_different_combination_but_similar_items(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex meta_rule_name2 = uuid4().hex @@ -200,8 +260,8 @@ def test_add_two_meta_rules_with_different_combination_but_similar_items(): "object_categories": [object_category_id1, object_category_id2], "action_categories": [action_category_id1, action_category_id2] } - req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 data = { "name": meta_rule_name2, "subject_categories": [subject_category_id2], @@ -209,87 +269,147 @@ def test_add_two_meta_rules_with_different_combination_but_similar_items(): "action_categories": [action_category_id2] } - req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 + + +# This test Succeed as it's okay to have empty id in adding meta rule, as it is not attached to model yet +def test_add_meta_rules_with_empty_subject_in_mid(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + value = meta_rule_helper.get_body_meta_rule_with_empty_category_in_mid('subject') + with pytest.raises(exceptions.SubjectCategoryUnknown) as exception_info: + req = hug.test.post(meta_rules, "/meta_rules", body=value, + headers=auth_headers) + # assert req.status == hug.HTTP_200 + assert str(exception_info.value) == "400: Subject Category Unknown" + + +def test_add_meta_rules_with_empty_object_in_mid(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + value = meta_rule_helper.get_body_meta_rule_with_empty_category_in_mid('object') + with pytest.raises(exceptions.ObjectCategoryUnknown) as exception_info: + req = hug.test.post(meta_rules, "/meta_rules", body=value, + headers=auth_headers) + assert str(exception_info.value) == "400: Object Category Unknown" + + +def test_add_meta_rules_with_empty_action_in_mid(): + from moon_manager.api import meta_rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + value = meta_rule_helper.get_body_meta_rule_with_empty_category_in_mid('action') + with pytest.raises(exceptions.ActionCategoryUnknown) as exception_info: + req = hug.test.post(meta_rules, "/meta_rules", body=value, + headers=auth_headers) + assert str(exception_info.value) == "400: Action Category Unknown" def test_add_meta_rule_with_existing_name_error(): - client = utilities.register_client() name = uuid4().hex - req, meta_rules = add_meta_rules(client, name) - assert req.status_code == 200 - req, meta_rules = add_meta_rules(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Meta Rule Existing' + req, meta_rules = add_meta_rules(name) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.MetaRuleExisting) as exception_info: + req, meta_rules = add_meta_rules(name) + assert "409: Meta Rule Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Meta Rule Existing' def test_add_meta_rules_with_forbidden_char_in_name(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "<a>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, meta_rules = add_meta_rules("<a>") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_add_meta_rules_with_blank_name(): - client = utilities.register_client() - req, meta_rules = add_meta_rules(client, "") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Meta Rule Error' + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req, meta_rules = add_meta_rules("") + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Error' def test_add_meta_rules_without_subject_categories(): - client = utilities.register_client() name_meta_rule = uuid4().hex - req, meta_rules = add_meta_rules_without_category_ids(client, name_meta_rule) - assert req.status_code == 200 + req, meta_rules = add_meta_rules_without_category_ids(name_meta_rule) + assert req.status == hug.HTTP_200 def test_delete_meta_rules(): - client = utilities.register_client() name_meta_rule = uuid4().hex - req, meta_rules = add_meta_rules_without_category_ids(client, name_meta_rule) + req, meta_rules = add_meta_rules_without_category_ids(name_meta_rule) meta_rule_id = next(iter(meta_rules['meta_rules'])) - req = delete_meta_rules(client, meta_rules['meta_rules'][meta_rule_id]['name']) - assert req.status_code == 200 + req = delete_meta_rules(meta_rules['meta_rules'][meta_rule_id]['name']) + assert req.status == hug.HTTP_200 def test_delete_meta_rules_without_id(): - client = utilities.register_client() - req = delete_meta_rules_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Meta Rule Unknown" + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req = delete_meta_rules_without_id() + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Meta Rule Unknown" def test_update_meta_rules(): - client = utilities.register_client() - req = add_meta_rules(client, "testuser") + name = "testuser" + uuid4().hex + req = add_meta_rules(name) + meta_rule_id = list(req[1]['meta_rules'])[0] + req_update = update_meta_rules(name, meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + delete_meta_rules("testuser") + get_meta_rules() + + +def test_update_meta_rules_empty_name(): + req = add_meta_rules("testuser" + uuid4().hex) + meta_rule_id = list(req[1]['meta_rules'])[0] + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req_update = update_meta_rules("", meta_rule_id) + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Meta Rule Error' + + +def test_update_meta_rules_space_name(): + req = add_meta_rules("testuser" + uuid4().hex) meta_rule_id = list(req[1]['meta_rules'])[0] - req_update = update_meta_rules(client, "testuser", meta_rule_id) - assert req_update[0].status_code == 200 - delete_meta_rules(client, "testuser") - get_meta_rules(client) + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + req_update = update_meta_rules(" ", meta_rule_id) + assert "400: Meta Rule Error" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Meta Rule Error' def test_update_meta_rule_with_combination_existed(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name1) + req, meta_rules = add_meta_rules(meta_rule_name1) meta_rule_id1 = next(iter(meta_rules['meta_rules'])) data1 = meta_rules['meta_rules'][meta_rule_id1] meta_rule_name2 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name2) + req, meta_rules = add_meta_rules(meta_rule_name2) meta_rule_id2 = next(iter(meta_rules['meta_rules'])) data2 = meta_rules['meta_rules'][meta_rule_id2] data1['name'] = data2['name'] - req_update = update_meta_rules(client, name=meta_rule_name2, metaRuleId=meta_rule_id2, - data=data1) - assert req_update[0].status_code == 409 - assert req_update[1]['message']== '409: Meta Rule Existing' + with pytest.raises(exceptions.MetaRuleExisting) as exception_info: + req_update = update_meta_rules(name=meta_rule_name2, metaRuleId=meta_rule_id2, + data=data1) + assert "409: Meta Rule Existing" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_409 + # assert req_update[1]['message'] == '409: Meta Rule Existing' def test_update_meta_rule_with_different_combination_but_same_data(): - client = utilities.register_client() meta_rule_name1 = uuid4().hex subject_category = category_helper.add_subject_category( value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) @@ -316,47 +436,46 @@ def test_update_meta_rule_with_different_combination_but_same_data(): "object_categories": [object_category_id1, object_category_id2], "action_categories": [action_category_id1, action_category_id2] } - req, meta_rules = add_meta_rules(client, meta_rule_name1, data=data) - assert req.status_code == 200 + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 meta_rule_name2 = uuid4().hex - req, meta_rules = add_meta_rules(client, meta_rule_name2) + req, meta_rules = add_meta_rules(meta_rule_name2) meta_rule_id2 = next(iter(meta_rules['meta_rules'])) data2 = { "name": meta_rule_name2, "subject_categories": [subject_category_id1, subject_category_id2], "object_categories": [object_category_id1], - "action_categories": [action_category_id1,action_category_id2] + "action_categories": [action_category_id1, action_category_id2] } - req_update = update_meta_rules(client, name=meta_rule_name2, metaRuleId=meta_rule_id2, + req_update = update_meta_rules(name=meta_rule_name2, metaRuleId=meta_rule_id2, data=data2) - assert req_update[0].status_code == 200 + assert req_update[0].status == hug.HTTP_200 def test_update_meta_rules_without_id(): - client = utilities.register_client() - req_update = update_meta_rules(client, "testuser", "") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)["message"] == "400: Meta Rule Unknown" + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req_update = update_meta_rules("testuser", "") + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[0].data["message"] == "400: Meta Rule Unknown" def test_update_meta_rules_without_name(): - client = utilities.register_client() - req_update = update_meta_rules(client, "<br/>", "1234567") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)[ - "message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req_update = update_meta_rules("<br/>", "1234567") + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[0].data["message"] == "Key: 'name', [Forbidden characters in string]" def test_update_meta_rules_without_categories(): - client = utilities.register_client() - req_update = update_meta_rules_with_categories(client, "testuser") - assert req_update[0].status_code == 200 + req_update = update_meta_rules_with_categories("testuser" + uuid4().hex) + assert req_update[0].status == hug.HTTP_200 def test_update_meta_rules_with_empty_categories(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -364,14 +483,73 @@ def test_update_meta_rules_with_empty_categories(): "object_categories": [""], "action_categories": [""] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + # assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Subject Category Unknown' + + +def test_update_meta_rules_with_blank_subject_categories(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser1", + "subject_categories": [], + "object_categories": [object_category_id], + "action_categories": [action_category_id] + } + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + + assert req_update[0].status == hug.HTTP_200 + + +def test_update_meta_rules_with_blank_object_categories(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser1", + "subject_categories": [subject_category_id], + "object_categories": [], + "action_categories": [action_category_id] + } + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + + assert req_update[0].status == hug.HTTP_200 + + +def test_update_meta_rules_with_blank_action_categories(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser1", + "subject_categories": [subject_category_id], + "object_categories": [object_category_id], + "action_categories": [] + } + req_update = update_meta_rules_with_categories("testuser", data=data, meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Subject Category Unknown' + + assert req_update[0].status == hug.HTTP_200 + + +def test_update_meta_rules_with_empty_subject_category(): + subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() + data = { + "name": "testuser", + "subject_categories": [""], + "object_categories": [object_category_id], + "action_categories": [action_category_id] + } + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + # assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Subject Category Unknown' def test_update_meta_rules_with_empty_action_category(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -379,14 +557,15 @@ def test_update_meta_rules_with_empty_action_category(): "object_categories": [object_category_id], "action_categories": [""] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, - meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Action Category Unknown' + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert req_update[0].status == hug.HTTP_200 + # assert "400: Action Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Action Category Unknown' def test_update_meta_rules_with_empty_object_category(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -394,14 +573,16 @@ def test_update_meta_rules_with_empty_object_category(): "object_categories": [""], "action_categories": [action_category_id] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, - meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Object Category Unknown' + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + + assert req_update[0].status == hug.HTTP_200 + # assert "400: Object Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Object Category Unknown' def test_update_meta_rules_with_categories_and_one_empty(): - client = utilities.register_client() subject_category_id, object_category_id, action_category_id, meta_rule_id = data_builder.create_new_meta_rule() data = { "name": "testuser", @@ -409,7 +590,98 @@ def test_update_meta_rules_with_categories_and_one_empty(): "object_categories": [object_category_id, ""], "action_categories": [action_category_id, ""] } - req_update = update_meta_rules_with_categories(client, "testuser", data=data, - meta_rule_id=meta_rule_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Subject Category Unknown' + with pytest.raises(exceptions.SubjectCategoryUnknown) as exception_info: + req_update = update_meta_rules_with_categories("testuser", data=data, + meta_rule_id=meta_rule_id) + assert "400: Subject Category Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Subject Category Unknown' + + +def test_add_one_meta_rules_with_different_combination_but_similar_items(): + meta_rule_name1 = uuid4().hex + + subject_category = category_helper.add_subject_category( + value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) + subject_category_id1 = list(subject_category.keys())[0] + + object_category = category_helper.add_object_category( + value={"name": "object category name" + uuid4().hex, "description": "description 1"}) + object_category_id1 = list(object_category.keys())[0] + + action_category = category_helper.add_action_category( + value={"name": "action category name" + uuid4().hex, "description": "description 1"}) + action_category_id1 = list(action_category.keys())[0] + + subject_category = category_helper.add_subject_category( + value={"name": "subject category name" + uuid4().hex, "description": "description 1"}) + subject_category_id2 = list(subject_category.keys())[0] + + object_category = category_helper.add_object_category( + value={"name": "object category name" + uuid4().hex, "description": "description 1"}) + object_category_id2 = list(object_category.keys())[0] + + action_category = category_helper.add_action_category( + value={"name": "action category name" + uuid4().hex, "description": "description 1"}) + action_category_id2 = list(action_category.keys())[0] + + data = { + "name": meta_rule_name1, + "subject_categories": [subject_category_id1, subject_category_id2], + "object_categories": [object_category_id1, object_category_id2], + "action_categories": [action_category_id1, action_category_id2] + } + req, meta_rules = add_meta_rules(meta_rule_name1, data=data) + assert req.status == hug.HTTP_200 + + value = { + "name": "name_model", + "description": "test", + "meta_rules": [next(iter(meta_rules['meta_rules']))] + } + mode_id = next(iter(model_helper.add_model(value=value))) + + value = { + "name": "test_policy" + uuid4().hex, + "model_id": mode_id, + "genre": "authz", + "description": "test", + } + + policy_id = next(iter(policy_helper.add_policies(value=value))) + + data_id_1 = data_builder.create_subject_data(policy_id, subject_category_id1) + data_id_2 = data_builder.create_subject_data(policy_id, subject_category_id2) + data_id_3 = data_builder.create_object_data(policy_id, object_category_id2) + data_id_4 = data_builder.create_object_data(policy_id, object_category_id1) + data_id_5 = data_builder.create_action_data(policy_id, action_category_id1) + data_id_5 = data_builder.create_action_data(policy_id, action_category_id2) + + from moon_utilities.auth_functions import get_api_key_for_user + from falcon import HTTP_200, HTTP_400, HTTP_405, HTTP_409 + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy + + req = hug.test.delete(policy, "policies/{}".format(policy_id), headers=auth_headers) + assert req.status == HTTP_200 + + +def test_update_meta_rules_with_blank_action_categories_assigned_to_used_model(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import meta_rules + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + policies_list = policy_helper.add_policies_with_model() + policy_id = list(policies_list.keys())[0] + model_id = policies_list[policy_id]['model_id'] + models_list = model_helper.get_models(model_id=model_id) + meta_rule_id = models_list[model_id]["meta_rules"][0] + meta_rules_list = meta_rule_helper.get_meta_rules(meta_rule_id=meta_rule_id); + data = meta_rules_list[meta_rule_id] + + data["action_categories"] = [] + + with pytest.raises(exceptions.MetaRuleUpdateError) as exception_info: + hug.test.patch(meta_rules, "/meta_rules/{}".format(meta_rule_id), body=data, + headers=auth_headers) + assert "400: Meta_Rule Update Error" == str(exception_info.value) diff --git a/moon_manager/tests/unit_python/api/test_models.py b/moon_manager/tests/unit_python/api/test_models.py new file mode 100644 index 00000000..569fe1b4 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_models.py @@ -0,0 +1,475 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import json +import hug +import pytest +from moon_utilities import exceptions +from helpers import data_builder as builder +from helpers import policy_helper +from helpers import model_helper +from uuid import uuid4 + + +def get_models(): + from moon_manager.api import models + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(models, "/models", headers=auth_headers) + models = req.data + return req, models + + +def add_models(name, headers, data=None, ): + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule() + if not data: + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def update_model(name, model_id, headers): + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule() + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + headers['Content-Type'] = 'application/json' + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + if req.status == hug.HTTP_405: + return req + models = req.data + return req, models + + +def add_model_without_meta_rules_ids(name, headers): + from moon_manager.api import models + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [] + } + headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def add_model_with_empty_meta_rule_id(name, headers): + from moon_manager.api import models + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [""] + } + headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def update_model_without_meta_rules_ids(model_id, headers): + from moon_manager.api import models + name = "model_id" + uuid4().hex + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [] + } + headers['Content-Type'] = 'application/json' + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + models = req.data + return req, models + + +def delete_models(name, headers): + request, models = get_models() + for key, value in models['models'].items(): + if value['name'] == name: + from moon_manager.api import models + req = hug.test.delete(models, "/models/{}".format(key), headers=headers) + break + return req + + +def delete_models_without_id(headers): + from moon_manager.api import models + req = hug.test.delete(models, "/models/{}".format(""), headers=headers) + return req + + +def clean_models(headers): + req, models = get_models() + for key, value in models['models'].items(): + print(key) + print(value) + from moon_manager.api import models + hug.test.delete(models, "/models/{}".format(key), headers=headers) + + +def test_delete_model_assigned_to_policy(): + policy_name = "testuser" + uuid4().hex + req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(req.keys())[0] + data = { + "name": policy_name, + "description": "description of {}".format(policy_name), + "model_id": model_id, + "genre": "genre" + } + from moon_manager.api import policy + from moon_manager.api import models + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + hug.test.post(policy, "/policies", body=json.dumps(data), headers=headers) + with pytest.raises(exceptions.DeleteModelWithPolicy) as exception_info: + req = hug.test.delete(models, "/models/{}".format(model_id), headers={"X-Api-Key": + get_api_key_for_user("admin")}) + assert "400: Model With Policy Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Model With Policy Error' + + +def test_get_models(): + req, models = get_models() + assert req.status == hug.HTTP_200 + assert isinstance(models, dict) + assert "models" in models + + +def test_add_models(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req, models = add_models("testuser", auth_headers) + assert req.status == hug.HTTP_200 + assert isinstance(models, dict) + model_id = list(models["models"])[0] + assert "models" in models + assert models['models'][model_id]['name'] == "testuser" + assert models['models'][model_id]["description"] == "description of {}".format("testuser") + + +def test_add_models_with_meta_rule_has_blank_subject(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = "testuser1" + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule(empty="subject") + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + auth_headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_add_models_with_meta_rule_has_blank_object(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = "testuser1" + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule(empty="object") + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + auth_headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_add_models_with_meta_rule_has_blank_action(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = "testuser1" + from moon_manager.api import models + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule(empty="action") + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + auth_headers['Content-Type'] = 'application/json' + req = hug.test.post(models, "/models", body=json.dumps(data), + headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_delete_models(): + name = uuid4().hex + "testuser" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + add_models(name, auth_headers) + req = delete_models(name, headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_update_models_with_assigned_policy(): + from moon_manager.api import models + model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(model.keys())[0] + value = { + "name": "test_policy" + uuid4().hex, + "model_id": model_id, + "description": "test", + } + policy_helper.add_policies(value=value) + data = { + "name": "model_" + uuid4().hex, + "description": "description of model_2", + "meta_rules": [] + } + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + with pytest.raises(exceptions.DeleteModelWithPolicy) as exception_info: + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + assert "400: Model With Policy Error" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Model With Policy Error" + + +def test_update_models_with_no_assigned_policy(): + from moon_manager.api import models + model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(model.keys())[0] + data = { + "name": "model_" + uuid4().hex, + "description": "description of model_2", + "meta_rules": [] + } + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + assert req.status == hug.HTTP_200 + + +def test_update_models_without_meta_rule_key(): + from moon_manager.api import models + model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(model.keys())[0] + + data = { + "name": "model_" + uuid4().hex, + "description": "description of model_2", + } + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin"), 'Content-Type': 'application/json'} + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req = hug.test.patch(models, "/models/{}".format(model_id), body=json.dumps(data), + headers=headers) + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Meta Rule Unknown" + + +def test_delete_models_without_id(): + from moon_utilities.auth_functions import get_api_key_for_user + headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = delete_models_without_id(headers=headers) + assert req.status == hug.HTTP_405 + + +def test_add_model_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, models = add_models("<br/>", headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_add_model_with_name_contain_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req, models = add_models("test<br>user", headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_add_model_with_name_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.ModelContentError) as exception_info: + req, models = add_models(" ", headers=auth_headers) + assert "400: Model Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Model Unknown' + + +def test_add_model_with_empty_meta_rule_id(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + req, meta_rules = add_model_with_empty_meta_rule_id("testuser", headers=auth_headers) + assert "400: Meta Rule Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Meta Rule Unknown' + + +def test_add_model_with_existed_name(): + name = uuid4().hex + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req, models = add_models(name, headers=auth_headers) + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.ModelExisting) as exception_info: + req, models = add_models(name, headers=auth_headers) + assert "409: Model Error" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Model Error' + + +def test_add_model_with_existed_meta_rules_list(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + name = uuid4().hex + subject_category_id, object_category_id, action_category_id, meta_rule_id = \ + builder.create_new_meta_rule() + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + name = uuid4().hex + req, models = add_models(name=name, headers=auth_headers, data=data) + assert req.status == hug.HTTP_200 + data = { + "name": name, + "description": "description of {}".format(name), + "meta_rules": [meta_rule_id] + } + with pytest.raises(exceptions.ModelExisting) as exception_info: + req, models = add_models(name=name, headers=auth_headers, data=data) + assert "409: Model Error" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Model Error' + + +def test_add_model_without_meta_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req, meta_rules = add_model_without_meta_rules_ids("testuser", headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def test_update_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req = add_models("testuser", headers=auth_headers) + model_id = list(req[1]['models'])[0] + req_update = update_model("testuser", model_id, headers=auth_headers) + assert req_update[0].status == hug.HTTP_200 + model_id = list(req_update[1]["models"])[0] + assert req_update[1]["models"][model_id]["meta_rules"][0] is not None + delete_models("testuser", headers=auth_headers) + + +def test_update_model_name_with_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req = add_models("testuser", headers=auth_headers) + model_id = list(req[1]['models'])[0] + with pytest.raises(exceptions.ModelContentError) as exception_info: + req_update = update_model(" ", model_id, headers=auth_headers) + assert "400: Model Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]["message"] == '400: Model Unknown' + + +def test_update_model_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req = add_models("testuser", headers=auth_headers) + model_id = list(req[1]['models'])[0] + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ModelContentError) as exception_info: + req_update = update_model("", model_id, headers=auth_headers) + assert "400: Model Unknown" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[1]['message'] == '400: Model Unknown' + + +def test_update_meta_rules_without_id(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + clean_models(headers=auth_headers) + req_update = update_model("testuser", "", headers=auth_headers) + assert req_update.status == hug.HTTP_405 + + +def test_update_meta_rules_without_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req_update = update_model("<a></a>", "1234567", headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req_update[0].status == hug.HTTP_400 + # assert req_update[0].data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_update_meta_rules_without_meta_rules(): + value = { + "name": "mls_model_id" + uuid4().hex, + "description": "test", + "meta_rules": [] + } + model = model_helper.add_model(value=value) + model_id = list(model.keys())[0] + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req_update = update_model_without_meta_rules_ids(model_id, headers=auth_headers) + assert req_update[0].status == hug.HTTP_200 diff --git a/moon_manager/tests/unit_python/api/test_nova.py b/moon_manager/tests/unit_python/api/test_nova.py new file mode 100644 index 00000000..10118cc3 --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_nova.py @@ -0,0 +1,58 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + + +def create_project(tenant_dict): + from moon_manager.pip_driver import InformationManager + return InformationManager["objects"][0].create_project(**tenant_dict) + + +def list_projects(): + from moon_manager.pip_driver import InformationManager + return InformationManager["objects"][0].get_projects() + + +def list_objects(): + from moon_manager.pip_driver import InformationManager + print(f"IM : {InformationManager['objects'][0].driver.__dict__}") + return InformationManager["objects"][0].get_items() + + +def test_create_project(): + tenant_dict = { + "description": "test_project", + "domain": ['domain_id_1'], + "enabled": True, + "is_domain": False, + "name": 'project_1' + } + project = create_project(tenant_dict) + assert project + assert project.get('name') == tenant_dict.get('name') + + +def test_list_objects(): + objects = list_objects() + assert objects + assert objects["servers"][0].get('name') == "vm1" + +# TODO TO BE UPDATED +# def test_create_project_without_name(): +# tenant_dict = { +# "description": "test_project", +# "domain_id": ['domain_id_1'], +# "enabled": True, +# "is_domain": False, +# } +# with pytest.raises(Exception) as exception_info: +# create_project(tenant_dict) +# assert '400: Keystone project error' == str(exception_info.value) diff --git a/moon_manager/tests/unit_python/api/test_pdp.py b/moon_manager/tests/unit_python/api/test_pdp.py index 53a87b21..32b75726 100644 --- a/moon_manager/tests/unit_python/api/test_pdp.py +++ b/moon_manager/tests/unit_python/api/test_pdp.py @@ -1,48 +1,135 @@ -import json -import api.utilities as utilities -from helpers import data_builder as builder -from uuid import uuid4 +# Software Name: MOON +# Version: 5.4 -def get_pdp(client): - req = client.get("/pdp") - pdp = utilities.get_json(req.data) - return req, pdp +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. -def add_pdp(client, data): - req = client.post("/pdp", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - pdp = utilities.get_json(req.data) - return req, pdp +from falcon import HTTP_200, HTTP_400, HTTP_405 +import hug +import pytest +from moon_utilities import exceptions +from uuid import uuid4 +from helpers import data_builder as builder -def update_pdp(client, data, pdp_id): - req = client.patch("/pdp/{}".format(pdp_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - pdp = utilities.get_json(req.data) - return req, pdp +def test_get_pdp(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + req = hug.test.get(pdp, 'pdp/', headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + assert "pdps" in req.data -def delete_pdp(client, key): - req = client.delete("/pdp/{}".format(key)) - return req +def test_add_pdp_invalid_security_pipeline(mocker): + from moon_manager.api import pdp + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + data_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + data_no_project_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": None, + "description": "description of testuser" + } + data_no_project = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": None, + "description": "description of testuser" + } + + req = hug.test.post(pdp, "pdp/", data_no_project_no_pipeline, headers=auth_headers) + assert req.status == HTTP_200 + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.post(pdp, "pdp/", data_no_pipeline, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) -def delete_pdp_without_id(client): - req = client.delete("/pdp/{}".format("")) - return req + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.post(pdp, "pdp/", data_no_project, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) +def test_update_pdp_invalid_security_pipeline(mocker): + from moon_manager.api import pdp + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + data_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + data_no_project_no_pipeline = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [], + "vim_project_id": None, + "description": "description of testuser" + } + data_no_project = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": None, + "description": "description of testuser" + } -def test_get_pdp(): - client = utilities.register_client() - req, pdp = get_pdp(client) - assert req.status_code == 200 - assert isinstance(pdp, dict) - assert "pdps" in pdp + data_valid = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + req = hug.test.post(pdp, "pdp/", data_valid, headers=auth_headers) + assert req.status == HTTP_200 + pip_id = list(req.data['pdps'])[0] + + req = hug.test.patch(pdp, "pdp/{}".format(pip_id), data_no_project_no_pipeline, headers=auth_headers) + assert req.status == HTTP_200 + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.patch(pdp, "pdp/{}".format(pip_id), data_no_pipeline, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) -def test_add_pdp(): + with pytest.raises(exceptions.PdpContentError) as exception_info: + req = hug.test.patch(pdp, "pdp/{}".format(pip_id), data_no_project, headers=auth_headers) + assert "400: Pdp Error" == str(exception_info.value) + +def test_add_pdp(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -50,71 +137,182 @@ def test_add_pdp(): meta_rule_name="meta_rule_1" + uuid4().hex, model_name="model1" + uuid4().hex) data = { - "name": "testuser", + "name": "testuser" + uuid4().hex, "security_pipeline": [policy_id], - "keystone_project_id": "keystone_project_id", + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req, pdp = add_pdp(client, data) - assert req.status_code == 200 - assert isinstance(pdp, dict) - value = list(pdp["pdps"].values())[0] - assert "pdps" in pdp - assert value['name'] == "testuser" - assert value["description"] == "description of {}".format("testuser") - assert value["keystone_project_id"] == "keystone_project_id" + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + found = False + assert "pdps" in req.data + for value in req.data["pdps"].values(): + if value['name'] == data['name']: + found = True + assert value["description"] == "description of {}".format("testuser") + assert value["vim_project_id"] == "vim_project_id" + break + assert found -def test_delete_pdp(): - client = utilities.register_client() - request, pdp = get_pdp(client) - success_req = None - for key, value in pdp['pdps'].items(): - if value['name'] == "testuser": - success_req = delete_pdp(client, key) - break - assert success_req - assert success_req.status_code == 200 +def test_add_pdp_name_existed(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + name = "testuser" + uuid4().hex + data = { + "name": name, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id", + "description": "description of testuser" + } + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) -def test_add_pdp_with_forbidden_char_in_user(): data = { - "name": "<a>", - "security_pipeline": ["policy_id_1", "policy_id_2"], - "keystone_project_id": "keystone_project_id", + "name": name, + "security_pipeline": [policy_id2], + "vim_project_id": "vim_project_id" + uuid4().hex, + "description": "description of testuser" + uuid4().hex + } + with pytest.raises(exceptions.PdpExisting) as exception_info: + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert "409: Pdp Error" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Pdp Error' + + +def test_add_pdp_policy_used(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + + data = { + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req, models = add_pdp(client, data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + + name_uuid = "testuser" + uuid4().hex + data = { + "name": name_uuid, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id " + name_uuid, + "description": "description of testuser " + name_uuid + } + with pytest.raises(exceptions.PdpInUse) as exception_info: + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert "400: Pdp Inuse" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data['message'] == '409: Pdp Conflict' -def test_add_pdp_with_forbidden_char_in_keystone(): + +def test_delete_pdp(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) data = { - "name": "testuser", - "security_pipeline": ["policy_id_1", "policy_id_2"], - "keystone_project_id": "<a>", + "name": "testuser" + uuid4().hex, + "security_pipeline": [policy_id], + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req, meta_rules = add_pdp(client, data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'keystone_project_id', [Forbidden characters in string]" + req = hug.test.post(pdp, "pdp/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + req = hug.test.get(pdp, 'pdp/', headers=auth_headers) + success_req = None + for key, value in req.data['pdps'].items(): + if value['name'] == data['name']: + success_req = hug.test.delete(pdp, 'pdp/{}'.format(key), headers=auth_headers) + break + assert success_req + assert success_req.status == HTTP_200 + +# Fixme: should re-enabled the input validation for those tests +# def test_add_pdp_with_forbidden_char_in_user(): +# data = { +# "name": "<a>", +# "security_pipeline": ["policy_id_1", "policy_id_2"], +# "vim_project_id": "vim_project_id", +# "description": "description of testuser" +# } +# req = hug.test.post(pdp, "pdp/", data) +# assert req.status == HTTP_400 +# print(req.data) +# assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" +# +# +# def test_add_pdp_with_forbidden_char_in_keystone(): +# data = { +# "name": "testuser", +# "security_pipeline": ["policy_id_1", "policy_id_2"], +# "vim_project_id": "<a>", +# "description": "description of testuser" +# } +# req = hug.test.post(pdp, "pdp/", data) +# assert req.status == 400 +# assert req.data["message"] == "Key: 'vim_project_id', [Forbidden characters in string]" -def test_update_pdp(): + +def test_update_pdp(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( - subject_category_name="subject_category1"+uuid4().hex, - object_category_name="object_category1"+uuid4().hex, - action_category_name="action_category1"+uuid4().hex, - meta_rule_name="meta_rule_1"+uuid4().hex, - model_name="model1"+uuid4().hex) + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) data_add = { "name": "testuser", "security_pipeline": [policy_id], - "keystone_project_id": "keystone_project_id", + "vim_project_id": "vim_project_id", "description": "description of testuser" } @@ -125,40 +323,157 @@ def test_update_pdp(): meta_rule_name="meta_rule_1" + uuid4().hex, model_name="model1" + uuid4().hex) data_update = { - "name": "testuser", + "name": "testuser_updated", "security_pipeline": [policy_id_update], - "keystone_project_id": "keystone_project_id_update", - "description": "description of testuser" + "vim_project_id": "vim_project_id_update", + "description": "description of testuser_updated" } - client = utilities.register_client() - req = add_pdp(client, data_add) - pdp_id = list(req[1]['pdps'])[0] - req_update = update_pdp(client, data_update, pdp_id) - assert req_update[0].status_code == 200 - value = list(req_update[1]["pdps"].values())[0] - assert value["keystone_project_id"] == "keystone_project_id_update" - request, pdp = get_pdp(client) - for key, value in pdp['pdps'].items(): + req = hug.test.post(pdp, "pdp/", data_add, headers=auth_headers) + pdp_id = list(req.data['pdps'])[0] + req_update = hug.test.patch(pdp, "pdp/{}".format(pdp_id), data_update, headers=auth_headers) + assert req_update.status == HTTP_200 + value = list(req_update.data["pdps"].values())[0] + assert value["vim_project_id"] == data_update["vim_project_id"] + assert value["description"] == data_update["description"] + assert value["name"] == data_update['name'] + assert value["security_pipeline"] == data_update['security_pipeline'] + req = hug.test.get(pdp, 'pdp/', headers=auth_headers) + for key, value in req.data['pdps'].items(): if value['name'] == "testuser": - delete_pdp(client, key) + hug.test.delete(pdp, 'pdp/{}'.format(key), headers=auth_headers) break -def test_update_pdp_without_id(): - client = utilities.register_client() - req_update = update_pdp(client, "testuser", "") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)["message"] == 'Invalid Key :name not found' +def test_update_pdp_without_id(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + req = hug.test.patch(pdp, "pdp/", "testuser", headers=auth_headers) + assert req.status == HTTP_405 + # assert req.data["message"] == 'Invalid Key :name not found' -def test_update_pdp_without_user(): +def test_update_pdp_without_user(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) data = { "name": "", "security_pipeline": ["policy_id_1", "policy_id_2"], - "keystone_project_id": "keystone_project_id", + "vim_project_id": "vim_project_id", "description": "description of testuser" } - client = utilities.register_client() - req_update = update_pdp(client, data, "<a>") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)["message"] == "Forbidden characters in string" + req = hug.test.patch(pdp, "pdp/<a>", data, headers=auth_headers) + assert req.status == HTTP_400 + print(req.data) + assert req.data["errors"] == {'uuid': 'Invalid UUID provided'} + + +def test_update_pdp_name_existed(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + uuid1 = uuid4().hex + data1 = { + "name": "testuser1" + uuid1, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id" + uuid1, + "description": "description of testuser1" + uuid1 + } + req = hug.test.post(pdp, "pdp/", data1, headers=auth_headers) + assert req.status == HTTP_200 + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + + uuid2 = uuid4().hex + data2 = { + "name": "testuser2" + uuid2, + "security_pipeline": [policy_id2], + "vim_project_id": "vim_project_id" + uuid2, + "description": "description of testuser2" + uuid2 + } + req = hug.test.post(pdp, "pdp/", data2, headers=auth_headers) + pdp_id = list(req.data['pdps'])[0] + for item in list(req.data['pdps']): + if req.data['pdps'][item]['name']==data2['name']: + pdp_id=item + break + data2['name'] = data1['name'] + with pytest.raises(exceptions.PdpExisting) as exception_info: + req_update = hug.test.patch(pdp, "pdp/{}".format(pdp_id), data2, headers=auth_headers) + # assert req_update.data['message'] == '409: Pdp Error' + assert "409: Pdp Error" == str(exception_info.value) + + + +def test_update_pdp_policy_used(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import pdp + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:20000") + mocker.patch("subprocess.Popen", return_value=True) + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id1 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + uuid1 = uuid4().hex + data1 = { + "name": "testuser1" + uuid1, + "security_pipeline": [policy_id1], + "vim_project_id": "vim_project_id" + uuid1, + "description": "description of testuser1" + uuid1 + } + req = hug.test.post(pdp, "pdp/", data1, headers=auth_headers) + assert req.status == HTTP_200 + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id2 = builder.create_new_policy( + subject_category_name="subject_category1" + uuid4().hex, + object_category_name="object_category1" + uuid4().hex, + action_category_name="action_category1" + uuid4().hex, + meta_rule_name="meta_rule_1" + uuid4().hex, + model_name="model1" + uuid4().hex) + + uuid2 = uuid4().hex + data2 = { + "name": "testuser2" + uuid2, + "security_pipeline": [policy_id2], + "vim_project_id": "vim_project_id" + uuid2, + "description": "description of testuser2" + uuid2 + } + req = hug.test.post(pdp, "pdp/", data2, headers=auth_headers) + pdp_id = list(req.data['pdps'])[0] + for item in list(req.data['pdps']): + if req.data['pdps'][item]['name']==data2['name']: + pdp_id=item + break + data2['security_pipeline'] = data1['security_pipeline'] + + with pytest.raises(exceptions.PdpInUse) as exception_info: + req_update = hug.test.patch(pdp, "pdp/{}".format(pdp_id), data2, headers=auth_headers) + assert "400: Pdp Inuse" == str(exception_info.value) + # assert req_update.data['message'] == '409: Pdp Conflict' + + diff --git a/moon_manager/tests/unit_python/api/test_perimeter.py b/moon_manager/tests/unit_python/api/test_perimeter.py index ff7b09d7..c741adf7 100644 --- a/moon_manager/tests/unit_python/api/test_perimeter.py +++ b/moon_manager/tests/unit_python/api/test_perimeter.py @@ -1,19 +1,39 @@ -# import moon_manager -# import moon_manager.api -import json +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug import api.utilities as utilities from helpers import data_builder as builder import helpers.policy_helper as policy_helper from uuid import uuid4 +import pytest +from moon_utilities import exceptions + +def get_subjects(subject_id=None): + from moon_manager.api import perimeter + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def get_subjects(client): - req = client.get("/subjects") + if not subject_id: + req = hug.test.get(perimeter, 'subjects/', headers=auth_headers) + else: + req = hug.test.get(perimeter, 'subjects/{}'.format(subject_id), headers=auth_headers) subjects = utilities.get_json(req.data) return req, subjects -def add_subjects(client, policy_id, name, perimeter_id=None, data=None): +def add_subjects(policy_id, name, perimeter_id=None, data=None, auth_headers=None): + from moon_manager.api import perimeter if not data: name = name + uuid4().hex data = { @@ -23,44 +43,44 @@ def add_subjects(client, policy_id, name, perimeter_id=None, data=None): "email": "{}@moon".format(name) } if not perimeter_id: - req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/subjects".format(policy_id), + body=data, headers=auth_headers) else: - req = client.post("/policies/{}/subjects/{}".format(policy_id, perimeter_id), - data=json.dumps( - data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/subjects/{}".format(policy_id, perimeter_id), + body=data, headers=auth_headers) subjects = utilities.get_json(req.data) return req, subjects -def delete_subjects_without_perimeter_id(client): - req = client.delete("/subjects/{}".format("")) +def delete_subjects_without_perimeter_id(auth_headers=None): + from moon_manager.api import perimeter + req = hug.test.delete(perimeter, "/subjects/{}".format(""), headers=auth_headers) return req def test_perimeter_get_subject(): - client = utilities.register_client() - req, subjects = get_subjects(client) - assert req.status_code == 200 + req, subjects = get_subjects() + assert req.status == hug.HTTP_200 assert isinstance(subjects, dict) assert "subjects" in subjects def test_perimeter_add_subject(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value["name"] assert value["email"] def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] name = "testuser" @@ -71,13 +91,15 @@ def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - add_subjects(client, policy_id1, data['name'], perimeter_id=perimeter_id, data=data) + add_subjects(policy_id1, data['name'], perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) policies2 = policy_helper.add_policies() policy_id2 = list(policies2.keys())[0] - req, subjects = add_subjects(client, policy_id2, data['name'], - perimeter_id=perimeter_id, data=data) + req, subjects = add_subjects(policy_id2, data['name'], + perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value["name"] assert value["email"] assert len(value['policy_list']) == 2 @@ -86,20 +108,25 @@ def test_perimeter_add_same_subject_perimeter_id_with_new_policy_id(): def test_perimeter_add_same_subject_perimeter_id_with_different_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id = uuid4().hex - add_subjects(client, policy_id1, "testuser", perimeter_id=perimeter_id) + add_subjects(policy_id1, "testuser", perimeter_id=perimeter_id, auth_headers=auth_headers) policies2 = policy_helper.add_policies() policy_id2 = list(policies2.keys())[0] - req, subjects = add_subjects(client, policy_id2, "testuser", perimeter_id=perimeter_id) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req, subjects = add_subjects(policy_id2, "testuser", perimeter_id=perimeter_id, + auth_headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_add_same_subject_name_with_new_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id = uuid4().hex @@ -110,8 +137,8 @@ def test_perimeter_add_same_subject_name_with_new_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id1, None, perimeter_id=perimeter_id, - data=data) + req, subjects = add_subjects(policy_id1, None, perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) policies2 = policy_helper.add_policies() policy_id2 = list(policies2.keys())[0] value = list(subjects["subjects"].values())[0] @@ -121,9 +148,9 @@ def test_perimeter_add_same_subject_name_with_new_policy_id(): "password": "password for {}".format(value['name']), "email": "{}@moon".format(value['name']) } - req, subjects = add_subjects(client, policy_id2, None, data=data) + req, subjects = add_subjects(policy_id2, None, data=data, auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value["name"] assert value["email"] assert len(value['policy_list']) == 2 @@ -132,7 +159,8 @@ def test_perimeter_add_same_subject_name_with_new_policy_id(): def test_perimeter_add_same_subject_name_with_same_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id = uuid4().hex @@ -143,8 +171,8 @@ def test_perimeter_add_same_subject_name_with_same_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id1, None, perimeter_id=perimeter_id, - data=data) + req, subjects = add_subjects(policy_id1, None, perimeter_id=perimeter_id, + data=data, auth_headers=auth_headers) value = list(subjects["subjects"].values())[0] data = { "name": value['name'], @@ -152,31 +180,46 @@ def test_perimeter_add_same_subject_name_with_same_policy_id(): "password": "password for {}".format(value['name']), "email": "{}@moon".format(value['name']) } - req, subjects = add_subjects(client, policy_id1, None, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, subjects = add_subjects(policy_id1, None, data=data, auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_same_subject_perimeter_id_with_existed_policy_id_in_list(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] name = "testuser" + uuid4().hex data = { - "name": name, + "name": name + uuid4().hex, "description": "description of {}".format(name), "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id, name, data=data) + subj_id = "b34e5a29-5494-4cc5-9356-daa244b8c254" + req, subjects = get_subjects(subj_id) + if subjects['subjects']: + for __policy_id in subjects['subjects'][subj_id]['policy_list']: + req = hug.test.delete(perimeter, + "/policies/{}/subjects/{}".format(__policy_id, subj_id), + headers=auth_headers) + req, subjects = add_subjects(policy_id, name, data=data, auth_headers=auth_headers) perimeter_id = list(subjects["subjects"].values())[0]['id'] - req, subjects = add_subjects(client, policy_id, name, perimeter_id=perimeter_id, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, subjects = add_subjects(policy_id, name, perimeter_id=perimeter_id, data=data, + auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_subject_invalid_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] name = "testuser" @@ -186,103 +229,121 @@ def test_perimeter_add_subject_invalid_policy_id(): "password": "password for {}".format(name), "email": "{}@moon".format(name) } - req, subjects = add_subjects(client, policy_id + "0", "testuser", data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req, subjects = add_subjects( policy_id + "0", "testuser", data, auth_headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' -def test_perimeter_add_subject_policy_id_none(): - client = utilities.register_client() - name = "testuser" - data = { - "name": name + uuid4().hex, - "description": "description of {}".format(name), - "password": "password for {}".format(name), - "email": "{}@moon".format(name) - } - req, subjects = add_subjects(client, None, "testuser", data) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' +def test_perimeter_add_subject_blank_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + policies = policy_helper.add_policies() + policy_id = list(policies.keys())[0] + with pytest.raises(exceptions.ValidationKeyError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/subjects".format(policy_id), body={'test':"aa"}, + headers=auth_headers) + assert "Invalid Key :name not found" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == 'Invalid Key :name not found' def test_perimeter_add_subject_with_forbidden_char_in_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "<a>", "description": "description of {}".format(""), "password": "password for {}".format(""), "email": "{}@moon".format("") } - req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + subj_id = "a34e5a29-5494-4cc5-9356-daa244b8c888" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/subjects".format(subj_id), body=data, + headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_perimeter_update_subject_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update" } - req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] == value2['description'] def test_perimeter_update_subject_description(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update", } - req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_subject_description_and_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update", 'name': value1['name'] + "update" } - req = client.patch("/subjects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + from moon_manager.api import perimeter + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["subjects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_subject_wrong_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -290,64 +351,83 @@ def test_perimeter_update_subject_wrong_id(): "name": name, "description": "description of {}".format('testuser'), } - req, subjects = add_subjects(client, policy_id=policy_id1, name='testuser', data=data) + req, subjects = add_subjects(policy_id=policy_id1, name='testuser', data=data, + auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/subjects/{}".format(perimeter_id + "wrong"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id + "wrong"), + body=data, headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_update_subject_name_with_existed_one(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name1 = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] perimeter_id1 = uuid4().hex - req, subjects = add_subjects(client, policy_id=policy_id1, name=name1, - perimeter_id=perimeter_id1) + req, subjects = add_subjects(policy_id=policy_id1, name=name1, + perimeter_id=perimeter_id1, auth_headers=auth_headers) value1 = list(subjects["subjects"].values())[0] perimeter_id2 = uuid4().hex name2 = 'testuser' + uuid4().hex - req, subjects = add_subjects(client, policy_id=policy_id1, name=name2, - perimeter_id=perimeter_id2) + req, subjects = add_subjects(policy_id=policy_id1, name=name2, + perimeter_id=perimeter_id2, auth_headers=auth_headers) data = { 'name': value1['name'], } - req = client.patch("/subjects/{}".format(perimeter_id2), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 + with pytest.raises(exceptions.SubjectExisting) as exception_info: + req = hug.test.patch(perimeter, "/subjects/{}".format(perimeter_id2), body=data, + headers=auth_headers) + assert "409: Subject Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 def test_perimeter_delete_subject(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - req, subjects = add_subjects(client, policy_id, "testuser") + req, subjects = add_subjects(policy_id, "testuser", auth_headers=auth_headers) subject_id = list(subjects["subjects"].values())[0]["id"] - req = client.delete("/policies/{}/subjects/{}".format(policy_id, subject_id)) - assert req.status_code == 200 + req = hug.test.delete(perimeter, "/policies/{}/subjects/{}".format(policy_id, subject_id), + headers=auth_headers) + assert req.status == hug.HTTP_200 def test_perimeter_delete_subjects_without_perimeter_id(): - client = utilities.register_client() - req = delete_subjects_without_perimeter_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Subject Unknown" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + with pytest.raises(exceptions.SubjectUnknown) as exception_info: + req = delete_subjects_without_perimeter_id(auth_headers) + assert "400: Subject Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Subject Unknown" -def get_objects(client): - req = client.get("/objects") +def get_objects(): + from moon_manager.api import perimeter + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(perimeter, "/objects", headers=auth_headers) objects = utilities.get_json(req.data) return req, objects -def add_objects(client, name, policyId=None, data=None, perimeter_id=None): +def add_objects(name, policyId=None, data=None, perimeter_id=None, auth_headers=None): + from moon_manager.api import perimeter if not policyId: subject_category_id, object_category_id, action_category_id, meta_rule_id, policyId = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, @@ -361,59 +441,70 @@ def add_objects(client, name, policyId=None, data=None, perimeter_id=None): "description": "description of {}".format(name), } if not perimeter_id: - req = client.post("/policies/{}/objects/".format(policyId), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/objects/".format(policyId), body=data, + headers=auth_headers) else: - req = client.post("/policies/{}/objects/{}".format(policyId, perimeter_id), - data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/objects/{}".format(policyId, perimeter_id), + body=data, headers=auth_headers) + objects = utilities.get_json(req.data) return req, objects -def delete_objects_without_perimeter_id(client): - req = client.delete("/objects/{}".format("")) +def delete_objects_without_perimeter_id(auth_headers=None): + from moon_manager.api import perimeter + req = hug.test.delete(perimeter, "/objects/{}".format(""), headers=auth_headers) return req def test_perimeter_get_object(): - client = utilities.register_client() - req, objects = get_objects(client) - assert req.status_code == 200 + + req, objects = get_objects() + assert req.status == hug.HTTP_200 assert isinstance(objects, dict) assert "objects" in objects def test_perimeter_add_object(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects("testuser", auth_headers=auth_headers) value = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value['name'] def test_perimeter_add_object_with_wrong_policy_id(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser", policyId='wrong') - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req, objects = add_objects("testuser", policyId='wrong', auth_headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_object_with_policy_id_none(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser" + uuid4().hex, "description": "description of {}".format("testuser"), } - req = client.post("/policies/{}/objects/".format(None), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format(None), body=data, + headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_same_object_name_with_new_policy_id(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects("testuser", auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -421,16 +512,17 @@ def test_perimeter_add_same_object_name_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, auth_headers=auth_headers) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_object_perimeter_id_with_new_policy_id(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects( "testuser", auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -438,17 +530,18 @@ def test_perimeter_add_same_object_perimeter_id_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data, - perimeter_id=value1['id']) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + perimeter_id=value1['id'],auth_headers=auth_headers) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_object_perimeter_id_with_different_name(): - client = utilities.register_client() - req, objects = add_objects(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, objects = add_objects( "testuser", auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -456,14 +549,17 @@ def test_perimeter_add_same_object_perimeter_id_with_different_name(): "name": value1['name'] + 'different', "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data, - perimeter_id=value1['id']) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_add_same_object_name_with_same_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -471,16 +567,20 @@ def test_perimeter_add_same_object_name_with_same_policy_id(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, auth_headers=auth_headers) value = list(objects["objects"].values())[0] - assert req.status_code == 200 - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + + assert req.status == hug.HTTP_200 + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, objects = add_objects('testuser', policyId=policy_id1, data=data, auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_same_object_perimeter_id_with_existed_policy_id_in_list(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -488,16 +588,21 @@ def test_perimeter_add_same_object_perimeter_id_with_existed_policy_id_in_list() "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects( 'testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value = list(objects["objects"].values())[0] - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data, - perimeter_id=value['id']) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + perimeter_id=value['id'], auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_update_object_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -505,26 +610,30 @@ def test_perimeter_update_object_name(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id), body=data, + headers=auth_headers) objects = utilities.get_json(req.data) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] == value2['description'] def test_perimeter_update_object_description(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -532,26 +641,30 @@ def test_perimeter_update_object_description(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id), body=data, + headers=auth_headers) objects = utilities.get_json(req.data) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_object_description_and_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -559,7 +672,8 @@ def test_perimeter_update_object_description_and_name(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] @@ -567,19 +681,21 @@ def test_perimeter_update_object_description_and_name(): 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id), body=data, + headers=auth_headers) objects = utilities.get_json(req.data) value2 = list(objects["objects"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_object_wrong_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -587,7 +703,8 @@ def test_perimeter_update_object_wrong_id(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data) + req, objects = add_objects('testuser', policyId=policy_id1, data=data, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] perimeter_id = value1['id'] @@ -595,13 +712,17 @@ def test_perimeter_update_object_wrong_id(): 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/objects/{}".format(perimeter_id + "wrong"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id + "wrong"), body=data, + headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 def test_perimeter_update_object_name_with_existed_one(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter name = 'testuser' + uuid4().hex policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -609,7 +730,8 @@ def test_perimeter_update_object_name_with_existed_one(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data1) + req, objects = add_objects('testuser', policyId=policy_id1, data=data1, + auth_headers=auth_headers) value1 = list(objects["objects"].values())[0] name = 'testuser' + uuid4().hex @@ -618,7 +740,8 @@ def test_perimeter_update_object_name_with_existed_one(): "name": name, "description": "description of {}".format('testuser'), } - req, objects = add_objects(client, 'testuser', policyId=policy_id1, data=data2) + req, objects = add_objects('testuser', policyId=policy_id1, data=data2, + auth_headers=auth_headers) value2 = list(objects["objects"].values())[0] perimeter_id2 = value2['id'] @@ -626,59 +749,113 @@ def test_perimeter_update_object_name_with_existed_one(): data3 = { 'name': value1['name'] } - req = client.patch("/objects/{}".format(perimeter_id2), data=json.dumps(data3), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Object Existing' + with pytest.raises(exceptions.ObjectExisting) as exception_info: + req = hug.test.patch(perimeter, "/objects/{}".format(perimeter_id2), body=data3, + headers=auth_headers) + assert "409: Object Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Object Existing' def test_perimeter_add_object_without_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "<br/>", "description": "description of {}".format(""), } - req = client.post("/policies/{}/objects/".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_perimeter_add_object_blank_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + with pytest.raises(exceptions.ValidationKeyError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body={}, headers=auth_headers) + assert "Invalid Key :name not found" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == 'Invalid Key :name not found' def test_perimeter_add_object_with_name_contain_spaces(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "test<a>user", "description": "description of {}".format("test user"), } - req = client.post("/policies/{}/objects/".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), body=data, + headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" + + +def test_perimeter_add_object_with_name_space(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + data = { + "name": " ", + "description": "description of {}".format("test user"), + } + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects/".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body =data, headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_delete_object(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] object_id = builder.create_object(policy_id) - req = client.delete("/policies/{}/objects/{}".format(policy_id, object_id)) - assert req.status_code == 200 + req = hug.test.delete(perimeter, "/policies/{}/objects/{}".format(policy_id, object_id), headers=auth_headers) + + assert req.status == hug.HTTP_200 def test_perimeter_delete_objects_without_perimeter_id(): - client = utilities.register_client() - req = delete_objects_without_perimeter_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Object Unknown" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ObjectUnknown) as exception_info: + req = delete_objects_without_perimeter_id(auth_headers=auth_headers) + assert "400: Object Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Object Unknown" -def get_actions(client): - req = client.get("/actions") + +def get_actions(): + from moon_manager.api import perimeter + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.get(perimeter, "/actions", headers=auth_headers) actions = utilities.get_json(req.data) return req, actions -def add_actions(client, name, policy_id=None, data=None, perimeter_id=None): +def add_actions(name, policy_id=None, data=None, perimeter_id=None, auth_headers=None): + from moon_manager.api import perimeter if not policy_id: subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy( subject_category_name="subject_category1" + uuid4().hex, @@ -693,60 +870,72 @@ def add_actions(client, name, policy_id=None, data=None, perimeter_id=None): "description": "description of {}".format(name), } if not perimeter_id: - req = client.post("/policies/{}/actions/".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/actions/".format(policy_id), body=data, + headers=auth_headers) else: - req = client.post("/policies/{}/actions/{}".format(policy_id, perimeter_id), - data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(perimeter, "/policies/{}/actions/{}".format(policy_id, perimeter_id), + body=data, headers=auth_headers) actions = utilities.get_json(req.data) return req, actions -def delete_actions_without_perimeter_id(client): - req = client.delete("/actions/{}".format("")) +def delete_actions_without_perimeter_id(auth_headers=None): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req = hug.test.delete(perimeter, "/actions/{}".format(""), headers=auth_headers) return req def test_perimeter_get_actions(): - client = utilities.register_client() - req, actions = get_actions(client) - assert req.status_code == 200 + + req, actions = get_actions() + + assert req.status == hug.HTTP_200 assert isinstance(actions, dict) assert "actions" in actions def test_perimeter_add_actions(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, actions = add_actions("testuser", auth_headers=auth_headers) value = list(actions["actions"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value['name'] def test_perimeter_add_action_with_wrong_policy_id(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser", policy_id="wrong") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req, actions = add_actions("testuser", policy_id="wrong", auth_headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_action_with_policy_id_none(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser" + uuid4().hex, "description": "description of {}".format("testuser"), } - req = client.post("/policies/{}/actions/".format(None), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions/".format(None), body=data, + headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Policy Unknown' def test_perimeter_add_same_action_name_with_new_policy_id(): - client = utilities.register_client() - req, action = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, action = add_actions("testuser", auth_headers=auth_headers) value1 = list(action["actions"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -754,16 +943,18 @@ def test_perimeter_add_same_action_name_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data) + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + auth_headers=auth_headers) value2 = list(action["actions"].values())[0] - assert req.status_code == 200 + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_action_perimeter_id_with_new_policy_id(): - client = utilities.register_client() - req, action = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, action = add_actions("testuser", auth_headers=auth_headers) value1 = list(action["actions"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -771,17 +962,19 @@ def test_perimeter_add_same_action_perimeter_id_with_new_policy_id(): "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data, - perimeter_id=value1['id']) + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) value2 = list(action["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['id'] == value2['id'] assert value1['name'] == value2['name'] def test_perimeter_add_same_action_perimeter_id_with_different_name(): - client = utilities.register_client() - req, action = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, action = add_actions("testuser", auth_headers=auth_headers) value1 = list(action["actions"].values())[0] policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] @@ -789,240 +982,323 @@ def test_perimeter_add_same_action_perimeter_id_with_different_name(): "name": value1['name'] + 'different', "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data, - perimeter_id=value1['id']) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_add_same_action_name_with_same_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] - req, action = add_actions(client, "testuser", policy_id=policy_id1) + req, action = add_actions("testuser", policy_id=policy_id1, auth_headers=auth_headers) value1 = list(action["actions"].values())[0] data = { "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_same_action_perimeter_id_with_existed_policy_id_in_list(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policies1 = policy_helper.add_policies() policy_id1 = list(policies1.keys())[0] - req, action = add_actions(client, "testuser", policy_id=policy_id1) + req, action = add_actions("testuser", policy_id=policy_id1, auth_headers=auth_headers) value1 = list(action["actions"].values())[0] data = { "name": value1['name'], "description": "description of {}".format('testuser'), } - req, action = add_actions(client, 'testuser', policy_id=policy_id1, data=data, - perimeter_id=value1['id']) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req, action = add_actions('testuser', policy_id=policy_id1, data=data, + perimeter_id=value1['id'], auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_perimeter_add_actions_without_name(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "<a>", "description": "description of {}".format(""), } - req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_perimeter_add_actions_with_name_contain_spaces(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "test<a>user", "description": "description of {}".format("test user"), } - req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" + with pytest.raises(exceptions.ValidationContentError) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "Key: 'name', [Forbidden characters in string]" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "Key: 'name', [Forbidden characters in string]" def test_add_subjects_without_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser", "description": "description of {}".format("test user"), } - req = client.post("/policies/{}/subjects".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/subjects".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_add_objects_without_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser", "description": "description of {}".format("test user"), } - req = client.post("/policies/{}/objects".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/objects".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), + body=data, headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_add_action_without_policy_id(): - client = utilities.register_client() + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter data = { "name": "testuser", "description": "description of {}".format("test user"), } - req = client.post("/policies/{}/actions".format("111"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(perimeter, "/policies/{}/actions".format( + "a34e5a29-5494-4cc5-9356-daa244b8c888"), body=data, + headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_perimeter_update_action_name(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] == value2['description'] def test_perimeter_update_actions_description(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'description': value1['description'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_actions_description_and_name(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id), body=data, + headers=auth_headers) subjects = utilities.get_json(req.data) value2 = list(subjects["actions"].values())[0] - assert req.status_code == 200 + + assert req.status == hug.HTTP_200 assert value1['name'] + 'update' == value2['name'] assert value1['id'] == value2['id'] assert value1['description'] + 'update' == value2['description'] def test_perimeter_update_action_wrong_id(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] perimeter_id = value1['id'] data = { 'name': value1['name'] + "update", 'description': value1['description'] + "update" } - req = client.patch("/actions/{}".format(perimeter_id + "wrong"), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Perimeter content is invalid.' + with pytest.raises(exceptions.PerimeterContentError) as exception_info: + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id + "wrong"), body=data, + headers=auth_headers) + assert "400: Perimeter content is invalid." == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == '400: Perimeter content is invalid.' def test_perimeter_update_action_name_with_existed_one(): - client = utilities.register_client() - req, actions = add_actions(client, "testuser") + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + req, actions = add_actions("testuser", auth_headers=auth_headers) value1 = list(actions["actions"].values())[0] - req, actions = add_actions(client, "testuser") + req, actions = add_actions("testuser", auth_headers=auth_headers) value2 = list(actions["actions"].values())[0] perimeter_id2 = value2['id'] data = { 'name': value1['name'], } - req = client.patch("/actions/{}".format(perimeter_id2), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Action Existing' + with pytest.raises(exceptions.ActionExisting) as exception_info: + req = hug.test.patch(perimeter, "/actions/{}".format(perimeter_id2), body=data, + headers=auth_headers) + assert "409: Action Existing" == str(exception_info.value) + # assert req.status == hug.HTTP_409 + # assert req.data["message"] == '409: Action Existing' def test_perimeter_delete_actions(): - client = utilities.register_client() - + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] action_id = builder.create_action(policy_id) - req = client.delete("/policies/{}/actions/{}".format(policy_id, action_id)) - assert req.status_code == 200 + req = hug.test.delete(perimeter, "/policies/{}/actions/{}".format(policy_id, action_id), + headers=auth_headers) -def test_delete_subject_without_policy(): - client = utilities.register_client() + assert req.status == hug.HTTP_200 + +def test_delete_subject_assigned_to_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + from moon_manager.db_driver import PolicyManager policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] + subject_id = builder.create_subject(policy_id) + PolicyManager.delete_policy(moon_user_id="admin", policy_id=policy_id) + PolicyManager.delete_subject(moon_user_id="admin", policy_id=None ,perimeter_id=subject_id) - action_id = builder.create_action(policy_id) + req = hug.test.get(perimeter, "subjects/{}".format(subject_id), headers=auth_headers) + assert req.data['subjects'] == {} - req = client.delete("/subjects/{}".format(action_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" +def test_delete_subject_without_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter + policies = policy_helper.add_policies() + policy_id = list(policies.keys())[0] -def test_delete_objects_without_policy(): - client = utilities.register_client() + subject_id = builder.create_subject(policy_id) + + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.delete(perimeter, "/subjects/{}".format(subject_id), headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" + +def test_delete_objects_without_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] - action_id = builder.create_action(policy_id) + object_id = builder.create_object(policy_id) - req = client.delete("/objects/{}".format(action_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.delete(perimeter, "/objects/{}".format(object_id), headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" -def test_delete_actions_without_policy(): - client = utilities.register_client() +def test_delete_actions_without_policy(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import perimeter policies = policy_helper.add_policies() policy_id = list(policies.keys())[0] action_id = builder.create_action(policy_id) - req = client.delete("/actions/{}".format(action_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.delete(perimeter, "/actions/{}".format(action_id), headers=auth_headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" def test_perimeter_delete_actions_without_perimeter_id(): - client = utilities.register_client() - req = delete_actions_without_perimeter_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Action Unknown" + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ActionUnknown) as exception_info: + req = delete_actions_without_perimeter_id(auth_headers=auth_headers) + assert "400: Action Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Action Unknown" diff --git a/moon_manager/tests/unit_python/api/test_perimeter_examples.py b/moon_manager/tests/unit_python/api/test_perimeter_examples.py new file mode 100644 index 00000000..0598629c --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_perimeter_examples.py @@ -0,0 +1,55 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug +import json + + +# def test_local_perimeter_get_subject(): +# from moon_manager.api import perimeter +# subjects = perimeter.Subjects.get() +# assert isinstance(subjects, dict) +# assert "subjects" in subjects + + + +# def test_http_perimeter_post_subject(): +# from moon_manager.api import perimeter +# result = hug.test.post(perimeter, 'subjects/b34e5a2954944cc59356daa244b8c254', +# body={'name': 'ha'}, +# headers={'Content-Type': 'application/json'}) +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data +# +# +# def test_http_perimeter_get_subject_2(): +# from moon_manager.api import perimeter +# result = hug.test.get(perimeter, 'subjects/b34e5a29-5494-4cc5-9356-daa244b8c254') +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data +# +# def test_http_perimeter_get_subject_3(): +# from moon_manager.api import perimeter +# result = hug.test.get(perimeter, 'policies/b34e5a29-5494-4cc5-9356-daa244b8c254/subjects/') +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data +# +# +# def test_http_perimeter_get_subject_4(): +# from moon_manager.api import perimeter +# result = hug.test.get(perimeter, 'policies/b34e5a29-5494-4cc5-9356-daa244b8c254/subjects/b34e5a29-5494-4cc5-9356-daa244b8c254') +# assert result.status == hug.HTTP_200 +# assert isinstance(result.data, dict) +# assert "subjects" in result.data diff --git a/moon_manager/tests/unit_python/api/test_policies.py b/moon_manager/tests/unit_python/api/test_policies.py index 76161d53..a07ba725 100644 --- a/moon_manager/tests/unit_python/api/test_policies.py +++ b/moon_manager/tests/unit_python/api/test_policies.py @@ -1,23 +1,32 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON -import json +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from falcon import HTTP_200, HTTP_400, HTTP_405, HTTP_409 +import hug from uuid import uuid4 -import api.utilities as utilities +import pytest +from moon_utilities import exceptions from helpers import model_helper from helpers import policy_helper -from helpers import data_builder -def get_policies(client): - req = client.get("/policies") - policies = utilities.get_json(req.data) - return req, policies +def get_policies(auth_headers): + from moon_manager.api import policy + req = hug.test.get(policy, "policies", headers=auth_headers) + return req -def add_policies(client, name): +def add_policies(name, auth_headers): + from moon_manager.api import policy req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -26,106 +35,153 @@ def add_policies(client, name): "model_id": model_id, "genre": "genre" } - req = client.post("/policies", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policies = utilities.get_json(req.data) - return req, policies + req = hug.test.post(policy, "policies", data, headers=auth_headers) + return req -def delete_policies_without_id(client): - req = client.delete("/policies/{}".format("")) +def delete_policies_without_id(auth_headers): + from moon_manager.api import policy + req = hug.test.delete(policy, "policies/{}".format(""), headers=auth_headers) return req def test_get_policies(): - client = utilities.register_client() - req, policies = get_policies(client) - assert req.status_code == 200 - assert isinstance(policies, dict) - assert "policies" in policies + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = get_policies(auth_headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + assert "policies" in req.data def test_add_policies(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policy_name = "testuser" + uuid4().hex - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 200 - assert isinstance(policies, dict) - value = list(policies["policies"].values())[0] - assert "policies" in policies + req = add_policies(policy_name, auth_headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + value = list(req.data["policies"].values())[0] + assert "policies" in req.data assert value['name'] == policy_name assert value["description"] == "description of {}".format(policy_name) def test_add_policies_without_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() data = { "name": policy_name, "description": "description of {}".format(policy_name), "model_id": "", "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) - assert req.status_code == 200 + assert req.status == HTTP_200 def test_add_policies_with_same_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} name = uuid4().hex policy_name = name - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 200 - assert isinstance(policies, dict) - value = list(policies["policies"].values())[0] - assert "policies" in policies + req = add_policies(policy_name, auth_headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + value = list(req.data["policies"].values())[0] + assert "policies" in req.data assert value['name'] == policy_name assert value["description"] == "description of {}".format(policy_name) - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyExisting) as exception_info: + req = add_policies(policy_name, auth_headers=auth_headers) + assert "409: Policy Already Exists" == str(exception_info.value) + # assert req.status == HTTP_409 + # assert req.data["message"] == '409: Policy Already Exists' def test_add_policy_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policy_name = "" - client = utilities.register_client() - req, policies = add_policies(client, policy_name) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Content Error' + with pytest.raises(exceptions.PolicyContentError) as exception_info: + req = add_policies(policy_name, auth_headers=auth_headers) + assert "400: Policy Content Error" == str(exception_info.value) + # assert req.status == HTTP_400 + # assert req.data["message"] == '400: Policy Content Error' -def test_update_policies_with_model(): +def test_add_policy_with_model_has_no_meta_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import policy + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} policy_name = "testuser" + uuid4().hex - client = utilities.register_client() + req = model_helper.add_model_without_meta_rule() + model_id = list(req.keys())[0] data = { "name": policy_name, "description": "description of {}".format(policy_name), - "model_id": "", + "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) - req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + with pytest.raises(exceptions.MetaRuleUnknown) as exception_info: + hug.test.post(policy, "policies/", data, headers=auth_headers) + assert "400: Meta Rule Unknown" == str(exception_info.value) + + +def test_add_policy_with_model_has_blank_subject_meta_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + from moon_manager.api import policy + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + policy_name = "testuser" + uuid4().hex + req = model_helper.add_model_with_blank_subject_meta_rule() model_id = list(req.keys())[0] data = { - "name": policy_name + "-2", + "name": policy_name, "description": "description of {}".format(policy_name), "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 - assert json.loads(req.data)['policies'][policy_id]['name'] == policy_name + '-2' + with pytest.raises(exceptions.MetaRuleContentError) as exception_info: + hug.test.post(policy, "policies/", data, headers=auth_headers) + assert "400: Meta Rule Error" == str(exception_info.value) + + + +# FIXME: uncomment when model API is re-inserted +# def test_update_policies_with_model(): +# from moon_manager.api import policy +# policy_name = "testuser" + uuid4().hex +# data = { +# "name": policy_name, +# "description": "description of {}".format(policy_name), +# "model_id": "", +# "genre": "genre" +# } +# req = hug.test.post(policy, "policies/", data) +# policy_id = next(iter(req.data['policies'])) +# req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) +# model_id = list(req.data.keys())[0] +# data = { +# "name": policy_name + "-2", +# "description": "description of {}".format(policy_name), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.patch("policies/{}".format(policy_id), data) +# assert req.status == HTTP_200 +# assert req.data['policies'][policy_id]['name'] == policy_name + '-2' def test_update_policies_name_success(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -134,9 +190,8 @@ def test_update_policies_name_success(): "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) data = { "name": policy_name + "-2", @@ -144,26 +199,24 @@ def test_update_policies_name_success(): "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 - assert json.loads(req.data)['policies'][policy_id]['name'] == policy_name + '-2' + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert req.status == HTTP_200 + assert req.data['policies'][policy_id]['name'] == policy_name + '-2' -def test_update_policies_model_unused(): +def test_update_blank_policies_with_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = uuid4().hex - client = utilities.register_client() - req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(req.keys())[0] data = { "name": policy_name, "description": "description of {}".format(policy_name), - "model_id": model_id, + "model_id": "", "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -172,55 +225,82 @@ def test_update_policies_model_unused(): "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert req.status == HTTP_200 -def test_update_policy_name_with_existed_one(): - policy_name1 = "testuser" + uuid4().hex - client = utilities.register_client() +def test_update_policies_model_unused(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy + policy_name = uuid4().hex req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { - "name": policy_name1, - "description": "description of {}".format(policy_name1), + "name": policy_name, + "description": "description of {}".format(policy_name), "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id1 = next(iter(utilities.get_json(req.data)['policies'])) - - policy_name2 = "testuser" + uuid4().hex - client = utilities.register_client() + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { - "name": policy_name2, - "description": "description of {}".format(policy_name2), + "name": policy_name, + "description": "description of {}".format(policy_name), "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id2 = next(iter(utilities.get_json(req.data)['policies'])) - data = { - "name": policy_name1, - "description": "description of {}".format(policy_name1), - "model_id": model_id, - "genre": "genre" - } - req = client.patch("/policies/{}".format(policy_id2), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Policy Already Exists' + with pytest.raises(exceptions.PolicyUpdateError) as exception_info: + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert "400: Policy update error" == str(exception_info.value) + + +# FIXME: uncomment when model API is re-inserted +# def test_update_policy_name_with_existed_one(): +# from moon_manager.api import policy +# policy_name1 = "testuser" + uuid4().hex +# req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) +# model_id = list(req.keys())[0] +# data = { +# "name": policy_name1, +# "description": "description of {}".format(policy_name1), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.post(policy, "policies/", data) +# policy_id1 = next(iter(req.data['policies'])) +# +# policy_name2 = "testuser" + uuid4().hex +# eq = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) +# model_id = list(req.data.keys())[0] +# data = { +# "name": policy_name2, +# "description": "description of {}".format(policy_name2), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.post(policy, "policies/", data) +# policy_id2 = next(iter(req.data['policies'])) +# +# data = { +# "name": policy_name1, +# "description": "description of {}".format(policy_name1), +# "model_id": model_id, +# "genre": "genre" +# } +# req = hug.test.patch(policy, "policies/{}".format(policy_id2), data) +# assert req.status == HTTP_409 +# assert req.data["message"] == '409: Policy Already Exists' def test_update_policies_with_empty_name(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -229,9 +309,8 @@ def test_update_policies_with_empty_name(): "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) data = { "name": "", @@ -239,15 +318,18 @@ def test_update_policies_with_empty_name(): "model_id": model_id, "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Content Error' + with pytest.raises(exceptions.PolicyContentError) as exception_info: + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert "400: Policy Content Error" == str(exception_info.value) + # assert req.status == HTTP_400 + # assert req.data["message"] == '400: Policy Content Error' def test_update_policies_with_blank_model(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy policy_name = "testuser" + uuid4().hex - client = utilities.register_client() req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) model_id = list(req.keys())[0] data = { @@ -256,9 +338,8 @@ def test_update_policies_with_blank_model(): "model_id": model_id, "genre": "genre" } - req = client.post("/policies/", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - policy_id = next(iter(utilities.get_json(req.data)['policies'])) + req = hug.test.post(policy, "policies/", data, headers=auth_headers) + policy_id = next(iter(req.data['policies'])) data = { "name": policy_name, @@ -267,76 +348,77 @@ def test_update_policies_with_blank_model(): "genre": "genre" } - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 200 + with pytest.raises(exceptions.PolicyUpdateError) as exception_info: + req = hug.test.patch(policy, "policies/{}".format(policy_id), data, headers=auth_headers) + assert "400: Policy update error" == str(exception_info.value) -def test_update_policies_connected_to_rules_with_blank_model(): - client = utilities.register_client() - req, rules, policy_id = data_builder.add_rules(client) - req = client.get("/policies") - data = utilities.get_json(req.data) - for policy_obj_id in data['policies']: - if policy_obj_id == policy_id: - policy = data['policies'][policy_obj_id] - policy['model_id'] = '' - req = client.patch("/policies/{}".format(policy_id), data=json.dumps(policy), - headers={'Content-Type': 'application/json'}) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy update error' +# FIXME: uncomment when model API is re-inserted +# def test_update_policies_connected_to_rules_with_blank_model(): +# from moon_manager.api import policy +# req, rules, policy_id = data_builder.add_rules() +# req = hug.test.get(policy, "policies") +# for policy_obj_id in req.data['policies']: +# if policy_obj_id == policy_id: +# policy = req.data['policies'][policy_obj_id] +# policy['model_id'] = '' +# req = hug.test.patch("/policies/{}".format(policy_id), req.data) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy update error' def test_delete_policies(): - client = utilities.register_client() - - policy = policy_helper.add_policies() - policy_id = list(policy.keys())[0] - - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 200 - - -def test_delete_policy_with_dependencies_rule(): - client = utilities.register_client() - req, rules, policy_id = data_builder.add_rules(client) - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy With Rule Error' - - -def test_delete_policy_with_dependencies_subject_data(): - client = utilities.register_client() - req, rules, policy_id = data_builder.add_rules(client) - req = client.delete("/policies/{}/rules/{}".format(policy_id, next(iter(rules['rules'])))) - assert req.status_code == 200 - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy With Data Error' - - -def test_delete_policy_with_dependencies_perimeter(): - client = utilities.register_client() - policy = policy_helper.add_policies() - policy_id = next(iter(policy)) - - data = { - "name": 'testuser'+uuid4().hex, - "description": "description of {}".format(uuid4().hex), - "password": "password for {}".format(uuid4().hex), - "email": "{}@moon".format(uuid4().hex) - } - req = client.post("/policies/{}/subjects".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 200 - req = client.delete("/policies/{}".format(policy_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy With Perimeter Error' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import policy + _policy = policy_helper.add_policies() + policy_id = list(_policy.keys())[0] + req = hug.test.delete(policy, "policies/{}".format(policy_id), headers=auth_headers) + assert req.status == HTTP_200 + + +# FIXME: uncomment when rule API is re-inserted +# def test_delete_policy_with_dependencies_rule(): +# from moon_manager.api import policy +# req, rules, policy_id = data_builder.add_rules() +# req = hug.test.delete(policy, "policies/{}".format(policy_id)) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy With Rule Error' + + +# FIXME: uncomment when perimeter API is re-inserted +# def test_delete_policy_with_dependencies_subject_data(): +# from moon_manager.api import policy +# req, rules, policy_id = data_builder.add_rules() +# req = hug.test.delete(policy, "policies/{}/rules/{}".format(policy_id, next(iter(rules['rules'])))) +# assert req.status == HTTP_200 +# req = hug.test.delete(policy, "policies/{}".format(policy_id)) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy With Data Error' + + +# FIXME: uncomment when perimeter API is re-inserted +# def test_delete_policy_with_dependencies_perimeter(): +# from moon_manager.api import policy +# _policy = policy_helper.add_policies() +# policy_id = next(iter(_policy)) +# +# data = { +# "name": 'testuser'+uuid4().hex, +# "description": "description of {}".format(uuid4().hex), +# "password": "password for {}".format(uuid4().hex), +# "email": "{}@moon".format(uuid4().hex) +# } +# req = hug.test.post(policy, "policies/{}/subjects".format(policy_id), data) +# +# assert req.status == HTTP_200 +# req = hug.test.delete(policy, "policies/{}".format(policy_id)) +# assert req.status == HTTP_400 +# assert req.data["message"] == '400: Policy With Perimeter Error' def test_delete_policies_without_id(): - client = utilities.register_client() - req = delete_policies_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Policy Unknown' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = delete_policies_without_id(auth_headers=auth_headers) + assert req.status == HTTP_405 diff --git a/moon_manager/tests/unit_python/api/test_rules.py b/moon_manager/tests/unit_python/api/test_rules.py index a3c21839..2bb7a96f 100644 --- a/moon_manager/tests/unit_python/api/test_rules.py +++ b/moon_manager/tests/unit_python/api/test_rules.py @@ -1,114 +1,317 @@ -import api.utilities as utilities +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import pytest +from moon_utilities import exceptions import json from helpers import data_builder as builder -from uuid import uuid4 from helpers import policy_helper +from helpers import rules_helper +import hug + +def get_rules(policy_id): + from moon_manager.api import rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} -def get_rules(client, policy_id): - req = client.get("/policies/{}/rules".format(policy_id)) - rules = utilities.get_json(req.data) + req = hug.test.get(rules, "/policies/{}/rules".format(policy_id), headers=auth_headers) + rules = req.data return req, rules -def add_rules_without_policy_id(client): +def add_rules_without_policy_id(headers): + from moon_manager.api import rules subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() data = { "meta_rule_id": meta_rule_id, "rule": [subject_category_id, object_category_id, action_category_id], - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(None), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) + headers['Content-Type'] = 'application/json' + req = hug.test.post(rules, "/policies/{}/rules".format(None), body=json.dumps(data), + headers=headers) + rules = req.data return req, rules -def add_rules_without_meta_rule_id(client, policy_id): +def add_rules_without_meta_rule_id(policy_id, headers): + from moon_manager.api import rules data = { "meta_rule_id": "", "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"], - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) + headers['Content-Type'] = 'application/json' + req = hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=headers) + rules = req.data return req, rules -def add_rules_without_rule(client, policy_id): +def add_rules_without_rule(policy_id, headers): + from moon_manager.api import rules data = { "meta_rule_id": "meta_rule_id1", - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) + headers['Content-Type'] = 'application/json' + req = hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=headers) + rules = req.data return req, rules -def delete_rules(client, policy_id, meta_rule_id): - req = client.delete("/policies/{}/rules/{}".format(policy_id, meta_rule_id)) +def delete_rules(policy_id, meta_rule_id, headers): + from moon_manager.api import rules + req = hug.test.delete(rules, "/policies/{}/rules/{}".format(policy_id, meta_rule_id), + headers=headers) return req -def test_get_rules(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, rules = get_rules(client, policy_id) - assert req.status_code == 200 +def update_rule(policy_id, rule_id, instructions, headers): + from moon_manager.api import rules + req = hug.test.patch(rules, "/policies/{}/rules/{}".format(policy_id, rule_id), + headers=headers, + body=instructions) + return req + + +def test_add_rules_with_invalid_decision_instructions(): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + + data = { + "meta_rule_id": meta_rule_id, + "rule": [subject_category_id, object_category_id, action_category_id], + "instructions": [ + {"decision": "invalid"}, + ], + "enabled": True + } + + with pytest.raises(exceptions.RuleContentError) as exception_info: + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + assert "400: Rule Error" == str(exception_info.value) + + +def test_add_rules_with_meta_rule_not_linked_with_policy_model(): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + policy_id = builder.create_new_policy()[-1] + meta_rule_id = builder.create_new_meta_rule()[-1] + + data = { + "meta_rule_id": meta_rule_id, + "rule": ["subject_data_id2", "object_data_id2", "action_data_id2"], + "instructions": [ + {"decision": "grant"}, + ], + "enabled": True + } + + with pytest.raises(exceptions.MetaRuleNotLinkedWithPolicyModel) as exception_info: + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + assert "400: MetaRule Not Linked With Model - Policy" == str(exception_info.value) + + +def test_add_rules_with_invalid_rule(): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + sub_data_id = builder.create_subject_data(policy_id, subject_category_id) + obj_data_id = builder.create_object_data(policy_id, object_category_id) + act_data_id = builder.create_action_data(policy_id, action_category_id) + + data = { + "meta_rule_id": meta_rule_id, + "rule": [obj_data_id, sub_data_id, act_data_id], + "instructions": [ + {"decision": "grant"}, + ], + "enabled": True + } + + with pytest.raises(exceptions.RuleContentError) as exception_info: + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + assert "400: Rule Error" == str(exception_info.value) + + +def test_add_rules_with_no_given_decision_instructions(policy_id=None): + from moon_manager.api import rules + + auth_headers = rules_helper.get_headers() + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() + sub_data_id = builder.create_subject_data(policy_id, subject_category_id) + obj_data_id = builder.create_object_data(policy_id, object_category_id) + act_data_id = builder.create_action_data(policy_id, action_category_id) + + data = { + "meta_rule_id": meta_rule_id, + "rule": [sub_data_id, obj_data_id, act_data_id], + "instructions": [], + "enabled": True + } + + req = hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers=auth_headers) + + assert req.status == hug.HTTP_200 + + default_instruction = {"decision": "grant"} + rules = req.data['rules'] + rule_id = next(iter(req.data['rules'])) + assert rules[rule_id]["instructions"][0] == default_instruction + + +def test_get_rules(policy_id=None): + if policy_id == None: + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + + req, rules = get_rules(policy_id) + assert req.status == hug.HTTP_200 assert isinstance(rules, dict) assert "rules" in rules return req, rules def test_add_rules(): - client = utilities.register_client() - req, rules, policy = builder.add_rules(client, ) - assert req.status_code == 200 + req, rules, policy = builder.add_rules() + assert req.status == hug.HTTP_200 def test_add_rules_without_policy_id(): - client = utilities.register_client() - req, rules = add_rules_without_policy_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Policy Unknown" + from moon_manager.api import rules + + subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() + data = { + "meta_rule_id": meta_rule_id, + "rule": [subject_category_id, object_category_id, action_category_id], + "instructions": [ + {"decision": "grant"}, + ], + "enabled": True + } + + headers = rules_helper.get_headers() + with pytest.raises(exceptions.PolicyUnknown) as exception_info: + req = hug.test.post(rules, "/policies/{}/rules".format(None), body=json.dumps(data), + headers=headers) + assert "400: Policy Unknown" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == "400: Policy Unknown" + # # def test_add_rules_without_meta_rule_id(): # policy_id = utilities.get_policy_id() # client = utilities.register_client() # req, rules = add_rules_without_meta_rule_id(client, policy_id) -# assert req.status_code == 400 +# assert req.status == 400 # assert json.loads(req.data)["message"] == "Key: 'meta_rule_id', [Empty String]" def test_add_rules_without_rule(): - policy_id = utilities.get_policy_id() - client = utilities.register_client() - req, rules = add_rules_without_rule(client, policy_id) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == 'Invalid Key :rule not found' + from moon_utilities.auth_functions import get_api_key_for_user + policy = policy_helper.add_policies() + policy_id = next(iter(policy)) + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + with pytest.raises(exceptions.ValidationKeyError) as exception_info: + req, rules = add_rules_without_rule(policy_id, headers=auth_headers) + assert "Invalid Key :rule not found" == str(exception_info.value) + # assert req.status == hug.HTTP_400 + # assert req.data["message"] == 'Invalid Key :rule not found' + + +def test_update_rule_without_body(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, rules, policy_id = builder.add_rules() + rule_id = list(rules['rules'].keys())[0] + + req = update_rule(policy_id, rule_id, instructions=None, headers=auth_headers) + + assert req.status == hug.HTTP_400 + + +def test_update_rule_without_instructions_in_body(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + data = {"instruction": [ # faute de frappe + {"decision": "deny"}, + ]} + + req, rules, policy_id = builder.add_rules() + rule_id = list(rules['rules'].keys())[0] + + req = update_rule(policy_id, rule_id, instructions=None, headers=auth_headers) + + assert req.status == hug.HTTP_400 + + +def test_update_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, rules, policy_id = builder.add_rules() + rule_id = list(rules['rules'].keys())[0] + + data = {"instructions": [ + {"decision": "deny"}, + ]} + req = update_rule(policy_id, rule_id, data, headers=auth_headers) + + rules = get_rules(policy_id)[1]['rules']['rules'] + + rule = None + for rule_ in rules: + if rule_['id'] == rule_id: + rule = rule_ + break + + assert req.status == hug.HTTP_200 and rule['instructions'][0]['decision'] == "deny" def test_delete_rules_with_invalid_parameters(): - client = utilities.register_client() - req = delete_rules(client, "", "") - assert req.status_code == 404 - # assert json.loads(req.data)["message"] == 'Invalid Key :rule not found' + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = delete_rules("", "", headers=auth_headers) + assert req.status == hug.HTTP_405 def test_delete_rules_without_policy_id(): - client = utilities.register_client() + from moon_manager.api import rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = builder.create_new_policy() sub_data_id = builder.create_subject_data(policy_id, subject_category_id) obj_data_id = builder.create_object_data(policy_id, object_category_id) @@ -116,14 +319,15 @@ def test_delete_rules_without_policy_id(): data = { "meta_rule_id": meta_rule_id, "rule": [sub_data_id, obj_data_id, act_data_id], - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - req, added_rules = get_rules(client, policy_id) + hug.test.post(rules, "/policies/{}/rules".format(policy_id), body=json.dumps(data), + headers={'Content-Type': 'application/json', + "X-Api-Key": get_api_key_for_user("admin")}) + req, added_rules = get_rules(policy_id) id = list(added_rules["rules"]["rules"])[0]["id"] - rules = delete_rules(client, None, id) - assert rules.status_code == 200 + rules = delete_rules(None, id, headers=auth_headers) + assert rules.status == hug.HTTP_200 diff --git a/moon_manager/tests/unit_python/api/test_slaves.py b/moon_manager/tests/unit_python/api/test_slaves.py new file mode 100644 index 00000000..29d5e62e --- /dev/null +++ b/moon_manager/tests/unit_python/api/test_slaves.py @@ -0,0 +1,90 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from falcon import HTTP_200, HTTP_400, HTTP_405 +import hug +from uuid import uuid4 +from helpers import data_builder as builder + + +def test_get_slaves(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import slave + req = hug.test.get(slave, 'slaves/', headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + assert "slaves" in req.data + for slave in req.data.get("slaves"): + assert "name" in slave + assert "description" in slave + assert "status" in slave + assert "server_ip" in slave + assert "port" in slave + + +def test_add_slave(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import slave + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:10000") + mocker.patch("subprocess.Popen", return_value=True) + data = { + "name": "test_slave_" + uuid4().hex, + "description": "description of test_slave" + } + req = hug.test.post(slave, "slave/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + found = False + assert "slaves" in req.data + for value in req.data["slaves"].values(): + assert "name" in value + assert "description" in value + assert "api_key" in value + assert "process" in value + assert "log" in value + assert "extra" in value + if value['name'] == data['name']: + found = True + assert value["description"] == "description of test_slave" + assert "port" in value.get("extra") + assert "status" in value.get("extra") + assert "server_ip" in value.get("extra") + break + assert found + + +def test_delete_slave(mocker): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + from moon_manager.api import slave + mocker.patch('moon_manager.plugins.pyorchestrator.get_server_url', + return_value="http://127.0.0.1:10000") + mocker.patch("subprocess.Popen", return_value=True) + data = { + "name": "test_slave_" + uuid4().hex, + "description": "description of test_slave" + } + req = hug.test.post(slave, "slave/", data, headers=auth_headers) + assert req.status == HTTP_200 + assert isinstance(req.data, dict) + req = hug.test.get(slave, 'slaves/', headers=auth_headers) + success_req = None + for key, value in req.data['slaves'].items(): + if value['name'] == data['name']: + success_req = hug.test.delete(slave, 'slave/{}'.format(key), headers=auth_headers) + break + assert success_req + assert success_req.status == HTTP_200 + diff --git a/moon_manager/tests/unit_python/api/test_unit_models.py b/moon_manager/tests/unit_python/api/test_unit_models.py deleted file mode 100644 index 6e93ed28..00000000 --- a/moon_manager/tests/unit_python/api/test_unit_models.py +++ /dev/null @@ -1,352 +0,0 @@ -# Copyright 2018 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. - -import json -import api.utilities as utilities -from helpers import data_builder as builder -from helpers import policy_helper -from helpers import model_helper -from uuid import uuid4 - - -def get_models(client): - req = client.get("/models") - models = utilities.get_json(req.data) - return req, models - - -def add_models(client, name, data=None): - subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() - - if not data: - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - req = client.post("/models", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def update_model(client, name, model_id): - subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() - - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def add_model_without_meta_rules_ids(client, name): - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [] - } - req = client.post("/models", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def add_model_with_empty_meta_rule_id(client, name): - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [""] - } - req = client.post("/models", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def update_model_without_meta_rules_ids(client, model_id): - name = "model_id" + uuid4().hex - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - models = utilities.get_json(req.data) - return req, models - - -def delete_models(client, name): - request, models = get_models(client) - for key, value in models['models'].items(): - if value['name'] == name: - req = client.delete("/models/{}".format(key)) - break - return req - - -def delete_models_without_id(client): - req = client.delete("/models/{}".format("")) - return req - - -def test_delete_model_assigned_to_policy(): - policy_name = "testuser" + uuid4().hex - client = utilities.register_client() - req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(req.keys())[0] - data = { - "name": policy_name, - "description": "description of {}".format(policy_name), - "model_id": model_id, - "genre": "genre" - } - req = client.post("/policies", data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - req = client.delete("/models/{}".format(model_id)) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Model With Policy Error' - - -def clean_models(): - client = utilities.register_client() - req, models = get_models(client) - for key, value in models['models'].items(): - print(key) - print(value) - client.delete("/models/{}".format(key)) - - -def test_get_models(): - client = utilities.register_client() - req, models = get_models(client) - assert req.status_code == 200 - assert isinstance(models, dict) - assert "models" in models - - -def test_add_models(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, "testuser") - assert req.status_code == 200 - assert isinstance(models, dict) - model_id = list(models["models"])[0] - assert "models" in models - assert models['models'][model_id]['name'] == "testuser" - assert models['models'][model_id]["description"] == "description of {}".format("testuser") - - -def test_delete_models(): - client = utilities.register_client() - req = delete_models(client, "testuser") - assert req.status_code == 200 - - -def test_update_models_with_assigned_policy(): - client = utilities.register_client() - - model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(model.keys())[0] - value = { - "name": "test_policy" + uuid4().hex, - "model_id": model_id, - "description": "test", - } - policy = policy_helper.add_policies(value=value) - data = { - "name": "model_" + uuid4().hex, - "description": "description of model_2", - "meta_rules": [] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Model With Policy Error" - - -def test_update_models_with_no_assigned_policy(): - client = utilities.register_client() - - model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(model.keys())[0] - - data = { - "name": "model_" + uuid4().hex, - "description": "description of model_2", - "meta_rules": [] - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 200 - - -def test_add_models_with_meta_rule_key(): - client = utilities.register_client() - - model = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) - model_id = list(model.keys())[0] - - data = { - "name": "model_" + uuid4().hex, - "description": "description of model_2", - - } - req = client.patch("/models/{}".format(model_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Invalid Key :meta_rules not found" - - -def test_delete_models_without_id(): - client = utilities.register_client() - req = delete_models_without_id(client) - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "400: Model Unknown" - - -def test_add_model_with_empty_name(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, "<br/>") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" - - -def test_add_model_with_name_contain_space(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, "test<br>user") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == "Key: 'name', [Forbidden characters in string]" - - -def test_add_model_with_name_space(): - clean_models() - client = utilities.register_client() - req, models = add_models(client, " ") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Model Unknown' - - -def test_add_model_with_empty_meta_rule_id(): - clean_models() - client = utilities.register_client() - req, meta_rules = add_model_with_empty_meta_rule_id(client, "testuser") - assert req.status_code == 400 - assert json.loads(req.data)["message"] == '400: Meta Rule Unknown' - - -def test_add_model_with_existed_name(): - clean_models() - client = utilities.register_client() - name = uuid4().hex - req, models = add_models(client, name) - assert req.status_code == 200 - req, models = add_models(client, name) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Model Error' - - -def test_add_model_with_existed_meta_rules_list(): - clean_models() - client = utilities.register_client() - name = uuid4().hex - - subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - name = uuid4().hex - req, models = add_models(client=client, name=name, data=data) - assert req.status_code == 200 - - data = { - "name": name, - "description": "description of {}".format(name), - "meta_rules": [meta_rule_id] - } - req, models = add_models(client=client, name=name, data=data) - assert req.status_code == 409 - assert json.loads(req.data)["message"] == '409: Model Error' - - -def test_add_model_without_meta_rules(): - clean_models() - client = utilities.register_client() - req, meta_rules = add_model_without_meta_rules_ids(client, "testuser") - assert req.status_code == 200 - # assert json.loads(req.data)["message"] == "Key: 'meta_rules', [Empty Container]" - - -def test_update_model(): - clean_models() - client = utilities.register_client() - req = add_models(client, "testuser") - model_id = list(req[1]['models'])[0] - req_update = update_model(client, "testuser", model_id) - assert req_update[0].status_code == 200 - model_id = list(req_update[1]["models"])[0] - assert req_update[1]["models"][model_id]["meta_rules"][0] is not None - delete_models(client, "testuser") - - -def test_update_model_name_with_space(): - clean_models() - client = utilities.register_client() - req = add_models(client, "testuser") - model_id = list(req[1]['models'])[0] - req_update = update_model(client, " ", model_id) - assert req_update[0].status_code == 400 - assert req_update[1]["message"] == '400: Model Unknown' - - -def test_update_model_with_empty_name(): - clean_models() - client = utilities.register_client() - req = add_models(client, "testuser") - model_id = list(req[1]['models'])[0] - req_update = update_model(client, "", model_id) - assert req_update[0].status_code == 400 - assert req_update[1]['message'] == '400: Model Unknown' - - -def test_update_meta_rules_without_id(): - clean_models() - client = utilities.register_client() - req_update = update_model(client, "testuser", "") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)["message"] == "400: Model Unknown" - - -def test_update_meta_rules_without_name(): - client = utilities.register_client() - req_update = update_model(client, "<a></a>", "1234567") - assert req_update[0].status_code == 400 - assert json.loads(req_update[0].data)[ - "message"] == "Key: 'name', [Forbidden characters in string]" - - -def test_update_meta_rules_without_meta_rules(): - value = { - "name": "mls_model_id" + uuid4().hex, - "description": "test", - "meta_rules": [] - } - model = model_helper.add_model(value=value) - model_id = list(model.keys())[0] - client = utilities.register_client() - req_update = update_model_without_meta_rules_ids(client, model_id) - assert req_update[0].status_code == 200 diff --git a/moon_manager/tests/unit_python/api/utilities.py b/moon_manager/tests/unit_python/api/utilities.py index 2e51fec8..baf59a51 100644 --- a/moon_manager/tests/unit_python/api/utilities.py +++ b/moon_manager/tests/unit_python/api/utilities.py @@ -1,26 +1,16 @@ -import json -from uuid import uuid4 +# Software Name: MOON -def get_json(data): - return json.loads(data.decode("utf-8")) +# Version: 5.4 +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 -def register_client(): - import moon_manager.server - server = moon_manager.server.create_server() - client = server.app.test_client() - return client +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. -def get_policy_id(): - from helpers import policy_helper - value = { - "name": "test_policy"+uuid4().hex, - "model_id": "", - "genre": "authz", - "description": "test", - } - policy_helper.add_policies(value=value) - req = policy_helper.get_policies() - policy_id = list(req.keys())[0] - return policy_id +import json +from uuid import uuid4 +def get_json(data): + return data;#json.loads(data.decode("utf-8")) diff --git a/moon_manager/tests/unit_python/conftest.py b/moon_manager/tests/unit_python/conftest.py index 90a27e54..702f3c19 100644 --- a/moon_manager/tests/unit_python/conftest.py +++ b/moon_manager/tests/unit_python/conftest.py @@ -1,254 +1,164 @@ -import base64 -import json -import logging +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import os import pytest import requests_mock +import yaml +import mock_keystone +import mock_nova +import mock_engine +import mock_slaves + + +__CONF = """ +database: + url: sqlite:////tmp/database_test.db + driver: moon_manager.plugins.sql + migration_dir: moon_manager.api.db.migrations + +management: + url: http://127.0.0.1:8000 + user: admin + password: admin + token_file: db.json + +orchestration: + driver: moon_manager.plugins.pyorchestrator + connection: local + slaves: + port: 10000...10100 + pipelines: + port: 20000...20100 + +information: + user: admin + password: p4ssw0rd + domain: default + project: admin + check_token: false + certificate: false + url: http://keystone:5000/v3 + subjects: + drivers: + moon_manager.plugins.moon_keystone_plugin: + url: http://keystone:5000/v3 + objects: + drivers: + moon_manager.plugins.moon_nova_plugin: + url: http://keystone:5000/compute/v2.1 + + global_attrs: + driver: moon_manager.plugins.global_attrs + attributes: + mode: + values: + - build + - run + default: run + url: file:/tmp/mode + #url: https://127.0.0.1:8080/mode + #url: mysql+pymysql://moon:p4sswOrd1@db/moon_mode + #url: sqlite:////tmp/database.db + #url: driver://moon_manager.plugins.my_plugin -CONF = { - "openstack": { - "keystone": { - "url": "http://keystone:5000/v3", - "user": "admin", - "check_token": False, - "password": "p4ssw0rd", - "domain": "default", - "certificate": False, - "project": "admin" - } - }, - "components": { - "wrapper": { - "bind": "0.0.0.0", - "port": 8080, - "container": "wukongsun/moon_wrapper:v4.3", - "timeout": 5, - "hostname": "wrapper" - }, - "manager": { - "bind": "0.0.0.0", - "port": 8082, - "container": "wukongsun/moon_manager:v4.3", - "hostname": "manager" - }, - "port_start": 31001, - "orchestrator": { - "bind": "0.0.0.0", - "port": 8083, - "container": "wukongsun/moon_orchestrator:v4.3", - "hostname": "orchestrator" - }, - "pipeline": { - "interface": { - "bind": "0.0.0.0", - "port": 8080, - "container": "wukongsun/moon_interface:v4.3", - "hostname": "interface" - }, - "authz": { - "bind": "0.0.0.0", - "port": 8081, - "container": "wukongsun/moon_authz:v4.3", - "hostname": "authz" - }, - } - }, - "logging": { - "handlers": { - "file": { - "filename": "/tmp/moon.log", - "class": "logging.handlers.RotatingFileHandler", - "level": "DEBUG", - "formatter": "custom", - "backupCount": 3, - "maxBytes": 1048576 - }, - "console": { - "class": "logging.StreamHandler", - "formatter": "brief", - "level": "INFO", - "stream": "ext://sys.stdout" - } - }, - "formatters": { - "brief": { - "format": "%(levelname)s %(name)s %(message)-30s" - }, - "custom": { - "format": "%(asctime)-15s %(levelname)s %(name)s %(message)s" - } - }, - "root": { - "handlers": [ - "console" - ], - "level": "ERROR" - }, - "version": 1, - "loggers": { - "moon": { - "handlers": [ - "console", - "file" - ], - "propagate": False, - "level": "DEBUG" - } - } - }, - "slave": { - "name": None, - "master": { - "url": None, - "login": None, - "password": None - } - }, - "docker": { - "url": "tcp://172.88.88.1:2376", - "network": "moon" - }, - "database": { - "url": "sqlite:///database.db", - # "url": "mysql+pymysql://moon:p4sswOrd1@db/moon", - "driver": "sql" - }, - "messenger": { - "url": "rabbit://moon:p4sswOrd1@messenger:5672/moon" - }, -} - -COMPONENTS = ( - "logging", - "openstack/keystone", - "database", - "slave", - "components/manager", - "components/orchestrator" -) - -PODS = { - "pods": { - "721760dd-de5f-11e7-8001-3863bbb766f3": [ - { - "pdp_id": "b3d3e18abf3340e8b635fd49e6634ccd", - "port": 8080, - "genre": "interface", - "name": "interface-paltry", - "keystone_project_id": "a64beb1cc224474fb4badd43173e7101", - "namespace": "moon", - "container": "wukongsun/moon_interface:v4.3" - }, - { - "pdp_id": "b3d3e18abf3340e8b635fd49e6634ccd", - "meta_rule_id": "f8f49a779ceb47b3ac810f01ef71b4e0", - "port": 8081, - "genre": "authz", - "name": "authz-economic", - "policy_id": "f8f49a779ceb47b3ac810f01ef71b4e0", - "keystone_project_id": "a64beb1cc224474fb4badd43173e7101", - "namespace": "moon", - "container": "wukongsun/moon_authz:v4.3" - } - ] - } -} - -SLAVES = { - "slaves": [ - { - "context": - { - "cluster": "kubernetes", - "user": "kubernetes-admin" - }, - "name": "kubernetes-admin@kubernetes", - "configured": True, - "wrapper_name": "mywrapper", - "ip": "NC", - "port": 31002, - "internal_port": 8080 - } - ] -} - - -def get_b64_conf(component=None): - if component in CONF: - return base64.b64encode( - json.dumps( - CONF[component]).encode('utf-8') + b"\n").decode('utf-8') - elif "/" in component: - key1, _, key2 = component.partition("/") - return base64.b64encode( - json.dumps( - CONF[key1][key2]).encode('utf-8') + b"\n").decode('utf-8') - else: - return base64.b64encode( - json.dumps(CONF).encode('utf-8') + b"\n").decode('utf-8') +plugins: + directory: /var/moon/plugins + +components: + manager: + port: 8080 + bind: 0.0.0.0 + hostname: manager + +logging: + version: 1 + + formatters: + brief: + format: "%(levelname)s %(name)s %(message)-30s" + custom: + format: "%(asctime)-15s %(levelname)s %(name)s %(message)s" + + handlers: + console: + class : logging.StreamHandler + formatter: custom + level : INFO + stream : ext://sys.stdout + file: + class : logging.handlers.RotatingFileHandler + formatter: custom + level : DEBUG + filename: /tmp/moon.log + maxBytes: 1048576 + backupCount: 3 + + loggers: + moon: + level: DEBUG + handlers: [console, file] + propagate: no + + root: + level: ERROR + handlers: [console] +""" @pytest.fixture(autouse=True) def no_requests(monkeypatch): """ Modify the response from Requests module """ + global manager_api_key with requests_mock.Mocker(real_http=True) as m: - for component in COMPONENTS: - m.register_uri( - 'GET', 'http://consul:8500/v1/kv/{}'.format(component), - json=[{'Key': component, 'Value': get_b64_conf(component)}] - ) - m.register_uri( - 'POST', 'http://keystone:5000/v3/auth/tokens', - headers={'X-Subject-Token': "111111111"} - ) - m.register_uri( - 'DELETE', 'http://keystone:5000/v3/auth/tokens', - headers={'X-Subject-Token': "111111111"} - ) - - def match_request_text(request): - # request.url may be None, or '' prevents a TypeError. - return 'http://keystone:5000/v3/users?name=testuser' in request.url - - m.register_uri( - requests_mock.ANY, '/v3/users', - additional_matcher=match_request_text, - json={"users": {}} - ) - m.register_uri( - 'POST', 'http://keystone:5000/v3/users/', - json={"users": [{"id": "1111111111111"}]} - ) - m.register_uri( - 'POST', 'http://orchestrator:8083/pods', - json=PODS, - headers={"content-type": "application/json"} - ) - m.register_uri( - 'GET', 'http://orchestrator:8083/pods', - json=PODS - ) - m.register_uri( - 'GET', 'http://localhost/slaves', - json=SLAVES - ) - m.register_uri( - 'DELETE', 'http://orchestrator:8083/pods/{}'.format(list([PODS['pods'].keys()])[0]), - headers={"content-type": "application/json"} - ) - - print("Start populating the DB.") - from python_moondb.db_manager import init_engine, main - engine = init_engine() - print("engine={}".format(engine)) - main("upgrade", logging.getLogger("db_manager"), engine) - print("End populating the DB.") - yield m + try: + os.remove("/tmp/database_test.db") + except FileNotFoundError: + pass + try: + os.remove("/tmp/moon.pwd") + except FileNotFoundError: + pass + print("Configure...") + from moon_manager.api.configuration import init_database, set_configuration + set_configuration(yaml.safe_load(__CONF)) + print("Create a new user") + from moon_utilities.auth_functions import add_user, init_db, get_api_key_for_user + init_db() + try: + user = add_user("admin", "admin") + manager_api_key = user["api_key"] + except KeyError: + print("User already exists") + manager_api_key = get_api_key_for_user("admin") + print("Initialize the database") + init_database() + from moon_manager import db_driver, orchestration_driver + + db_driver.init() + orchestration_driver.init() + + mock_keystone.register_keystone(m) + mock_nova.register_nova(m) + mock_engine.register_engine(m) + mock_slaves.register_slaves(m) -# @pytest.fixture(autouse=True, scope="session") -# def manage_database(): -# from moon_db.db_manager import init_engine, run -# engine = init_engine() -# run("upgrade", logging.getLogger("db_manager"), engine) -# yield -# print("Will close the DB") + from moon_manager.pip_driver import InformationManager + for category in InformationManager: + for manager in InformationManager[category]: + manager.set_auth() + + yield m + for category in InformationManager: + for manager in InformationManager[category]: + manager.unset_auth() diff --git a/moon_manager/tests/unit_python/helpers/__init__.py b/moon_manager/tests/unit_python/helpers/__init__.py index e69de29b..582be686 100644 --- a/moon_manager/tests/unit_python/helpers/__init__.py +++ b/moon_manager/tests/unit_python/helpers/__init__.py @@ -0,0 +1,11 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + diff --git a/moon_manager/tests/unit_python/helpers/assignment_helper.py b/moon_manager/tests/unit_python/helpers/assignment_helper.py index 22a56e38..05d13c46 100644 --- a/moon_manager/tests/unit_python/helpers/assignment_helper.py +++ b/moon_manager/tests/unit_python/helpers/assignment_helper.py @@ -1,49 +1,57 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + def get_action_assignments(policy_id, action_id=None, category_id=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_action_assignments("", policy_id, action_id, category_id) def add_action_assignment(policy_id, action_id, category_id, data_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.add_action_assignment("", policy_id, action_id, category_id, data_id) def delete_action_assignment(policy_id, action_id, category_id, data_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager PolicyManager.delete_action_assignment("", policy_id, action_id, category_id, data_id) def get_object_assignments(policy_id, object_id=None, category_id=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_object_assignments("", policy_id, object_id, category_id) def add_object_assignment(policy_id, object_id, category_id, data_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.add_object_assignment("", policy_id, object_id, category_id, data_id) def delete_object_assignment(policy_id, object_id, category_id, data_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager PolicyManager.delete_object_assignment("", policy_id, object_id, category_id, data_id) def get_subject_assignments(policy_id, subject_id=None, category_id=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_subject_assignments("", policy_id, subject_id, category_id) def add_subject_assignment(policy_id, subject_id, category_id, data_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.add_subject_assignment("", policy_id, subject_id, category_id, data_id) def delete_subject_assignment(policy_id, subject_id, category_id, data_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager PolicyManager.delete_subject_assignment("", policy_id, subject_id, category_id, data_id) diff --git a/moon_manager/tests/unit_python/helpers/category_helper.py b/moon_manager/tests/unit_python/helpers/category_helper.py index 6c419ca8..bbb04e09 100644 --- a/moon_manager/tests/unit_python/helpers/category_helper.py +++ b/moon_manager/tests/unit_python/helpers/category_helper.py @@ -1,40 +1,47 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + def add_subject_category(cat_id=None, value=None): - from python_moondb.core import ModelManager - category = ModelManager.add_subject_category(user_id=None, category_id=cat_id, value=value) + from moon_manager.db_driver import ModelManager + category = ModelManager.add_subject_category(moon_user_id=None, category_id=cat_id, value=value) return category def get_subject_category(cat_id=None): - from python_moondb.core import ModelManager - category = ModelManager.get_subject_categories(user_id=None, category_id=cat_id) + from moon_manager.db_driver import ModelManager + category = ModelManager.get_subject_categories(moon_user_id=None, category_id=cat_id) return category def add_object_category(cat_id=None, value=None): - from python_moondb.core import ModelManager - category = ModelManager.add_object_category(user_id=None, category_id=cat_id, value=value) + from moon_manager.db_driver import ModelManager + category = ModelManager.add_object_category(moon_user_id=None, category_id=cat_id, value=value) return category def get_object_category(cat_id=None): - from python_moondb.core import ModelManager - category = ModelManager.get_object_categories(user_id=None, category_id=cat_id) + from moon_manager.db_driver import ModelManager + category = ModelManager.get_object_categories(moon_user_id=None, category_id=cat_id) return category def add_action_category(cat_id=None, value=None): - from python_moondb.core import ModelManager - category = ModelManager.add_action_category(user_id=None, category_id=cat_id, value=value) + from moon_manager.db_driver import ModelManager + category = ModelManager.add_action_category(moon_user_id=None, category_id=cat_id, value=value) return category def get_action_category(cat_id=None): - from python_moondb.core import ModelManager - category = ModelManager.get_action_categories(user_id=None, category_id=cat_id) + from moon_manager.db_driver import ModelManager + category = ModelManager.get_action_categories(moon_user_id=None, category_id=cat_id) return category diff --git a/moon_manager/tests/unit_python/helpers/data_builder.py b/moon_manager/tests/unit_python/helpers/data_builder.py index 91808cbe..e2799375 100644 --- a/moon_manager/tests/unit_python/helpers/data_builder.py +++ b/moon_manager/tests/unit_python/helpers/data_builder.py @@ -1,15 +1,21 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug from .category_helper import * from .policy_helper import * from .data_helper import * from helpers import model_helper from .meta_rule_helper import * -import api.utilities as utilities -import json from uuid import uuid4 @@ -55,7 +61,7 @@ def create_pdp(policies_ids): value = { "name": "test_pdp", "security_pipeline": policies_ids, - "keystone_project_id": "keystone_project_id1", + "vim_project_id": "vim_project_id1", "description": "...", } return value @@ -96,7 +102,7 @@ def create_new_policy(subject_category_name=None, object_category_name=None, def create_new_meta_rule(subject_category_name=None, object_category_name=None, - action_category_name=None, meta_rule_name=None): + action_category_name=None, meta_rule_name=None, empty=None): if not subject_category_name: subject_category_name = "subjectCategory_" + uuid4().hex if not object_category_name: @@ -116,6 +122,12 @@ def create_new_meta_rule(subject_category_name=None, object_category_name=None, "object_categories": [object_category_id], "action_categories": [action_category_id] } + if empty == 'subject': + value["subject_categories"] = [] + if empty == 'object': + value["object_categories"] = [] + if empty == 'action': + value["action_categories"] = [] meta_rule = add_meta_rule(value=value) return subject_category_id, object_category_id, action_category_id, list(meta_rule.keys())[0] @@ -179,7 +191,10 @@ def create_action_data(policy_id, category_id): def get_policy_id_with_subject_assignment(): - client = utilities.register_client() + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -193,13 +208,16 @@ def get_policy_id_with_subject_assignment(): "category_id": subject_category_id, "data_id": data_id } - client.post("/policies/{}/subject_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + response = hug.test.post(assignments, "/policies/{}/subject_assignments/".format(policy_id), + body=data, headers=auth_headers) return policy_id def get_policy_id_with_object_assignment(): - client = utilities.register_client() + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -214,13 +232,16 @@ def get_policy_id_with_object_assignment(): "data_id": data_id } - client.post("/policies/{}/object_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + hug.test.post(assignments, "policies/{}/object_assignments".format(policy_id), body=data, + headers=auth_headers) return policy_id def get_policy_id_with_action_assignment(): - client = utilities.register_client() + from moon_manager.api import assignments + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + subject_category_id, object_category_id, action_category_id, meta_rule_id, policy_id = create_new_policy( subject_category_name="subject_category1" + uuid4().hex, object_category_name="object_category1" + uuid4().hex, @@ -234,12 +255,16 @@ def get_policy_id_with_action_assignment(): "category_id": action_category_id, "data_id": data_id } - client.post("/policies/{}/action_assignments".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) + hug.test.post(assignments, "policies/{}/action_assignments".format(policy_id), body =data, + headers=auth_headers) return policy_id -def add_rules(client): +def add_rules(): + from moon_manager.api import rules + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + sub_id, obj_id, act_id, meta_rule_id, policy_id = create_new_policy("sub_cat" + uuid4().hex, "obj_cat" + uuid4().hex, "act_cat" + uuid4().hex) @@ -249,12 +274,10 @@ def add_rules(client): data = { "meta_rule_id": meta_rule_id, "rule": [sub_data_id, obj_data_id, act_data_id], - "instructions": ( + "instructions": [ {"decision": "grant"}, - ), + ], "enabled": True } - req = client.post("/policies/{}/rules".format(policy_id), data=json.dumps(data), - headers={'Content-Type': 'application/json'}) - rules = utilities.get_json(req.data) - return req, rules, policy_id + req = hug.test.post(rules, "policies/{}/rules".format(policy_id), body=data, headers=auth_headers) + return req, req.data, policy_id diff --git a/moon_manager/tests/unit_python/helpers/data_helper.py b/moon_manager/tests/unit_python/helpers/data_helper.py index e1c05640..cb1ee38c 100644 --- a/moon_manager/tests/unit_python/helpers/data_helper.py +++ b/moon_manager/tests/unit_python/helpers/data_helper.py @@ -1,99 +1,106 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + def get_action_data(policy_id, data_id=None, category_id=None): - from python_moondb.core import PolicyManager - return PolicyManager.get_action_data("", policy_id, data_id, category_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_action_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id) def add_action_data(policy_id, data_id=None, category_id=None, value=None): - from python_moondb.core import PolicyManager - return PolicyManager.add_action_data("", policy_id, data_id, category_id, value) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_action_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id, value=value) def delete_action_data(policy_id, data_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_action_data("", policy_id=policy_id, data_id=data_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_action_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id) def get_object_data(policy_id, data_id=None, category_id=None): - from python_moondb.core import PolicyManager - return PolicyManager.get_object_data("", policy_id, data_id, category_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_object_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id) def add_object_data(policy_id, data_id=None, category_id=None, value=None): - from python_moondb.core import PolicyManager - return PolicyManager.add_object_data("", policy_id, data_id, category_id, value) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_object_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id, value=value) def delete_object_data(policy_id, data_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_object_data("", policy_id=policy_id, data_id=data_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_object_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id) def get_subject_data(policy_id, data_id=None, category_id=None): - from python_moondb.core import PolicyManager - return PolicyManager.get_subject_data("", policy_id, data_id, category_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_subject_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id) def add_subject_data(policy_id, data_id=None, category_id=None, value=None): - from python_moondb.core import PolicyManager - return PolicyManager.set_subject_data("", policy_id, data_id, category_id, value) + from moon_manager.db_driver import PolicyManager + return PolicyManager.set_subject_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id, category_id=category_id, value=value) def delete_subject_data(policy_id, data_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_subject_data("", policy_id=policy_id, data_id=data_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_subject_data(moon_user_id="admin", policy_id=policy_id, data_id=data_id) def get_actions(policy_id, perimeter_id=None): - from python_moondb.core import PolicyManager - return PolicyManager.get_actions("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_actions(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def add_action(policy_id, perimeter_id=None, value=None): - from python_moondb.core import PolicyManager - return PolicyManager.add_action("", policy_id, perimeter_id, value) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_action(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id, value=value) def delete_action(policy_id, perimeter_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_action("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_action(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def get_objects(policy_id, perimeter_id=None): - from python_moondb.core import PolicyManager - return PolicyManager.get_objects("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_objects(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def add_object(policy_id, perimeter_id=None, value=None): - from python_moondb.core import PolicyManager - return PolicyManager.add_object("", policy_id, perimeter_id, value) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_object(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id, value=value) def delete_object(policy_id, perimeter_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_object("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_object(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def get_subjects(policy_id, perimeter_id=None): - from python_moondb.core import PolicyManager - return PolicyManager.get_subjects("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_subjects(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def add_subject(policy_id, perimeter_id=None, value=None): - from python_moondb.core import PolicyManager - return PolicyManager.add_subject("", policy_id, perimeter_id, value) + from moon_manager.db_driver import PolicyManager + return PolicyManager.add_subject(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id, value=value) def delete_subject(policy_id, perimeter_id): - from python_moondb.core import PolicyManager - PolicyManager.delete_subject("", policy_id, perimeter_id) + from moon_manager.db_driver import PolicyManager + PolicyManager.delete_subject(moon_user_id="admin", policy_id=policy_id, perimeter_id=perimeter_id) def get_available_metadata(policy_id): - from python_moondb.core import PolicyManager - return PolicyManager.get_available_metadata("", policy_id) + from moon_manager.db_driver import PolicyManager + return PolicyManager.get_available_metadata(moon_user_id="admin", policy_id=policy_id) diff --git a/moon_manager/tests/unit_python/helpers/import_export_helper.py b/moon_manager/tests/unit_python/helpers/import_export_helper.py new file mode 100644 index 00000000..1ba94fd0 --- /dev/null +++ b/moon_manager/tests/unit_python/helpers/import_export_helper.py @@ -0,0 +1,287 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +from api import test_models as test_models +from api import test_policies as test_policies +from api import test_perimeter as test_perimeter +from api import test_meta_data as test_categories +from api import test_data as test_data +from api import test_meta_rules as test_meta_rules +from api import test_assignement as test_assignments +from api import test_rules as test_rules +import logging +import hug + +logger = logging.getLogger("moon.manager.test.api." + __name__) + + +def clean_models(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req, models = test_models.get_models() + for key in models["models"]: + from moon_manager.api import models + hug.test.delete(models, "/models/{}".format(key), headers=auth_headers) + + +def clean_policies(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for key in policies["policies"]: + from moon_manager.api import policy + req = hug.test.delete(policy, "/policies/{}".format(key), headers=auth_headers) + assert req.status == hug.HTTP_200 + + +def clean_subjects(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + subjects = test_perimeter.get_subjects() + logger.info("subjects {}".format(subjects)) + for key in subjects[1]["subjects"]: + subject = subjects[1]["subjects"][key] + policy_keys = subject["policy_list"] + logger.info("subjects policy_keys {}".format(policy_keys)) + for policy_key in policy_keys: + from moon_manager.api import perimeter + hug.test.delete(perimeter, "/policies/{}/subjects/{}".format(policy_key, key), headers=auth_headers ) + hug.test.delete(perimeter, "/subjects/{}".format(key), headers=auth_headers) + + +def clean_objects(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + objects = test_perimeter.get_objects() + logger.info("objects {}".format(objects)) + for key in objects[1]["objects"]: + object_ = objects[1]["objects"][key] + policy_keys = object_["policy_list"] + logger.info("objects policy_keys {}".format(policy_keys)) + for policy_key in policy_keys: + from moon_manager.api import perimeter + hug.test.delete(perimeter, "/policies/{}/objects/{}".format(policy_key, key), headers=auth_headers ) + hug.test.delete(perimeter, "/objects/{}".format(key), headers=auth_headers) + +def clean_actions(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + actions = test_perimeter.get_actions() + logger.info("actions {}".format(actions)) + for key in actions[1]["actions"]: + action = actions[1]["actions"][key] + policy_keys = action["policy_list"] + logger.info("action policy_keys {}".format(policy_keys)) + from moon_manager.api import perimeter + for policy_key in policy_keys: + hug.test.delete(perimeter, "/policies/{}/actions/{}".format(policy_key, key), headers=auth_headers) + hug.test.delete(perimeter, "/actions/{}".format(key), headers=auth_headers) + + + +def clean_subject_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, categories = test_categories.get_subject_categories() + logger.info(categories) + for key in categories["subject_categories"]: + from moon_manager.api import meta_data + hug.test.delete(meta_data, "/subject_categories/{}".format(key), headers=auth_headers) + + +def clean_object_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, categories = test_categories.get_object_categories() + logger.info(categories) + for key in categories["object_categories"]: + from moon_manager.api import meta_data + hug.test.delete(meta_data, "/object_categories/{}".format(key), headers=auth_headers) + + +def clean_action_categories(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, categories = test_categories.get_action_categories() + logger.info(categories) + for key in categories["action_categories"]: + from moon_manager.api import meta_data + hug.test.delete(meta_data, "/action_categories/{}".format(key), headers=auth_headers) + + +def clean_subject_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + logger.info("clean_subject_data on {}".format(policies)) + for policy_key in policies["policies"]: + req, data = test_data.get_subject_data(policy_id=policy_key) + logger.info("============= data {}".format(data)) + for data_item in data["subject_data"]: + if data_item["data"]: + for data_id in data_item["data"]: + logger.info("============= Deleting {}/{}".format(policy_key, data_id)) + from moon_manager.api import data + hug.test.delete(data, "/policies/{}/subject_data/{}/{}".format(policy_key, + data_item['category_id'], data_id), headers=auth_headers) + + +def clean_object_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, data = test_data.get_object_data(policy_id=policy_key) + for data_item in data["object_data"]: + if data_item["data"]: + for data_id in data_item["data"]: + logger.info("============= object_data {}/{}".format(policy_key, data_id)) + from moon_manager.api import data + hug.test.delete(data, "/policies/{}/object_data/{}/{}".format(policy_key, + data_item['category_id'], data_id), headers=auth_headers) + + +def clean_action_data(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, data = test_data.get_action_data(policy_id=policy_key) + for data_item in data["action_data"]: + if data_item["data"]: + for data_id in data_item["data"]: + logger.info("============= action_data {}/{}".format(policy_key, data_id)) + from moon_manager.api import data + hug.test.delete(data, "/policies/{}/action_data/{}/{}".format(policy_key, + data_item['category_id'], data_id), headers=auth_headers) + + +def clean_meta_rule(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req, meta_rules_obj = test_meta_rules.get_meta_rules() + meta_rules_obj = meta_rules_obj["meta_rules"] + for meta_rule_key in meta_rules_obj: + logger.info("clean_meta_rule.meta_rule_key={}".format(meta_rule_key)) + logger.info("clean_meta_rule.meta_rule={}".format(meta_rules_obj[meta_rule_key])) + from moon_manager.api import meta_rules + hug.test.delete(meta_rules, "/meta_rules/{}".format(meta_rule_key), headers=auth_headers) + + +def clean_subject_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, assignments = test_assignments.get_subject_assignment(policy_key) + for key in assignments["subject_assignments"]: + subject_key = assignments["subject_assignments"][key]["subject_id"] + cat_key = assignments["subject_assignments"][key]["category_id"] + data_keys = assignments["subject_assignments"][key]["assignments"] + for data_key in data_keys: + from moon_manager.api import assignments + hug.test.delete(assignments, + "/policies/{}/subject_assignments/{}/{}/{}".format(policy_key, + subject_key, cat_key, data_key), headers=auth_headers) + + +def clean_object_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, assignments = test_assignments.get_object_assignment(policy_key) + for key in assignments["object_assignments"]: + object_key = assignments["object_assignments"][key]["object_id"] + cat_key = assignments["object_assignments"][key]["category_id"] + data_keys = assignments["object_assignments"][key]["assignments"] + for data_key in data_keys: + from moon_manager.api import assignments + hug.test.delete(assignments, + "/policies/{}/object_assignments/{}/{}/{}".format(policy_key, + object_key, cat_key, data_key), headers=auth_headers) + + +def clean_action_assignments(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, assignments = test_assignments.get_action_assignment(policy_key) + for key in assignments["action_assignments"]: + action_key = assignments["action_assignments"][key]["action_id"] + cat_key = assignments["action_assignments"][key]["category_id"] + data_keys = assignments["action_assignments"][key]["assignments"] + for data_key in data_keys: + from moon_manager.api import assignments + hug.test.delete(assignments, + "/policies/{}/action_assignments/{}/{}/{}".format(policy_key, + action_key, cat_key, data_key), headers=auth_headers) + + +def clean_rules(): + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + req = test_policies.get_policies(auth_headers=auth_headers) + + policies = req.data + for policy_key in policies["policies"]: + req, rules = test_rules.get_rules(policy_key) + rules = rules["rules"]["rules"] + for rule_key in rules: + from moon_manager.api import rules + hug.test.delete(rules, "/policies/{}/rules/{}".format(policy_key, rule_key["id"]), headers=auth_headers) + + +def clean_all(): + clean_rules() + + clean_subject_assignments() + clean_object_assignments() + clean_action_assignments() + + clean_subject_data() + clean_object_data() + clean_action_data() + + clean_actions() + clean_objects() + clean_subjects() + + clean_policies() + clean_models() + clean_meta_rule() + + clean_subject_categories() + clean_object_categories() + clean_action_categories() diff --git a/moon_manager/tests/unit_python/helpers/meta_rule_helper.py b/moon_manager/tests/unit_python/helpers/meta_rule_helper.py index e882706b..0542d394 100644 --- a/moon_manager/tests/unit_python/helpers/meta_rule_helper.py +++ b/moon_manager/tests/unit_python/helpers/meta_rule_helper.py @@ -1,18 +1,25 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + from helpers import data_builder as builder from uuid import uuid4 def set_meta_rule(meta_rule_id, value=None): - from python_moondb.core import ModelManager + from moon_manager.db_driver import ModelManager if not value: - action_category_id = builder.create_action_category("action_category_id1"+uuid4().hex) - subject_category_id = builder.create_subject_category("subject_category_id1"+uuid4().hex) - object_category_id = builder.create_object_category("object_category_id1"+uuid4().hex) + action_category_id = builder.create_action_category("action_category_id1" + uuid4().hex) + subject_category_id = builder.create_subject_category("subject_category_id1" + uuid4().hex) + object_category_id = builder.create_object_category("object_category_id1" + uuid4().hex) value = { "name": "MLS_meta_rule", "description": "test", @@ -20,30 +27,58 @@ def set_meta_rule(meta_rule_id, value=None): "object_categories": [object_category_id], "action_categories": [action_category_id] } - return ModelManager.set_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value) + return ModelManager.set_meta_rule(moon_user_id=None, meta_rule_id=meta_rule_id, value=value) def add_meta_rule(meta_rule_id=None, value=None): - from python_moondb.core import ModelManager + from moon_manager.db_driver import ModelManager if not value: - action_category_id = builder.create_action_category("action_category_id1"+uuid4().hex) - subject_category_id = builder.create_subject_category("subject_category_id1"+uuid4().hex) - object_category_id = builder.create_object_category("object_category_id1"+uuid4().hex) + action_category_id = builder.create_action_category("action_category_id1" + uuid4().hex) + subject_category_id = builder.create_subject_category("subject_category_id1" + uuid4().hex) + object_category_id = builder.create_object_category("object_category_id1" + uuid4().hex) value = { - "name": "MLS_meta_rule"+uuid4().hex, + "name": "MLS_meta_rule" + uuid4().hex, "description": "test", "subject_categories": [subject_category_id], "object_categories": [object_category_id], "action_categories": [action_category_id] } - return ModelManager.add_meta_rule(user_id=None, meta_rule_id=meta_rule_id, value=value) + return ModelManager.add_meta_rule(moon_user_id=None, meta_rule_id=meta_rule_id, value=value) + + +def get_body_meta_rule_with_empty_category_in_mid(type=None): + action_category_id1 = builder.create_action_category("action_category_id1" + uuid4().hex) + subject_category_id1 = builder.create_subject_category("subject_category_id1" + uuid4().hex) + object_category_id1 = builder.create_object_category("object_category_id1" + uuid4().hex) + + action_category_id2 = builder.create_action_category("action_category_id1" + uuid4().hex) + subject_category_id2 = builder.create_subject_category("subject_category_id1" + uuid4().hex) + object_category_id2 = builder.create_object_category("object_category_id1" + uuid4().hex) + value = { + "name": "MLS_meta_rule" + uuid4().hex, + "description": "test", + "subject_categories": [subject_category_id1], + "object_categories": [object_category_id1], + "action_categories": [action_category_id1] + } + if type == 'subject': + value['subject_categories'].append("") + if type == 'object': + value['object_categories'].append("") + if type == 'action': + value['action_categories'].append("") + + value['subject_categories'].append(subject_category_id2) + value['object_categories'].append(object_category_id2) + value['action_categories'].append(action_category_id2) + return value def get_meta_rules(meta_rule_id=None): - from python_moondb.core import ModelManager - return ModelManager.get_meta_rules(user_id=None, meta_rule_id=meta_rule_id) + from moon_manager.db_driver import ModelManager + return ModelManager.get_meta_rules(moon_user_id=None, meta_rule_id=meta_rule_id) def delete_meta_rules(meta_rule_id=None): - from python_moondb.core import ModelManager - ModelManager.delete_meta_rule(user_id=None, meta_rule_id=meta_rule_id) + from moon_manager.db_driver import ModelManager + ModelManager.delete_meta_rule(moon_user_id=None, meta_rule_id=meta_rule_id) diff --git a/moon_manager/tests/unit_python/helpers/model_helper.py b/moon_manager/tests/unit_python/helpers/model_helper.py index 73808e03..ed705af8 100644 --- a/moon_manager/tests/unit_python/helpers/model_helper.py +++ b/moon_manager/tests/unit_python/helpers/model_helper.py @@ -1,19 +1,26 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + from helpers import data_builder as builder from uuid import uuid4 def get_models(model_id=None): - from python_moondb.core import ModelManager - return ModelManager.get_models(user_id=None, model_id=model_id) + from moon_manager.db_driver import ModelManager + return ModelManager.get_models(moon_user_id=None, model_id=model_id) def add_model(model_id=None, value=None): - from python_moondb.core import ModelManager + from moon_manager.db_driver import ModelManager if not value: subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule() name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id @@ -22,27 +29,53 @@ def add_model(model_id=None, value=None): "description": "test", "meta_rules": [meta_rule_id] } - return ModelManager.add_model(user_id=None, model_id=model_id, value=value) + return ModelManager.add_model(moon_user_id=None, model_id=model_id, value=value) + + +def add_model_without_meta_rule(model_id=None, value=None): + from moon_manager.db_driver import ModelManager + if not value: + name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id + value = { + "name": name, + "description": "test", + "meta_rules": "" + } + return ModelManager.add_model(moon_user_id=None, model_id=model_id, value=value) + + +def add_model_with_blank_subject_meta_rule(model_id=None, value=None): + from moon_manager.db_driver import ModelManager + if not value: + subject_category_id, object_category_id, action_category_id, meta_rule_id = builder.create_new_meta_rule(empty='subject') + name = "MLS"+uuid4().hex if model_id is None else "MLS " + model_id + value = { + "name": name, + "description": "test", + "meta_rules": [meta_rule_id] + } + return ModelManager.add_model(moon_user_id=None, model_id=model_id, value=value) + def delete_models(uuid=None, name=None): - from python_moondb.core import ModelManager + from moon_manager.db_driver import ModelManager if not uuid: for model_id, model_value in get_models(): if name == model_value['name']: uuid = model_id break - ModelManager.delete_model(user_id=None, model_id=uuid) + ModelManager.delete_model(moon_user_id=None, model_id=uuid) def delete_all_models(): - from python_moondb.core import ModelManager + from moon_manager.db_driver import ModelManager models_values = get_models() print(models_values) for model_id, model_value in models_values.items(): - ModelManager.delete_model(user_id=None, model_id=model_id) + ModelManager.delete_model(moon_user_id=None, model_id=model_id) def update_model(model_id=None, value=None): - from python_moondb.core import ModelManager - return ModelManager.update_model(user_id=None, model_id=model_id, value=value) + from moon_manager.db_driver import ModelManager + return ModelManager.update_model(moon_user_id=None, model_id=model_id, value=value) diff --git a/moon_manager/tests/unit_python/helpers/pdp_helper.py b/moon_manager/tests/unit_python/helpers/pdp_helper.py index 3d169b06..e970961a 100644 --- a/moon_manager/tests/unit_python/helpers/pdp_helper.py +++ b/moon_manager/tests/unit_python/helpers/pdp_helper.py @@ -1,23 +1,31 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + def update_pdp(pdp_id, value): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager return PDPManager.update_pdp("", pdp_id, value) def delete_pdp(pdp_id): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager PDPManager.delete_pdp("", pdp_id) def add_pdp(pdp_id=None, value=None): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager return PDPManager.add_pdp("", pdp_id, value) def get_pdp(pdp_id=None): - from python_moondb.core import PDPManager + from moon_manager.db_driver import PDPManager return PDPManager.get_pdp("", pdp_id) diff --git a/moon_manager/tests/unit_python/helpers/policy_helper.py b/moon_manager/tests/unit_python/helpers/policy_helper.py index eddd0b8d..ffd0d1bb 100644 --- a/moon_manager/tests/unit_python/helpers/policy_helper.py +++ b/moon_manager/tests/unit_python/helpers/policy_helper.py @@ -1,17 +1,25 @@ -# Copyright 2015 Open Platform for NFV Project, Inc. and its contributors -# This software is distributed under the terms and conditions of the 'Apache-2.0' -# license which can be found in the file 'LICENSE' in this package distribution -# or at 'http://www.apache.org/licenses/LICENSE-2.0'. +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + from uuid import uuid4 +from helpers import model_helper def get_policies(): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_policies("admin") def add_policies(policy_id=None, value=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager if not value: value = { "name": "test_policy"+ uuid4().hex, @@ -19,11 +27,24 @@ def add_policies(policy_id=None, value=None): "genre": "authz", "description": "test", } - return PolicyManager.add_policy("admin", policy_id=policy_id, value=value) + return PolicyManager.add_policy(moon_user_id="admin", policy_id=policy_id, value=value) + + +def add_policies_with_model(policy_id=None, value=None): + from moon_manager.db_driver import PolicyManager + req = model_helper.add_model(model_id="mls_model_id" + uuid4().hex) + model_id = list(req.keys())[0] + data = { + "name": "test_policy"+ uuid4().hex, + "description": "test", + "model_id": model_id, + "genre": "genre" + } + return PolicyManager.add_policy(moon_user_id="admin", policy_id=policy_id, value=data) def delete_policies(uuid=None, name=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager if not uuid: for policy_id, policy_value in get_policies(): if name == policy_value['name']: @@ -33,31 +54,31 @@ def delete_policies(uuid=None, name=None): def update_policy(policy_id, value): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.update_policy("admin", policy_id, value) def get_policy_from_meta_rules(meta_rule_id): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_policy_from_meta_rules("admin", meta_rule_id) def get_rules(policy_id=None, meta_rule_id=None, rule_id=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager return PolicyManager.get_rules("", policy_id, meta_rule_id, rule_id) def add_rule(policy_id=None, meta_rule_id=None, value=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager if not value: value = { "rule": ("high", "medium", "vm-action"), - "instructions": ({"decision": "grant"}), + "instructions": [{"decision": "grant"}], "enabled": "", } return PolicyManager.add_rule("", policy_id, meta_rule_id, value) def delete_rule(policy_id=None, rule_id=None): - from python_moondb.core import PolicyManager + from moon_manager.db_driver import PolicyManager PolicyManager.delete_rule("", policy_id, rule_id) diff --git a/moon_manager/tests/unit_python/helpers/rules_helper.py b/moon_manager/tests/unit_python/helpers/rules_helper.py new file mode 100644 index 00000000..ce7e8bd2 --- /dev/null +++ b/moon_manager/tests/unit_python/helpers/rules_helper.py @@ -0,0 +1,18 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +def get_headers(): + from moon_utilities.auth_functions import get_api_key_for_user + + auth_headers = {"X-Api-Key": get_api_key_for_user("admin"), + 'Content-Type': 'application/json'} + return auth_headers diff --git a/moon_manager/tests/unit_python/mock_engine.py b/moon_manager/tests/unit_python/mock_engine.py new file mode 100644 index 00000000..0685d376 --- /dev/null +++ b/moon_manager/tests/unit_python/mock_engine.py @@ -0,0 +1,19 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + + +def register_engine(m): + for port in range(20000, 20010): + m.register_uri( + 'POST', 'http://127.0.0.1:{}/update'.format(port), + json={} + ) diff --git a/moon_manager/tests/unit_python/mock_keystone.py b/moon_manager/tests/unit_python/mock_keystone.py new file mode 100644 index 00000000..73e5681d --- /dev/null +++ b/moon_manager/tests/unit_python/mock_keystone.py @@ -0,0 +1,59 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + +import requests_mock + + +def register_keystone(m): + m.register_uri( + 'POST', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'DELETE', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/users?name=testuser&domain_id=default', + json={"users": {}} + ) + m.register_uri( + 'GET', 'http://keystone:5000/v3/users?name=testuser&domain_id=default', + json={"users": {}} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/users/', + json={"users": [{ + "id": "b34e5a29-5494-4cc5-9356-daa244b8c254" + }]} + ) + + def match_request_text(request): + # request.url may be None, or '' prevents a TypeError. + return 'http://keystone:5000/v3/users?name=' in request.url + + m.register_uri( + requests_mock.ANY, '/v3/users', + additional_matcher=match_request_text, + json={"users": [{ + "id": "b34e5a29-5494-4cc5-9356-daa244b8c254" + }]} + ) + m.register_uri( + 'POST', 'http://keystone:5000/v3/projects/', + json={ + "description": "test_project", + "domain_id": ['domain_id_1'], + "enabled": True, + "is_domain": False, + "name": 'project_1' + } + ) diff --git a/moon_manager/tests/unit_python/mock_nova.py b/moon_manager/tests/unit_python/mock_nova.py new file mode 100644 index 00000000..e898ad1a --- /dev/null +++ b/moon_manager/tests/unit_python/mock_nova.py @@ -0,0 +1,28 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + +import requests_mock + + +def register_nova(m): + m.register_uri( + 'POST', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'DELETE', 'http://keystone:5000/v3/auth/tokens', + headers={'X-Subject-Token': "b34e5a29-5494-4cc5-9356-daa244b8c254"} + ) + m.register_uri( + 'GET', 'http://keystone:5000/compute/v2.1/servers', + json={"servers": [{"name": "vm1"}]} + ) + diff --git a/moon_manager/tests/unit_python/mock_slaves.py b/moon_manager/tests/unit_python/mock_slaves.py new file mode 100644 index 00000000..935bb0de --- /dev/null +++ b/moon_manager/tests/unit_python/mock_slaves.py @@ -0,0 +1,38 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +SLAVES = { + "slaves": { + "d464cc58a0cd46dea3191ba70f4e7df8": { + "name": "slave_test", + "address": "", + "description": "...", + "api_key": "e58a882a6b658a22660f00a0c273e7f6b4c4eb5abe54eccba2cae307905d67e3746537bd790c41887e11840c2d186b6d6eeec0e426bcfa7a872cc3417a35124a", + "log": "/tmp/moon_d464cc58a0cd46dea3191ba70f4e7df8.log", + "process": "/tmp/d464cc58a0cd46dea3191ba70f4e7df8.pid", + "extra": { + "description": "...", + "starttime": 1543851265.76279, + "port": 10001, + "server_ip": "127.0.0.1", + "status": "down" + } + } + } +} + + +def register_slaves(m): + m.register_uri( + 'GET', 'http://localhost/slaves', + json=SLAVES + ) diff --git a/moon_manager/tests/unit_python/plugins/__init__.py b/moon_manager/tests/unit_python/plugins/__init__.py new file mode 100644 index 00000000..1856aa2c --- /dev/null +++ b/moon_manager/tests/unit_python/plugins/__init__.py @@ -0,0 +1,12 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + diff --git a/moon_manager/tests/unit_python/plugins/test_global_attrs.py b/moon_manager/tests/unit_python/plugins/test_global_attrs.py new file mode 100644 index 00000000..603e03ae --- /dev/null +++ b/moon_manager/tests/unit_python/plugins/test_global_attrs.py @@ -0,0 +1,148 @@ +# Software Name: MOON + +# Version: 5.4 + +# SPDX-FileCopyrightText: Copyright (c) 2018-2020 Orange and its contributors +# SPDX-License-Identifier: Apache-2.0 + +# This software is distributed under the 'Apache License 2.0', +# the text of which is available at 'http://www.apache.org/licenses/LICENSE-2.0.txt' +# or see the "LICENSE" file for more details. + + +import hug +from moon_manager.pip_driver import AttrsManager +from moon_manager.api.configuration import get_configuration + + +def test_mode_add_get(): + default_value = get_configuration( + "information")["global_attrs"]["attributes"]["mode"]["default"] + value = AttrsManager.delete_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + value = AttrsManager.get_object(object_type="mode") + assert value["value"] == default_value + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + + +def test_mode_add_gets(): + default_value = \ + get_configuration("information")["global_attrs"]["attributes"]["mode"]["default"] + value = AttrsManager.delete_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + values = AttrsManager.get_objects() + assert "mode" in values + assert values["mode"]["value"] == default_value + assert isinstance(values["mode"], dict) + for key in ("id", "value", "default", "values"): + assert key in values["mode"] + assert values["mode"]["value"] == default_value + + +def test_mode_update(): + value = AttrsManager.update_object(object_id="build", object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + + +def test_mode_delete(): + value = AttrsManager.update_object(object_id="build", object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + value = AttrsManager.delete_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "run" + + +def test_hug_mode_add_get(): + from moon_manager.api import attributes + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + default_value = get_configuration( + "information")["global_attrs"]["attributes"]["mode"]["default"] + + req = hug.test.delete(attributes, "/attributes/{}".format("mode"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + + +def test_hug_mode_update(): + from moon_manager.api import attributes + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + + req = hug.test.put(attributes, "/attributes/{}/{}".format("mode", "build"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + + +def test_hug_mode_delete(): + from moon_manager.api import attributes + from moon_utilities.auth_functions import get_api_key_for_user + auth_headers = {"X-Api-Key": get_api_key_for_user("admin")} + default_value = get_configuration( + "information")["global_attrs"]["attributes"]["mode"]["default"] + + req = hug.test.put(attributes, "/attributes/{}/{}".format("mode", "build"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == "build" + req = hug.test.delete(attributes, "/attributes/{}".format("mode"), headers=auth_headers) + assert req.status == hug.HTTP_200 + value = req.data + assert isinstance(value, dict) + assert "attributes" in value + value = value["attributes"] + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value + value = AttrsManager.get_object(object_type="mode") + assert isinstance(value, dict) + for key in ("id", "value", "default", "values"): + assert key in value + assert value["value"] == default_value diff --git a/moon_manager/tests/unit_python/requirements.txt b/moon_manager/tests/unit_python/requirements.txt index d6f190e4..e021a5fb 100644 --- a/moon_manager/tests/unit_python/requirements.txt +++ b/moon_manager/tests/unit_python/requirements.txt @@ -1,5 +1,11 @@ -flask -flask_cors -flask_restful -python_moondb==1.2.20 -python_moonutilities==1.4.20 +hug!=2.5.0 +moon_utilities +sqlalchemy +pymysql +pytest-mock +pytest-cov +requests_mock +tinydb +pytest +pytest-benchmark +pyaml |