blob: 12fd7763fcbbc7501a0c2567821d2fadf9fc842f [file] [log] [blame]
koblosz2ac270a2018-10-23 07:32:30 +02001# ============LICENSE_START=======================================================
2# INTEGRATION CSIT
3# ================================================================================
4# Copyright (C) 2018 Nokia Intellectual Property. All rights reserved.
5# ================================================================================
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17# ============LICENSE_END=========================================================
18
19import json
adam6142bef2018-10-01 10:34:19 +020020import logging
koblosz2ac270a2018-10-23 07:32:30 +020021from functools import partial
22from sys import argv
adam6142bef2018-10-01 10:34:19 +020023from http.server import BaseHTTPRequestHandler, HTTPServer
24
25DEFAULT_PORT = 8443
26
27
28class SOHandler(BaseHTTPRequestHandler):
michal.banka5d7b0662019-04-09 13:29:37 +020029 def __init__(self, expected_requests, expected_responses, requests, responses, *args, **kwargs):
adam6142bef2018-10-01 10:34:19 +020030
koblosz2ac270a2018-10-23 07:32:30 +020031 self._expected_requests = expected_requests
32 self._expected_responses = expected_responses
michal.banka5d7b0662019-04-09 13:29:37 +020033 self._requests = requests["requests"]
34 self._responses = responses["responses"]
35 self._known_endpoints = self._get_known_endpoints()
koblosz2ac270a2018-10-23 07:32:30 +020036 super().__init__(*args, **kwargs)
adam6142bef2018-10-01 10:34:19 +020037
38 def do_POST(self):
koblosz2ac270a2018-10-23 07:32:30 +020039 logging.info(
40 'POST called. Expected POST REQUEST: ' + json.dumps(
41 self._expected_requests["post"]) + '\nExpected POST response: ' +
42 json.dumps(self._expected_responses["post"]))
adam6142bef2018-10-01 10:34:19 +020043 self.send_response(200)
44 self._set_headers()
45
koblosz2ac270a2018-10-23 07:32:30 +020046 self.wfile.write(json.dumps(self._expected_responses["post"]).encode("utf-8"))
adam6142bef2018-10-01 10:34:19 +020047 return
48
49 def do_GET(self):
michal.banka5d7b0662019-04-09 13:29:37 +020050 print(self._known_endpoints)
51 if self._does_path_exist_as_endpoint():
52 expected_response = self._get_response_by_path()
53 if expected_response:
54 self.send_response(expected_response["responseCode"])
55 self._set_headers()
56 self.wfile.write(json.dumps(expected_response["body"]).encode("utf-8"))
57 else:
58 response_body = "{\"message:\" \"no response for endpoint\"}"
59 self.send_response(400)
60 self._set_headers()
61 self.wfile.write(json.dumps(response_body).encode("utf-8"))
62 else:
63 logging.info('GET called. Expected GET REQUEST: '
64 + json.dumps(self._expected_requests["get"])
65 + '\nExpected GET response: '
66 + json.dumps(self._expected_responses["get"]))
67 self.send_response(200)
68 self._set_headers()
69 self.wfile.write(json.dumps(self._expected_responses["get"]).encode("utf-8"))
koblosz2ac270a2018-10-23 07:32:30 +020070
71 def do_PUT(self):
72 request_body_json = self._get_request_body()
73 if request_body_json is not None:
74 self._apply_expected_data(request_body_json)
75 logging.info("EXPECTED RESPONSES: " + str(self._expected_responses))
76 logging.info("EXPECTED REQUESTS: " + str(self._expected_requests))
77 response_status = 200
78 else:
79 response_status = 400
80 self.send_response(response_status)
81 self._set_headers()
82
83 def _get_request_body(self):
84 content_len = int(self.headers['Content-Length'], 0)
85 parsed_req_body = None
86 if content_len > 0:
87 body = self.rfile.read(content_len)
88 body_decoded = body.decode('utf8')
89 logging.info("BODY: %s type: %s body decoded: %s type: %s", str(body), type(body), str(body_decoded),
90 type(body_decoded))
91 parsed_req_body = json.loads(body_decoded)
92 return parsed_req_body
93
94 def _apply_expected_data(self, request_body_json):
95 if self.path == '/setResponse':
96 logging.info("IN PUT /setResponse: " + str(request_body_json))
koblosz2ac270a2018-10-23 07:32:30 +020097 self._expected_responses.update(request_body_json)
koblosz2ac270a2018-10-23 07:32:30 +020098 elif self.path == '/setRequest':
99 logging.info("IN PUT /setRequest: " + str(request_body_json))
100 self._expected_requests.update(request_body_json)
adam6142bef2018-10-01 10:34:19 +0200101
102 def _set_headers(self):
103 self.send_header('Content-Type', 'application/json')
104 self.end_headers()
105
michal.banka5d7b0662019-04-09 13:29:37 +0200106 def _get_response_by_path(self):
107 for response in self._responses:
108 if response["path"] == self.path:
109 return response
110
111 def _does_path_exist_as_endpoint(self):
112 does_exist = False
113 for ep in self._known_endpoints:
114 if ep == self.path:
115 does_exist = True
116 break
117 return does_exist
118
119 def _create_path_from_request(self, request):
120 base_uri = request["path"]
121 query_params = request["queryParams"]
122 return base_uri + self._get_params_uri(query_params)
123
124 def _get_known_endpoints(self):
125 endpoints = []
126 for request in self._requests:
127 endpoints.append(self._create_path_from_request(request))
128 return endpoints
129
130 @staticmethod
131 def _get_params_uri(query_params):
132 params_uri = "?"
133 for parameter in query_params:
134 params_uri += parameter + '=' + query_params.get(parameter, '') + '&'
135 return params_uri[:-1]
136
koblosz2ac270a2018-10-23 07:32:30 +0200137
138class JsonFileToDictReader(object):
139
adam6142bef2018-10-01 10:34:19 +0200140 @staticmethod
koblosz2ac270a2018-10-23 07:32:30 +0200141 def read_expected_test_data(expected_responses_filename):
142 with open(expected_responses_filename, 'r') as file:
143 return json.load(file)
144
145
146def init_so_simulator():
michal.banka5d7b0662019-04-09 13:29:37 +0200147 requests = JsonFileToDictReader.read_expected_test_data("test_data_assets/requests.json")
148 responses = JsonFileToDictReader.read_expected_test_data("test_data_assets/responses.json")
149
koblosz2ac270a2018-10-23 07:32:30 +0200150 expected_so_requests = JsonFileToDictReader.read_expected_test_data(argv[1])
151 expected_so_responses = JsonFileToDictReader.read_expected_test_data(argv[2])
Ittay Sternf8af5bf2019-03-27 18:21:29 +0200152 logging.basicConfig(level=logging.INFO)
michal.banka5d7b0662019-04-09 13:29:37 +0200153 handler = partial(SOHandler, expected_so_requests, expected_so_responses, requests, responses)
koblosz2ac270a2018-10-23 07:32:30 +0200154 handler.protocol_version = "HTTP/1.0"
155 httpd = HTTPServer(('', DEFAULT_PORT), handler)
156 logging.info("serving on: " + str(httpd.socket.getsockname()))
157 httpd.serve_forever()
adam6142bef2018-10-01 10:34:19 +0200158
159
160if __name__ == '__main__':
koblosz2ac270a2018-10-23 07:32:30 +0200161 init_so_simulator()