blob: a5fffd5e1cf60033083bf168f843cf9edbf33656 [file] [log] [blame]
Alex Shatova39f4e82018-12-05 15:23:50 -05001# ============LICENSE_START=======================================================
Alex Shatov9a4d3c52019-04-01 11:32:06 -04002# Copyright (c) 2018-2019 AT&T Intellectual Property. All rights reserved.
Alex Shatova39f4e82018-12-05 15:23:50 -05003# ================================================================================
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#
Alex Shatova39f4e82018-12-05 15:23:50 -050017"""record all the messages going outside policy-handler during testing"""
18
19import copy
20import json
21
Alex Shatov9a4d3c52019-04-01 11:32:06 -040022from policyhandler.config import Config
Alex Shatova39f4e82018-12-05 15:23:50 -050023from policyhandler.onap.audit import REQUEST_X_ECOMP_REQUESTID
Alex Shatov9a4d3c52019-04-01 11:32:06 -040024from policyhandler.utils import Utils
Alex Shatova39f4e82018-12-05 15:23:50 -050025
26RESPONSE = "res"
Alex Shatov9a4d3c52019-04-01 11:32:06 -040027PEP_INSTANCE = "ONAPInstance"
28_LOGGER = Utils.get_logger(__file__)
Alex Shatova39f4e82018-12-05 15:23:50 -050029
30class _MockHttpRequestInResponse(object):
31 """Mock http request in reponse object"""
32 def __init__(self, method, uri, **kwargs):
33 self.method = method
34 self.uri = uri
35 self.params = copy.deepcopy(kwargs.get("params"))
36 self.req_json = copy.deepcopy(kwargs.get("json"))
37 self.headers = copy.deepcopy(kwargs.get("headers"))
38
39 def to_json(self):
40 """create json of the request"""
41 return {
42 "method": self.method,
43 "uri": self.uri,
44 "params": self.params,
45 "json": self.req_json,
46 "headers": self.headers
47 }
48
49
50class MockHttpResponse(object):
51 """Mock http response based on request"""
52 def __init__(self, method, uri, res_json, **kwargs):
53 """create response based on request"""
54 self.request = _MockHttpRequestInResponse(method, uri, **kwargs)
55
56 self.status_code = kwargs.get("status_code", 200)
57 self.res = copy.deepcopy(res_json)
58 self.text = json.dumps(self.res)
59
60 self._track()
61
62 def json(self):
63 """returns json of response"""
64 return self.res
65
66 def raise_for_status(self):
67 """ignoring"""
68 pass
69
70 def to_json(self):
71 """create json of the message"""
72 return {
73 "request": self.request.to_json(),
74 "status_code": self.status_code,
75 RESPONSE: self.res
76 }
77
78 def _track(self):
79 """append the message to tracker's history"""
80 Tracker.track(self.to_json())
81
82 def __str__(self):
83 """stringify for logging"""
84 return json.dumps(self.to_json(), sort_keys=True)
85
86
87class Tracker(object):
88 """record all the messages going outside policy-handler during testing"""
89 test_name = None
90 messages = []
Alex Shatov9a4d3c52019-04-01 11:32:06 -040091 test_names = []
92 validated_tests = {}
93 valid_tests = {}
Alex Shatova39f4e82018-12-05 15:23:50 -050094
95 @staticmethod
Alex Shatov9a4d3c52019-04-01 11:32:06 -040096 def reset(test_name=None):
Alex Shatova39f4e82018-12-05 15:23:50 -050097 """remove all the messages from history"""
98 Tracker.test_name = test_name
99 Tracker.messages.clear()
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400100 Tracker.test_names.append(test_name)
Alex Shatova39f4e82018-12-05 15:23:50 -0500101
102 @staticmethod
103 def track(message):
104 """append the tracked message to the history"""
105 message = copy.deepcopy(message)
106 Tracker.messages.append(message)
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400107 if _LOGGER:
108 _LOGGER.info("tracked_message: %s", json.dumps(message, sort_keys=True))
Alex Shatova39f4e82018-12-05 15:23:50 -0500109
110 @staticmethod
111 def to_string():
112 """stringify message history for logging"""
113 return json.dumps(Tracker.messages, sort_keys=True)
114
115 @staticmethod
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400116 def get_status(test_name=None):
117 """get the status of validation"""
118 if Tracker.valid_tests.get(test_name):
119 return "success"
120 if Tracker.validated_tests.get(test_name):
121 return "failed"
122 if test_name in Tracker.test_names:
123 return "covered"
124 return "unknown"
125
126 @staticmethod
127 def log_all_tests():
128 """log the covered and not covered test names"""
129 _LOGGER.info("-"*75)
130 _LOGGER.info("tracked test_names[%s]", len(Tracker.test_names))
131 for idx, test_name in enumerate(Tracker.test_names):
132 _LOGGER.info("%s[%s]: %s", Tracker.get_status(test_name), (idx + 1), test_name)
133
134 _LOGGER.info("not tracked test_names listed in main.mock_expected")
135 from .main.mock_expected import HISTORY_EXPECTED as main_history
136 for test_name in main_history:
137 if test_name not in Tracker.test_names:
138 _LOGGER.info("untracked: %s", test_name)
139
140 _LOGGER.info("not tracked test_names listed in pdp_api_v0.mock_expected")
141 from .pdp_api_v0.mock_expected import HISTORY_EXPECTED as pdp_api_v0_history
142 for test_name in pdp_api_v0_history:
143 if test_name not in Tracker.test_names:
144 _LOGGER.info("untracked: %s", test_name)
145
146 @staticmethod
Alex Shatova39f4e82018-12-05 15:23:50 -0500147 def _hide_volatiles(obj):
148 """hides the volatile field values"""
149 if not isinstance(obj, dict):
150 return obj
151
152 for key, value in obj.items():
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400153 if key in [REQUEST_X_ECOMP_REQUESTID, RESPONSE, PEP_INSTANCE]:
Alex Shatova39f4e82018-12-05 15:23:50 -0500154 obj[key] = "*"
155 elif isinstance(value, dict):
156 obj[key] = Tracker._hide_volatiles(value)
157
158 return obj
159
160 @staticmethod
161 def validate():
162 """validate that the message history is as expected"""
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400163 _LOGGER.info("Tracker.validate(%s)", Tracker.test_name)
Alex Shatova39f4e82018-12-05 15:23:50 -0500164 messages = [Tracker._hide_volatiles(copy.deepcopy(message))
165 for message in Tracker.messages]
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400166 Tracker.validated_tests[Tracker.test_name] = True
Alex Shatova39f4e82018-12-05 15:23:50 -0500167
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400168 if Config.is_pdp_api_default():
169 from .main.mock_expected import HISTORY_EXPECTED as main_history
170 expected = main_history.get(Tracker.test_name, [])
171 else:
172 from .pdp_api_v0.mock_expected import HISTORY_EXPECTED as pdp_api_v0_history
173 expected = pdp_api_v0_history.get(Tracker.test_name, [])
174
175 _LOGGER.info("messages: %s", json.dumps(messages, sort_keys=True))
176 _LOGGER.info("expected: %s", json.dumps(expected, sort_keys=True))
Alex Shatova39f4e82018-12-05 15:23:50 -0500177 assert Utils.are_the_same(messages, expected)
178
Alex Shatov9a4d3c52019-04-01 11:32:06 -0400179 _LOGGER.info("history valid for Tracker.validate(%s)", Tracker.test_name)
180 Tracker.valid_tests[Tracker.test_name] = True