147ba4385cc52a76cdf3acd4c913b1e02578472d
[dcaegen2/platform/plugins.git] / clamp-policy / tests / mock_setup.py
1 # ================================================================================
2 # Copyright (c) 2019 Wipro Limited Intellectual Property. All rights reserved.
3 # ================================================================================
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 #      http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 # ============LICENSE_END=========================================================
16 #
17
18 """unit tests for tasks in clamppolicyplugin"""
19
20 import json
21 import logging
22 from datetime import datetime, timedelta
23
24 from tests.mock_cloudify_ctx import MockCloudifyContextFull
25
26 LOG_FILE = 'logs/test_clamppolicyplugin.log'
27 POLICY_MODEL_ID = 'policy_model_id'
28 POLICY_ID = 'policy_id'
29 POLICY_VERSION = "policyVersion"
30 POLICY_NAME = "policyName"
31 POLICY_BODY = 'policy_body'
32 POLICY_CONFIG = 'config'
33 CONFIG_NAME = "ConfigName"
34 MONKEYED_POLICY_ID = 'monkeyed.Config_peach'
35
36 RUN_TS = datetime.utcnow()
37
38
39 class MonkeyedLogHandler(object):
40     """keep the shared logger handler here"""
41     _log_handler = None
42
43     @staticmethod
44     def add_handler_to(logger):
45         """adds the local handler to the logger"""
46         if not MonkeyedLogHandler._log_handler:
47             MonkeyedLogHandler._log_handler = logging.FileHandler(LOG_FILE)
48             MonkeyedLogHandler._log_handler.setLevel(logging.DEBUG)
49             formatter = logging.Formatter(
50                 fmt='%(asctime)s.%(msecs)03d %(levelname)+8s ' +
51                     '%(threadName)s %(name)s.%(funcName)s: %(message)s',
52                 datefmt='%Y%m%d_%H%M%S')
53             MonkeyedLogHandler._log_handler.setFormatter(formatter)
54         logger.addHandler(MonkeyedLogHandler._log_handler)
55
56
57 class MonkeyedPolicyBody(object):
58     """policy body that policy-engine returns"""
59     @staticmethod
60     def create_policy_body(policy_id, policy_version=1):
61         """returns a fake policy-body"""
62         prev_ver = policy_version - 1
63         timestamp = RUN_TS + timedelta(hours=prev_ver)
64
65         prev_ver = str(prev_ver)
66         this_ver = str(policy_version)
67         config = {
68             "policy_updated_from_ver": prev_ver,
69             "policy_updated_to_ver": this_ver,
70             "policy_hello": "world!",
71             "policy_updated_ts": timestamp.isoformat()[:-3] + 'Z',
72             "updated_policy_id": policy_id
73         }
74         return {
75             "policyConfigMessage": "Config Retrieved! ",
76             "policyConfigStatus": "CONFIG_RETRIEVED",
77             "type": "JSON",
78             POLICY_NAME: "{0}.{1}.xml".format(policy_id, this_ver),
79             POLICY_VERSION: this_ver,
80             POLICY_CONFIG: config,
81             "matchingConditions": {
82                 "ONAPName": "DCAE",
83                 CONFIG_NAME: "VigneshK_config_name"
84             },
85             "responseAttributes": {},
86             "property": None
87         }
88
89     @staticmethod
90     def create_policy(policy_id, policy_version=1):
91         """returns the whole policy object for policy_id and policy_version"""
92         return {
93             POLICY_ID: policy_id,
94             POLICY_BODY: MonkeyedPolicyBody.create_policy_body(policy_id, policy_version)
95         }
96
97     @staticmethod
98     def is_the_same_dict(policy_body_1, policy_body_2):
99         """check whether both policy_body objects are the same"""
100         if not isinstance(policy_body_1, dict) or not isinstance(policy_body_2, dict):
101             return False
102         for key in policy_body_1.keys():
103             if key not in policy_body_2:
104                 return False
105
106             val_1 = policy_body_1[key]
107             val_2 = policy_body_2[key]
108             if isinstance(val_1, dict) \
109             and not MonkeyedPolicyBody.is_the_same_dict(val_1, val_2):
110                 return False
111             if (val_1 is None and val_2 is not None) \
112             or (val_1 is not None and val_2 is None) \
113             or (val_1 != val_2):
114                 return False
115         return True
116
117
118 class MonkeyedResponse(object):
119     """Monkey response"""
120     def __init__(self, full_path, headers=None, resp_json=None):
121         self.full_path = full_path
122         self.status_code = 200
123         self.headers = headers or {}
124         self.resp_json = resp_json
125         self.text = json.dumps(resp_json or {})
126
127     def json(self):
128         """returns json of response"""
129         return self.resp_json
130
131     def raise_for_status(self):
132         """always happy"""
133         pass
134
135
136 class MonkeyedNode(object):
137     """node in cloudify"""
138     BLUEPRINT_ID = 'test_clamp_policy_bp_id'
139     DEPLOYMENT_ID = 'test_clamp_policy_dpl_id'
140     EXECUTION_ID = 'test_clamp_policy_exe_id'
141
142     def __init__(self, node_id, node_name, node_type, properties, relationships=None):
143         self.node_id = node_id
144         self.node_name = node_name
145         self.ctx = MockCloudifyContextFull(
146             node_id=self.node_id,
147             node_name=self.node_name,
148             node_type=node_type,
149             blueprint_id=MonkeyedNode.BLUEPRINT_ID,
150             deployment_id=MonkeyedNode.DEPLOYMENT_ID,
151             execution_id=MonkeyedNode.EXECUTION_ID,
152             properties=properties,
153             relationships=relationships
154         )
155         MonkeyedLogHandler.add_handler_to(self.ctx.logger)