blob: 4e69afd7aaf70756ea19ce0494942aa6489a77d4 [file] [log] [blame]
Alex Shatova39f4e82018-12-05 15:23:50 -05001# ============LICENSE_START=======================================================
2# Copyright (c) 2018 AT&T 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# ECOMP is a trademark and service mark of AT&T Intellectual Property.
18"""record all the messages going outside policy-handler during testing"""
19
20import copy
21import json
22
23from policyhandler.onap.audit import REQUEST_X_ECOMP_REQUESTID
24from policyhandler.policy_utils import Utils
25
26from .mock_expected import HISTORY_EXPECTED
27from .mock_settings import Settings
28
29RESPONSE = "res"
30
31class _MockHttpRequestInResponse(object):
32 """Mock http request in reponse object"""
33 def __init__(self, method, uri, **kwargs):
34 self.method = method
35 self.uri = uri
36 self.params = copy.deepcopy(kwargs.get("params"))
37 self.req_json = copy.deepcopy(kwargs.get("json"))
38 self.headers = copy.deepcopy(kwargs.get("headers"))
39
40 def to_json(self):
41 """create json of the request"""
42 return {
43 "method": self.method,
44 "uri": self.uri,
45 "params": self.params,
46 "json": self.req_json,
47 "headers": self.headers
48 }
49
50
51class MockHttpResponse(object):
52 """Mock http response based on request"""
53 def __init__(self, method, uri, res_json, **kwargs):
54 """create response based on request"""
55 self.request = _MockHttpRequestInResponse(method, uri, **kwargs)
56
57 self.status_code = kwargs.get("status_code", 200)
58 self.res = copy.deepcopy(res_json)
59 self.text = json.dumps(self.res)
60
61 self._track()
62
63 def json(self):
64 """returns json of response"""
65 return self.res
66
67 def raise_for_status(self):
68 """ignoring"""
69 pass
70
71 def to_json(self):
72 """create json of the message"""
73 return {
74 "request": self.request.to_json(),
75 "status_code": self.status_code,
76 RESPONSE: self.res
77 }
78
79 def _track(self):
80 """append the message to tracker's history"""
81 Tracker.track(self.to_json())
82
83 def __str__(self):
84 """stringify for logging"""
85 return json.dumps(self.to_json(), sort_keys=True)
86
87
88class Tracker(object):
89 """record all the messages going outside policy-handler during testing"""
90 test_name = None
91 messages = []
92
93 @staticmethod
94 def reset(test_name):
95 """remove all the messages from history"""
96 Tracker.test_name = test_name
97 Tracker.messages.clear()
98
99 @staticmethod
100 def track(message):
101 """append the tracked message to the history"""
102 message = copy.deepcopy(message)
103 Tracker.messages.append(message)
104 if Settings.logger:
105 Settings.logger.info("tracked_message: %s", json.dumps(message, sort_keys=True))
106
107 @staticmethod
108 def to_string():
109 """stringify message history for logging"""
110 return json.dumps(Tracker.messages, sort_keys=True)
111
112 @staticmethod
113 def _hide_volatiles(obj):
114 """hides the volatile field values"""
115 if not isinstance(obj, dict):
116 return obj
117
118 for key, value in obj.items():
119 if key in [REQUEST_X_ECOMP_REQUESTID, RESPONSE]:
120 obj[key] = "*"
121 elif isinstance(value, dict):
122 obj[key] = Tracker._hide_volatiles(value)
123
124 return obj
125
126 @staticmethod
127 def validate():
128 """validate that the message history is as expected"""
129 Settings.logger.info("Tracker.validate(%s)", Tracker.test_name)
130 messages = [Tracker._hide_volatiles(copy.deepcopy(message))
131 for message in Tracker.messages]
132 expected = HISTORY_EXPECTED.get(Tracker.test_name, [])
133
134 Settings.logger.info("messages: %s", json.dumps(messages, sort_keys=True))
135 Settings.logger.info("expected: %s", json.dumps(expected, sort_keys=True))
136 assert Utils.are_the_same(messages, expected)
137
138 Settings.logger.info("history valid for Tracker.validate(%s)", Tracker.test_name)