From 7bb53c64da2dcf88894bfd31503accdd81498f3d Mon Sep 17 00:00:00 2001 From: Thomas Duval Date: Wed, 3 Jun 2020 10:06:52 +0200 Subject: Update to new version 5.4 Signed-off-by: Thomas Duval Change-Id: Idcd868133d75928a1ffd74d749ce98503e0555ea --- .../tests/unit_python/conftest.py | 14 + .../tests/unit_python/mock_repo/__init__.py | 42 ++ .../unit_python/mock_repo/components_utilities.py | 136 +++++++ .../tests/unit_python/mock_repo/data.py | 315 ++++++++++++++ .../tests/unit_python/mock_repo/urls.py | 150 +++++++ .../tests/unit_python/requirements.txt | 1 + .../tests/unit_python/test_cache.py | 452 +++++++++++++++++++++ .../tests/unit_python/test_configuration.py | 166 ++++++++ .../tests/unit_python/test_validated_input.py | 154 +++++++ 9 files changed, 1430 insertions(+) create mode 100644 old/python_moonutilities/tests/unit_python/conftest.py create mode 100644 old/python_moonutilities/tests/unit_python/mock_repo/__init__.py create mode 100644 old/python_moonutilities/tests/unit_python/mock_repo/components_utilities.py create mode 100644 old/python_moonutilities/tests/unit_python/mock_repo/data.py create mode 100644 old/python_moonutilities/tests/unit_python/mock_repo/urls.py create mode 100644 old/python_moonutilities/tests/unit_python/requirements.txt create mode 100644 old/python_moonutilities/tests/unit_python/test_cache.py create mode 100644 old/python_moonutilities/tests/unit_python/test_configuration.py create mode 100644 old/python_moonutilities/tests/unit_python/test_validated_input.py (limited to 'old/python_moonutilities/tests/unit_python') diff --git a/old/python_moonutilities/tests/unit_python/conftest.py b/old/python_moonutilities/tests/unit_python/conftest.py new file mode 100644 index 00000000..34e5c272 --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/conftest.py @@ -0,0 +1,14 @@ +import pytest +import requests_mock +import mock_repo + + +@pytest.fixture(autouse=True) +def no_requests(monkeypatch): + """ Modify the response from Requests module + """ + with requests_mock.Mocker(real_http=True) as m: + mock_repo.register_cache(m) + + print("End registering URI") + yield m \ No newline at end of file diff --git a/old/python_moonutilities/tests/unit_python/mock_repo/__init__.py b/old/python_moonutilities/tests/unit_python/mock_repo/__init__.py new file mode 100644 index 00000000..fa50edb3 --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/mock_repo/__init__.py @@ -0,0 +1,42 @@ +import mock_repo.urls as register_urls +import mock_repo.data as data_mock + + +def register_cache(m): + """ Modify the response from Requests module + """ + register_urls.register_components(m) + register_urls.register_keystone(m) + + register_urls.register_pdp(m) + register_urls.register_meta_rules(m) + register_urls.register_policies(m) + register_urls.register_models(m) + + register_urls.register_policy_subject(m, data_mock.shared_ids["policy"]["policy_id_1"]) + register_urls.register_policy_subject_invalid_response(m, data_mock.shared_ids["policy"]["policy_id_invalid_response"]) + + register_urls.register_policy_object(m, data_mock.shared_ids["policy"]["policy_id_1"]) + register_urls.register_policy_object_invalid_response(m, data_mock.shared_ids["policy"]["policy_id_invalid_response"]) + + register_urls.register_policy_action(m, data_mock.shared_ids["policy"]["policy_id_1"]) + register_urls.register_policy_action_invalid_response(m, data_mock.shared_ids["policy"]["policy_id_invalid_response"]) + + register_urls.register_policy_subject_assignment(m, data_mock.shared_ids["policy"]["policy_id_1"], data_mock.shared_ids["perimeter"]["perimeter_id_1"]) + + register_urls.register_policy_subject_assignment_list(m, data_mock.shared_ids["policy"]["policy_id_2"]) + + register_urls.register_policy_object_assignment(m, data_mock.shared_ids["policy"]["policy_id_1"], data_mock.shared_ids["perimeter"]["perimeter_id_2"]) + + register_urls.register_policy_object_assignment_list(m, data_mock.shared_ids["policy"]["policy_id_2"]) + + register_urls.register_policy_action_assignment(m, data_mock.shared_ids["policy"]["policy_id_1"], data_mock.shared_ids["perimeter"]["perimeter_id_3"]) + + register_urls.register_policy_action_assignment_list(m, data_mock.shared_ids["policy"]["policy_id_2"]) + # register_urls.register_pods(m) + + # register_urls.register_policy_action_assignment(m, "policy_id_2", "perimeter_id_2") + # register_urls.register_policy_action_assignment(m, "policy_id_2", "perimeter_id_2") + # register_urls.register_policy_action_assignment(m, "policy_id_2", "perimeter_id_2") + + register_urls.register_rules(m, "policy_id1") diff --git a/old/python_moonutilities/tests/unit_python/mock_repo/components_utilities.py b/old/python_moonutilities/tests/unit_python/mock_repo/components_utilities.py new file mode 100644 index 00000000..11686ce4 --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/mock_repo/components_utilities.py @@ -0,0 +1,136 @@ +import base64 +import json + + +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": "interface" + }, + "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" + } +} + + +def get_b64_conf(component=None): + if component == "components": + return base64.b64encode( + json.dumps(CONF["components"]).encode('utf-8')+b"\n").decode('utf-8') + elif component in CONF: + return base64.b64encode( + json.dumps( + CONF[component]).encode('utf-8')+b"\n").decode('utf-8') + elif not component: + return base64.b64encode( + json.dumps(CONF).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(component.encode('utf-8')+b"\n").decode('utf-8') diff --git a/old/python_moonutilities/tests/unit_python/mock_repo/data.py b/old/python_moonutilities/tests/unit_python/mock_repo/data.py new file mode 100644 index 00000000..0e772e2c --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/mock_repo/data.py @@ -0,0 +1,315 @@ +components = ( + "logging", + "openstack/keystone", + "database", + "slave", + "components/manager", + "components/orchestrator", + "components/pipeline", + "components/port_start" +) + +shared_ids = { + "policy": { + "policy_id_1": "policy_id_1", + "policy_id_2": "policy_id_2", + "policy_id_3": "policy_id_3", + "policy_id_invalid_response": "policy_id_invalid_response" + }, + "category": { + "category_id_1": "category_id_1", + "invalid_category_id_1": " invalid_category_id_1" + }, + "perimeter": { + "perimeter_id_1": "subject_id_1", + "perimeter_id_2": "object_id_1", + "perimeter_id_3": "action_id_1" + }, + "meta_rule": { + "meta_rule_id_1": "meta_rule_id_1", + "meta_rule_id_2": "meta_rule_id_2" + }, + "rule": { + "rule_id_1": "rule_id_2", + "rule_id_2": "rule_id_2" + }, + "model": { + "model_id_1": "model_id_1" + }, + "subject": { + "subject_id_1": "subject_id_1", + "invalid_subject_id": "invalid_subject_id", + "invalid_category_id": "invalid_category_id", + "invalid_assignment_id": "invalid_assignment_id" + }, + "object": { + "object_id_1": "object_id_1", + "invalid_object_id": "invalid_object_id", + "invalid_category_id": "invalid_category_id", + "invalid_assignment_id": "invalid_assignment_id" + }, + "action": { + "action_id_1": "action_id_1", + "invalid_action_id": "invalid_action_id", + "invalid_category_id": "invalid_category_id", + "invalid_assignment_id": "invalid_assignment_id" + } +} + +pdp_mock = { + "pdp_id1": { + "name": "...", + "security_pipeline": ["policy_id_1", "policy_id_2"], + "keystone_project_id": "keystone_project_id1", + "description": "...", + } +} + +meta_rules_mock = { + shared_ids["meta_rule"]["meta_rule_id_1"]: { + "name": "meta_rule1", + "algorithm": "name of the meta rule algorithm", + "subject_categories": ["subject_category_id1", + "subject_category_id2"], + "object_categories": ["object_category_id1"], + "action_categories": ["action_category_id1"] + }, + shared_ids["meta_rule"]["meta_rule_id_2"]: { + "name": "name of the meta rules2", + "algorithm": "name of the meta rule algorithm", + "subject_categories": ["subject_category_id1", + "subject_category_id2"], + "object_categories": ["object_category_id1"], + "action_categories": ["action_category_id1"] + } +} + +policies_mock = { + shared_ids["policy"]["policy_id_1"]: { + "name": "test_policy1", + "model_id": shared_ids["model"]["model_id_1"], + "genre": "authz", + "description": "test", + } +} + +subject_mock = { + shared_ids["policy"]["policy_id_1"]: { + "subject_id": { + "name": "subject_name", + "keystone_id": "keystone_project_id1", + "description": "a description" + } + }, + shared_ids["policy"]["policy_id_invalid_response"]: { + "subject_id": { + "name": "subject_name", + "keystone_id": "keystone_project_id1", + "description": "a description" + } + } + +} + +subject_assignment_mock = { + shared_ids["subject"]["subject_id_1"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "subject_id": "subject_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"], + } +} + +subject_assignment_mock_invalid_subject_id = { + shared_ids["subject"]["invalid_subject_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "subject_id_invalid": "subject_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"], + } +} + +subject_assignment_mock_invalid_category_id = { + shared_ids["subject"]["invalid_category_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "subject_id": "subject_id_1", + "category_id_invalid": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"], + } +} + +subject_assignment_mock_invalid_assignment_id = { + shared_ids["subject"]["invalid_assignment_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "subject_id": "subject_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments_invalid": ["data_id_1, data_id_2"], + } +} + +object_mock = { + shared_ids["policy"]["policy_id_1"]: { + "object_id": { + "name": "object_name", + "description": "a description" + } + } +} + +object_assignment_mock = { + shared_ids["object"]["object_id_1"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "object_id": "object_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +object_assignment_mock_invalid_object_id = { + shared_ids["object"]["invalid_object_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "object_id": "object_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +object_assignment_mock_invalid_category_id = { + shared_ids["object"]["invalid_category_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "object_id": "object_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +object_assignment_mock_invalid_assignment_id = { + shared_ids["object"]["invalid_assignment_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "object_id": "object_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +action_mock = { + shared_ids["policy"]["policy_id_1"]: { + "action_id": { + "name": "action_name", + "description": "a description" + } + } +} + +action_assignment_mock = { + shared_ids["action"]["action_id_1"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "action_id": "action_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +action_assignment_mock_invalid_action_id = { + shared_ids["action"]["invalid_action_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "action_id": "action_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +action_assignment_mock_invalid_category_id = { + shared_ids["action"]["invalid_category_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "action_id": "action_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + +action_assignment_mock_invalid_assignment_id = { + shared_ids["action"]["invalid_assignment_id"]: { + "policy_id": shared_ids["policy"]["policy_id_1"], + "action_id": "action_id_1", + "category_id": shared_ids["category"]["category_id_1"], + "assignments": ["data_id_1, data_id_2"] + } +} + + +models_mock = { + shared_ids["model"]["model_id_1"]: { + "name": "test_model", + "description": "test", + "meta_rules": [shared_ids["meta_rule"]["meta_rule_id_1"]] + } +} + +rules_mock = { + "rules": { + "meta_rule_id": shared_ids["meta_rule"]["meta_rule_id_1"], + shared_ids["rule"]["rule_id_1"]: { + "rule": ["subject_data_id1", + "object_data_id1", + "action_data_id1"], + "instructions": ( + {"decision": "grant"}, + # "grant" to immediately exit, + # "continue" to wait for the result of next policy + # "deny" to deny the request + ) + }, + shared_ids["rule"]["rule_id_2"]: { + "rule": ["subject_data_id2", + "object_data_id2", + "action_data_id2"], + "instructions": ( + { + "update": { + "operation": "add", + # operations may be "add" or "delete" + "target": "rbac:role:admin" + # add the role admin to the current user + } + }, + {"chain": {"name": "rbac"}} + # chain with the policy named rbac + ) + } + } +} + +# pods_mock = { +# # "name": "pod_id1", +# # "hostname": "pod_host", +# # "port": { +# # "PrivatePort": "8998", +# # "Type": "tcp", +# # "IP": "0.0.0.0", +# # "PublicPort": "8080" +# # }, +# # "keystone_project_id": "keystone_project_id1", +# # "pdp_id": "", +# # "meta_rule_id": "meta_rule_id1", +# # "container_name": "container_name1", +# # "plugin_name": "plugin_name1", +# # "container_id": "container_id" +# "pod_id1": { +# "name": "pod_id1", +# "hostname": "pod_host", +# "port": { +# "PrivatePort": "8998", +# "Type": "tcp", +# "IP": "0.0.0.0", +# "PublicPort": "8080" +# }, +# "keystone_project_id": [1], +# "pdp_id": "", +# "meta_rule_id": "meta_rule_id1", +# "container_name": "container_name1", +# "plugin_name": "plugin_name1", +# "container_id": "container_id" +# }, +# +# } diff --git a/old/python_moonutilities/tests/unit_python/mock_repo/urls.py b/old/python_moonutilities/tests/unit_python/mock_repo/urls.py new file mode 100644 index 00000000..41fd1eec --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/mock_repo/urls.py @@ -0,0 +1,150 @@ +import mock_repo.components_utilities as comp_util +import mock_repo.data as data_mock + + +def register_components(m): + for component in data_mock.components: + m.register_uri( + 'GET', 'http://consul:8500/v1/kv/{}'.format(component), + json=[{'Key': component, 'Value': comp_util.get_b64_conf(component)}] + ) + + m.register_uri( + 'PUT', 'http://consul:8500/v1/kv/components/port_start', + json=[] + ) + + m.register_uri( + 'GET', 'http://consul:8500/v1/kv/components?recurse=true', + json=[ + {"Key": key, "Value": comp_util.get_b64_conf(key)} for key in data_mock.components + ], + # json={'Key': "components", 'Value': get_b64_comp_util.CONF("components")} + ) + + +def register_keystone(m): + 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"} + ) + 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": "1111111111111" + }]} + ) + +def register_model_any(m, module_name, mocked_data, key=None): + if key is None: + key = module_name + m.register_uri( + 'GET', 'http://{}:{}/{}'.format(comp_util.CONF['components']['manager']['hostname'], + comp_util.CONF['components']['manager']['port'], module_name), + + json={key: mocked_data} + ) + +def register_policy_any(m, policy_id, module_name, mocked_data, key=None): + if key is None: + key = module_name + m.register_uri( + 'GET', 'http://{}:{}/{}/{}/{}'.format(comp_util.CONF['components']['manager']['hostname'], + comp_util.CONF['components']['manager']['port'], 'policies', + policy_id, module_name), + json={key: mocked_data} + ) + +def register_pdp(m): + register_model_any(m, 'pdp', data_mock.pdp_mock,'pdps') + +def register_meta_rules(m): + register_model_any(m, 'meta_rules',data_mock.meta_rules_mock) + +def register_policies(m): + register_model_any(m, 'policies', data_mock.policies_mock) + + +def register_models(m): + register_model_any(m, 'models', data_mock.models_mock) + +def register_policy_subject(m, policy_id): + register_policy_any(m, policy_id, 'subjects', data_mock.subject_mock[policy_id]) + + +def register_policy_subject_invalid_response(m, policy_id): + register_policy_any(m, policy_id, 'subjects', data_mock.subject_mock[policy_id],'subjects_invalid_key') + +def register_policy_object(m, policy_id): + register_policy_any(m, policy_id, 'objects', data_mock.object_mock[policy_id]) + +def register_policy_object_invalid_response(m, policy_id): + register_policy_any(m, policy_id, 'objects', data_mock.subject_mock[policy_id],'objects_invalid_key') + +def register_policy_action(m, policy_id): + register_policy_any(m, policy_id, 'actions', data_mock.action_mock[policy_id]) + +def register_policy_action_invalid_response(m, policy_id): + register_policy_any(m, policy_id, 'actions', data_mock.subject_mock[policy_id],'actions_invalid_key') + +def register_policy_subject_assignment_list(m, policy_id): + register_policy_any(m, policy_id, 'subject_assignments', data_mock.subject_assignment_mock) + +def register_policy_object_assignment_list(m, policy_id): + register_policy_any(m, policy_id, 'object_assignments', data_mock.object_assignment_mock) + + +def register_policy_action_assignment_list(m, policy_id): + register_policy_any(m, policy_id, 'action_assignments', data_mock.action_assignment_mock) + +def register_policy_subject_assignment(m, policy_id, perimeter_id): + m.register_uri( + 'GET', 'http://{}:{}/{}/{}/subject_assignments/{}'.format(comp_util.CONF['components']['manager']['hostname'], + comp_util.CONF['components']['manager']['port'], + 'policies', + policy_id, + perimeter_id), + json={'subject_assignments': data_mock.subject_assignment_mock} + ) + +def register_policy_object_assignment(m, policy_id, perimeter_id): + m.register_uri( + 'GET', 'http://{}:{}/{}/{}/object_assignments/{}'.format(comp_util.CONF['components']['manager']['hostname'], + comp_util.CONF['components']['manager']['port'], + 'policies', + policy_id, + perimeter_id), + json={'object_assignments': data_mock.object_assignment_mock} + ) + +def register_policy_action_assignment(m, policy_id, perimeter_id): + m.register_uri( + 'GET', 'http://{}:{}/{}/{}/action_assignments/{}'.format(comp_util.CONF['components']['manager']['hostname'], + comp_util.CONF['components']['manager']['port'], + 'policies', + policy_id, + perimeter_id), + json={'action_assignments': data_mock.action_assignment_mock} + ) + +def register_rules(m, policy_id): + register_policy_any(m, policy_id, 'rules', data_mock.rules_mock) + +# def register_pods(m): +# m.register_uri( +# 'GET', 'http://{}:{}/pods'.format(comp_util.CONF['components']['orchestrator']['hostname'], +# comp_util.CONF['components']['orchestrator']['port']), +# json={'pods': data_mock.pods_mock} +# ) diff --git a/old/python_moonutilities/tests/unit_python/requirements.txt b/old/python_moonutilities/tests/unit_python/requirements.txt new file mode 100644 index 00000000..b08a2603 --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/requirements.txt @@ -0,0 +1 @@ +requests_mock \ No newline at end of file diff --git a/old/python_moonutilities/tests/unit_python/test_cache.py b/old/python_moonutilities/tests/unit_python/test_cache.py new file mode 100644 index 00000000..bef10a21 --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/test_cache.py @@ -0,0 +1,452 @@ +import pytest +import mock_repo.data as data_mock +import mock_repo.urls as register_urls +import requests_mock + + +def test_authz_request(): + from python_moonutilities import cache + c = cache.Cache() + assert isinstance(c.authz_requests, dict) + + +# tests for get (subject) in cache +# ================================================ +def test_get_subject_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'subject_name' + subject_id = cache_obj.get_subject(data_mock.shared_ids["policy"]["policy_id_1"], name) + assert subject_id is not None + +def test_get_subject_no_policy(): + from python_moonutilities import cache + cache_obj = cache.Cache() + with pytest.raises(Exception) as exception_info: + cache_obj.get_subject(None, "") + assert str(exception_info.value) == '400: Policy Unknown' + +def test_get_subject_invalid_name(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'invalid name' + with pytest.raises(Exception) as exception_info: + cache_obj.get_subject(data_mock.shared_ids["policy"]["policy_id_1"], name) + assert str(exception_info.value) == '400: Subject Unknown' + +def test_get_subject_invalid_response(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'policy_id_invalid_response' + with pytest.raises(Exception) as exception_info: + cache_obj.get_subject(data_mock.shared_ids["policy"]["policy_id_invalid_response"], name) + assert str(exception_info.value) == '400: Subject Unknown' + +# tests for get (object) in cache +# ================================================ +def test_get_object_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'object_name' + object_id = cache_obj.get_object(data_mock.shared_ids["policy"]["policy_id_1"], name) + assert object_id is not None + +def test_get_object_no_policy(): + from python_moonutilities import cache + cache_obj = cache.Cache() + with pytest.raises(Exception) as exception_info: + cache_obj.get_object(None, "") + assert str(exception_info.value) == '400: Policy Unknown' + +def test_get_object_invalid_name(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'invalid name' + with pytest.raises(Exception) as exception_info: + cache_obj.get_object(data_mock.shared_ids["policy"]["policy_id_1"], name) + assert str(exception_info.value) == '400: Object Unknown' + +def test_get_object_invalid_response(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'policy_id_invalid_response' + with pytest.raises(Exception) as exception_info: + cache_obj.get_object(data_mock.shared_ids["policy"]["policy_id_invalid_response"], name) + assert str(exception_info.value) == '400: Object Unknown' + +# tests for get (action) in cache +# ================================================ +def test_get_action_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'action_name' + action_id = cache_obj.get_action(data_mock.shared_ids["policy"]["policy_id_1"], name) + assert action_id is not None + + +def test_get_action_no_policy(): + from python_moonutilities import cache + cache_obj = cache.Cache() + with pytest.raises(Exception) as exception_info: + cache_obj.get_action(None, "") + assert str(exception_info.value) == '400: Policy Unknown' + +def test_get_action_invalid_name(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'invalid name' + with pytest.raises(Exception) as exception_info: + cache_obj.get_action(data_mock.shared_ids["policy"]["policy_id_1"], name) + assert str(exception_info.value) == '400: Action Unknown' + +def test_get_action_invalid_response(): + from python_moonutilities import cache + cache_obj = cache.Cache() + name = 'policy_id_invalid_response' + with pytest.raises(Exception) as exception_info: + cache_obj.get_action(data_mock.shared_ids["policy"]["policy_id_invalid_response"], name) + assert str(exception_info.value) == '400: Action Unknown' + +# ==================================================================================================== + +# tests for get (subject_assignment) in cache +# ================================================================================= + +def test_get_subject_assignment_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + subject_assignments = cache_obj.get_subject_assignments(data_mock.shared_ids["policy"]["policy_id_1"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert subject_assignments is not None + +def test_get_subject_assignment_no_policy(): + from python_moonutilities import cache + cache_obj = cache.Cache() + with pytest.raises(Exception) as exception_info: + cache_obj.get_subject_assignments(None, + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert str(exception_info.value) == '400: Policy Unknown' + + +@requests_mock.Mocker(kw='mock') +def test_get_subject_assignment_invalid_subject_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + + kwargs['mock'].get('http://manager:8082/policies/{}/subject_assignments/{}' + .format(data_mock.shared_ids["subject"]["invalid_subject_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'subject_assignments': data_mock.subject_assignment_mock_invalid_subject_id} + ) + cache_obj = cache.Cache() + subject_assignments = cache_obj.get_subject_assignments(data_mock.shared_ids["subject"]["invalid_subject_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(subject_assignments) == 0 + + +@requests_mock.Mocker(kw='mock') +def test_get_subject_assignment_invalid_category_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + kwargs['mock'].get('http://manager:8082/policies/{}/subject_assignments/{}' + .format(data_mock.shared_ids["subject"]["invalid_category_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'subject_assignments': data_mock.subject_assignment_mock_invalid_category_id} + ) + cache_obj = cache.Cache() + subject_assignments = cache_obj.get_subject_assignments(data_mock.shared_ids["subject"]["invalid_category_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(subject_assignments) == 0 + + +@requests_mock.Mocker(kw='mock') +def test_get_subject_assignment_invalid_assignment_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + kwargs['mock'].get('http://manager:8082/policies/{}/subject_assignments/{}' + .format(data_mock.shared_ids["subject"]["invalid_assignment_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'subject_assignments': data_mock.subject_assignment_mock_invalid_assignment_id} + ) + + cache_obj = cache.Cache() + subject_assignments = cache_obj.get_subject_assignments(data_mock.shared_ids["subject"]["invalid_assignment_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(subject_assignments) == 0 + + +def test_get_subject_assignment_empty_perimeter(): + from python_moonutilities import cache + cache_obj = cache.Cache() + subject_assignments = cache_obj.get_subject_assignments(data_mock.shared_ids["policy"]["policy_id_2"], + None, + data_mock.shared_ids["category"]["category_id_1"]) + assert len(subject_assignments) == 0 + + +def test_get_subject_assignment_invalid_category_failure(): + from python_moonutilities import cache + cache_obj = cache.Cache() + subject_assignments = cache_obj.get_subject_assignments(data_mock.shared_ids["policy"]["policy_id_1"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["invalid_category_id_1"]) + assert len(subject_assignments) == 0 + +# tests for get (object_assignment) in cache +# ========================================== +def test_get_object_assignment_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + object_assignments = cache_obj.get_object_assignments(data_mock.shared_ids["policy"]["policy_id_1"], + data_mock.shared_ids["perimeter"]["perimeter_id_2"], + data_mock.shared_ids["category"]["category_id_1"]) + assert object_assignments is not None + + +def test_get_object_assignment_no_policy(): + from python_moonutilities import cache + cache_obj = cache.Cache() + with pytest.raises(Exception) as exception_info: + cache_obj.get_object_assignments(None, data_mock.shared_ids["perimeter"]["perimeter_id_2"], + data_mock.shared_ids["category"]["category_id_1"]) + assert str(exception_info.value) == '400: Policy Unknown' + + +@requests_mock.Mocker(kw='mock') +def test_get_object_assignment_invalid_object_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + + kwargs['mock'].get('http://manager:8082/policies/{}/object_assignments/{}' + .format(data_mock.shared_ids["object"]["invalid_object_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'object_assignments': data_mock.object_assignment_mock_invalid_object_id} + ) + cache_obj = cache.Cache() + object_assignments = cache_obj.get_object_assignments(data_mock.shared_ids["object"]["invalid_object_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(object_assignments) == 0 + + +@requests_mock.Mocker(kw='mock') +def test_get_object_assignment_invalid_category_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + kwargs['mock'].get('http://manager:8082/policies/{}/object_assignments/{}' + .format(data_mock.shared_ids["object"]["invalid_category_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'object_assignments': data_mock.object_assignment_mock_invalid_category_id} + ) + cache_obj = cache.Cache() + object_assignments = cache_obj.get_object_assignments(data_mock.shared_ids["object"]["invalid_category_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(object_assignments) == 0 + + +@requests_mock.Mocker(kw='mock') +def test_get_object_assignment_invalid_assignment_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + kwargs['mock'].get('http://manager:8082/policies/{}/object_assignments/{}' + .format(data_mock.shared_ids["object"]["invalid_assignment_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'object_assignments': data_mock.object_assignment_mock_invalid_assignment_id} + ) + + cache_obj = cache.Cache() + object_assignments = cache_obj.get_object_assignments(data_mock.shared_ids["object"]["invalid_assignment_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(object_assignments) == 0 + +def test_get_object_assignment_none_perimeter(): + from python_moonutilities import cache + cache_obj = cache.Cache() + object_assignments = cache_obj.get_object_assignments(data_mock.shared_ids["policy"]["policy_id_2"], + None, + data_mock.shared_ids["category"]["category_id_1"]) + assert len(object_assignments) == 0 + + +def test_get_object_assignment_invalid_category_failure(): + from python_moonutilities import cache + cache_obj = cache.Cache() + object_assignments = cache_obj.get_object_assignments(data_mock.shared_ids["policy"]["policy_id_1"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["invalid_category_id_1"]) + assert len(object_assignments) == 0 + +# tests for get (action_assignment) in cache +# ========================================== +def test_get_action_assignment_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + action_assignments = cache_obj.get_action_assignments(data_mock.shared_ids["policy"]["policy_id_1"], + data_mock.shared_ids["perimeter"]["perimeter_id_3"], + data_mock.shared_ids["category"]["category_id_1"]) + assert action_assignments is not None + + +def test_get_action_assignment_no_policy(): + from python_moonutilities import cache + cache_obj = cache.Cache() + with pytest.raises(Exception) as exception_info: + cache_obj.get_action_assignments(None, data_mock.shared_ids["perimeter"]["perimeter_id_2"], + data_mock.shared_ids["category"]["category_id_1"]) + assert str(exception_info.value) == '400: Policy Unknown' + + +@requests_mock.Mocker(kw='mock') +def test_get_action_assignment_invalid_object_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + + kwargs['mock'].get('http://manager:8082/policies/{}/action_assignments/{}' + .format(data_mock.shared_ids["action"]["invalid_action_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'action_assignments': data_mock.action_assignment_mock_invalid_action_id} + ) + cache_obj = cache.Cache() + action_assignments = cache_obj.get_action_assignments(data_mock.shared_ids["action"]["invalid_action_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(action_assignments) == 0 + + +@requests_mock.Mocker(kw='mock') +def test_get_action_assignment_invalid_category_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + kwargs['mock'].get('http://manager:8082/policies/{}/action_assignments/{}' + .format(data_mock.shared_ids["action"]["invalid_category_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'action_assignments': data_mock.action_assignment_mock_invalid_category_id} + ) + cache_obj = cache.Cache() + action_assignments = cache_obj.get_action_assignments(data_mock.shared_ids["action"]["invalid_category_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(action_assignments) == 0 + + +@requests_mock.Mocker(kw='mock') +def test_get_action_assignment_invalid_assignment_id(**kwargs): + from python_moonutilities import cache + + register_urls.register_components(kwargs['mock']) + kwargs['mock'].get('http://manager:8082/policies/{}/action_assignments/{}' + .format(data_mock.shared_ids["action"]["invalid_assignment_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"]), + json={'action_assignments': data_mock.action_assignment_mock_invalid_assignment_id} + ) + + cache_obj = cache.Cache() + action_assignments = cache_obj.get_action_assignments(data_mock.shared_ids["action"]["invalid_assignment_id"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["category_id_1"]) + assert len(action_assignments) == 0 + +def test_get_action_assignment_none_perimeter(): + from python_moonutilities import cache + cache_obj = cache.Cache() + action_assignments = cache_obj.get_action_assignments(data_mock.shared_ids["policy"]["policy_id_2"], + None, + data_mock.shared_ids["category"]["category_id_1"]) + assert len(action_assignments) == 0 + + +def test_get_action_assignment_invalid_category_failure(): + from python_moonutilities import cache + cache_obj = cache.Cache() + action_assignments = cache_obj.get_action_assignments(data_mock.shared_ids["policy"]["policy_id_1"], + data_mock.shared_ids["perimeter"]["perimeter_id_1"], + data_mock.shared_ids["category"]["invalid_category_id_1"]) + assert len(action_assignments) == 0 + + +# ==================================================================================================== + +# tests for helper function in cache +# ================================== +def test_get_policy_from_meta_rules_success(): + from python_moonutilities import cache + cache_obj = cache.Cache() + policy_id = cache_obj.get_policy_from_meta_rules(data_mock.shared_ids["meta_rule"]["meta_rule_id_1"]) + assert policy_id is not None + +''' tests for containers function , security pipline in cache which not used for now + need to mock pdp object, /pods correctly +''' + +# def test_get_policy_from_meta_rules_failure(): +# from python_moonutilities import cache +# cache_obj = cache.Cache() +# meta_rule_id = 'meta_rule_id3' +# policy_id = cache_obj.get_policy_from_meta_rules(meta_rule_id) +# assert policy_id is None + +# def test_get_pdp_from_keystone_project_success(): +# from python_moonutilities import cache +# cache_obj = cache.Cache() +# keystone_project_id = 'keystone_project_id1' +# pdp_key = cache_obj.get_pdp_from_keystone_project(keystone_project_id) +# assert pdp_key is not None +# +# +# def test_get_pdp_from_keystone_project_failure(): +# from python_moonutilities import cache +# cache_obj = cache.Cache() +# keystone_project_id = 'keystone_project_id2' +# pdp_key = cache_obj.get_pdp_from_keystone_project(keystone_project_id) +# assert pdp_key is None +# +# +# def test_get_keystone_project_id_from_policy_id_success(): +# from python_moonutilities import cache +# cache_obj = cache.Cache() +# keystone_project_id = cache_obj.get_keystone_project_id_from_policy_id( +# data_mock.shared_ids["policy"]["policy_id_1"]) +# assert keystone_project_id is not None +# +# +# def test_get_keystone_project_id_from_policy_id_failure(): +# from python_moonutilities import cache +# cache_obj = cache.Cache() +# policy_id = 'policy_id_3' +# keystone_project_id = cache_obj.get_keystone_project_id_from_policy_id(policy_id) +# assert keystone_project_id is None + + +# def test_get_containers_from_keystone_project_id_success(): +# from python_moonutilities import cache +# cache_obj = cache.Cache() +# keystone_project_id = 1 +# meta_rule_id = 'meta_rule_id1' +# container_id, container_value = cache_obj.get_containers_from_keystone_project_id(keystone_project_id, meta_rule_id) +# assert container_id, container_value is not None + + +def test_cache_manager(): + from python_moonutilities import cache + cache_obj = cache.Cache() +# assert cache_obj.pdp is not None + assert cache_obj.meta_rules is not None + assert len(cache_obj.meta_rules) == 2 + assert cache_obj.policies is not None + assert len(cache_obj.policies) == 1 + assert cache_obj.models is not None diff --git a/old/python_moonutilities/tests/unit_python/test_configuration.py b/old/python_moonutilities/tests/unit_python/test_configuration.py new file mode 100644 index 00000000..d5d83f7a --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/test_configuration.py @@ -0,0 +1,166 @@ +import mock_repo.components_utilities as comp_util +import pytest +import requests_mock + + +def test_get_configuration_success(): + from python_moonutilities import configuration + assert configuration.get_configuration("components/port_start")["components/port_start"] == comp_util.CONF["components"]["port_start"] + + +@requests_mock.Mocker(kw='mock') +def test_get_configuration_mutliple_list_success(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components/port_start', + json=[ + {'Key': 'port_start', 'Value': comp_util.get_b64_conf("components/port_start")}, + {'Key': 'port_start', 'Value': comp_util.get_b64_conf("components/port_start")} + ] + ) + + assert len(configuration.get_configuration("components/port_start")) == 2 + + +@requests_mock.Mocker(kw='mock') +def test_get_configuration_mutliple_list_failure(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components/port_start', + json=[ + {'Key': 'port_start', 'Value': comp_util.get_b64_conf("components/port_start")}, + {'invalidKey': 'port_start', 'Value': comp_util.get_b64_conf("components/port_start")} + ] + ) + with pytest.raises(Exception) as exception_info: + configuration.get_configuration("components/port_start") + assert str(exception_info.value) == '500: Consul Content error' + + +@requests_mock.Mocker(kw='mock') +def test_get_configuration_not_found(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components/port_start_wrong', json=[ + ], status_code=500) + with pytest.raises(Exception) as exception_info: + configuration.get_configuration("components/port_start_wrong") + assert str(exception_info.value) == '500: Consul error' + + +@requests_mock.Mocker(kw='mock') +def test_get_configuration_invalid_response(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components/port_start', json=[ + {"port_start":'port_start', 'Value': comp_util.get_b64_conf("components/port_start")} + ]) + with pytest.raises(Exception) as exception_info: + configuration.get_configuration("components/port_start") + assert str(exception_info.value) == '500: Consul Content error' + + +################################ increment_port #################################### +@requests_mock.Mocker(kw='mock') +def test_put_increment_port_invalidkey_failure(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components/port_start', json=[ + {'Key': 'invalidkey', 'Value': comp_util.get_b64_conf("components/port_start")} + ], status_code=200) + with pytest.raises(Exception) as exception_info: + configuration.increment_port() + assert str(exception_info.value) == '500: Consul Content error' + + +@requests_mock.Mocker(kw='mock') +def test_put_increment_port_failure(**kwargs): + from python_moonutilities import configuration + kwargs['mock'].put('http://consul:8500/v1/kv/components/port_start', json=[], status_code=400) + kwargs['mock'].get('http://consul:8500/v1/kv/components/port_start', json=[ + {'Key': 'port_start', 'Value': comp_util.get_b64_conf("components/port_start")} + ], status_code=200) + with pytest.raises(Exception) as exception_info: + configuration.increment_port() + assert str(exception_info.value) == '500: Consul Content error' + + +def test_increment_port_success(): + from python_moonutilities import configuration + cur_port = comp_util.CONF["components"]["port_start"] + incremented_port = configuration.increment_port() + assert incremented_port == cur_port + 1 + + +################################ plugin #################################### +def test_get_plugins_success(): + from python_moonutilities import configuration + plugin = configuration.get_plugins() + assert plugin is not None + +def test_get_plugins_failure(no_requests): + from python_moonutilities import configuration + no_requests.register_uri( + 'GET', 'http://consul:8500/v1/kv/components/pipeline', + json=[{'Key': 'components/pipeline', 'Value': 'eyJjb250YWluZXIiOiAid3Vrb25nc3VuL21vb25fYXV0aHo6djQuMyIsICJwb3J0IjogODA4MX0='}] + ) + with pytest.raises(Exception) as exception_info: + configuration.get_plugins() + assert str(exception_info.value) == '500: Consul Content error' +################################ component #################################### +def test_get_components(): + from python_moonutilities import configuration + assert isinstance(configuration.get_components(), dict) + + +@requests_mock.Mocker(kw='mock') +def test_get_components_mutliple_list_success(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components?recurse=true', + json=[ + {'Key': 'components/c1', 'Value': 'eyJjb250YWluZXIiOiAid3Vrb25nc3VuL21vb25fYXV0aHo6djQuMyIsICJwb3J0IjogODA4MX0='}, + {'Key': 'components/c2', 'Value': 'eyJjb250YWluZXIiOiAid3Vrb25nc3VuL21vb25fYXV0aHo6djQuMyIsICJwb3J0IjogODA4MX0='} + ] + ) + + res = configuration.get_components() + assert bool(res) + + +@requests_mock.Mocker(kw='mock') +def test_get_components_mutliple_list_failure(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components?recurse=true', + json=[ + {'Key': 'components/c1', 'Value': "eyJjb250YWluZXIiOiAid3Vrb25"}, + {'invalidKey': 'components/c2', 'Value': "eyJjb250YWluZXIiOiAid3Vrb25"} + ] + ) + with pytest.raises(Exception) as exception_info: + configuration.get_components() + assert str(exception_info.value) == '500: Consul Content error' + + +@requests_mock.Mocker(kw='mock') +def test_get_components_not_found(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components?recurse=true', json=[ + ], status_code=500) + with pytest.raises(Exception) as exception_info: + configuration.get_components() + assert str(exception_info.value) == '400: Consul error' + + +@requests_mock.Mocker(kw='mock') +def test_get_components_invalid_response(**kwargs): + from python_moonutilities import configuration + + kwargs['mock'].get('http://consul:8500/v1/kv/components?recurse=true', json=[ + {"invalidKey":'invalid', 'Value': "jb250"} + ]) + with pytest.raises(Exception) as exception_info: + configuration.get_components() + assert str(exception_info.value) == '500: Consul Content error' diff --git a/old/python_moonutilities/tests/unit_python/test_validated_input.py b/old/python_moonutilities/tests/unit_python/test_validated_input.py new file mode 100644 index 00000000..723bc8ba --- /dev/null +++ b/old/python_moonutilities/tests/unit_python/test_validated_input.py @@ -0,0 +1,154 @@ +# 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 pytest + + +def test_valid_string(): + from python_moonutilities.security_functions import validate_data + validate_data("CorrectString") + validate_data("Correct String") + validate_data("Correct String!") + validate_data("Correct String@") + validate_data(None) + validate_data(True) + + +def test_invalid_string(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data("NotcorrectString") + + assert str(exception_info.value) == 'Forbidden characters in string' + + +def test_none_value(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(object) + + assert 'Value is Not String or Container or Dictionary' in str(exception_info.value) + + +def test_numeric_value(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(1) + assert 'Value is Not String or Container or Dictionary' in str(exception_info.value) + + with pytest.raises(Exception) as exception_info: + validate_data(1.23) + assert 'Value is Not String or Container or Dictionary' in str(exception_info.value) + + +def test_correct_list_one_element(): + from python_moonutilities.security_functions import validate_data + validate_data(["test_1", "test_2", "test_3"]) + + +def test_correct_list_multiple_element(): + from python_moonutilities.security_functions import validate_data + validate_data(["test"]) + + +def test_correct_nested_list(): + from python_moonutilities.security_functions import validate_data + validate_data([["test_1", "test_2"], [["test_3"], ["test_4"]], ["test_5", "test_6"], ["test_7"]]) + + +def test_incorrect_string_inside_list(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(["test_1", ["test_2", "forbiddencharacter"]]) + + assert str(exception_info.value) == 'Forbidden characters in string' + + +def test_correct_tuples(): + from python_moonutilities.security_functions import validate_data + validate_data(("test_1", "test_2")) + + +def test_correct_tuple_of_tuple(): + from python_moonutilities.security_functions import validate_data + validate_data(("test_1", ("test_2", "test_3"), (("test_4", "test_5"), ("test_6", "test_7")))) + + +def test_incorrect_string_within_tuple(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data(("test_1", "forbiddencharacter")) + + assert str(exception_info.value) == 'Forbidden characters in string' + + +def test_correct_dictionary(): + from python_moonutilities.security_functions import validate_data + validate_data({"test_1": "test_2"}) + + +def test_incorrect_string_within_dictionary(): + from python_moonutilities.security_functions import validate_data + with pytest.raises(Exception) as exception_info: + validate_data({"test_1": "forbiddencharacter"}) + + assert str(exception_info.value) == 'Forbidden characters in string' + + +def test_correct_function_pass(): + from python_moonutilities.security_functions import validate_input + + @validate_input() + def temp_function(string, list, tuple): + if string != "teststring": + raise ValueError("values which passed incorrect") + + temp_function("teststring", ["teststring", ["teststring"]], ("teststring", ("teststring", ))) + + +def test_incorrect_validating_function_with_kwargs(): + from python_moonutilities.security_functions import validate_input + + @validate_input(kwargs_state=[True,True]) + def temp_function(string, list, tuple): + if string != "teststring": + raise ValueError("values which passed incorrect") + + with pytest.raises(Exception) as exception_info: + temp_function("teststring", list=["teststring", ["teststring"]],tuple=("teststring", ("teststring", ))) + + assert str(exception_info.value) == 'Forbidden characters in string' + + +def test_incorrect_validating_function(): + from python_moonutilities.security_functions import validate_input + + @validate_input() + def temp_function(string, list, dictionary): + if string != "teststring": + raise ValueError("values which passed incorrect") + + with pytest.raises(Exception) as exception_info: + temp_function("teststring", ["teststring", ["teststring"]], {"teststring": ("teststring", )}) + + assert str(exception_info.value) == 'Forbidden characters in string' + + +def test_incorrect_validating_class_function(): + from python_moonutilities.security_functions import validate_input + + class Testclass: + @validate_input() + def temp_function(self, string, list, dictionary): + if string != "teststring": + raise ValueError("values which passed incorrect") + + e = Testclass() + + with pytest.raises(Exception) as exception_info: + e.temp_function("teststring", ["teststring", ["teststring"]], {"teststring": ("teststring", )}) + + assert str(exception_info.value) == 'Forbidden characters in string' -- cgit 1.2.3-korg