PRH simulators refactor
[integration/csit.git] / tests / dcaegen2 / prh-testcases / resources / simulator / httpServerLib.py
1 import _thread
2 import ssl
3 from http.server import HTTPServer
4
5 def set_response_200_ok(self, payload = None):
6     self.send_response(200)
7     self.send_header('Content-Type', 'application/json')
8     self.end_headers()
9     if payload != None:
10         self.wfile.write(payload)
11
12 def set_response_404_not_found(self):
13     self.send_response(404)
14     self.end_headers()
15
16 def set_response_500_server_error(self):
17     self.send_response(500)
18     self.end_headers()
19
20 def get_payload(self):
21     if self.headers['Content-Length'] == None:
22         raise Exception('Invalid payload, Content-Length not defined')
23
24     content_length = int(self.headers['Content-Length'])
25     return self.rfile.read(content_length)
26
27 def start_http_endpoint(port, handler_class):
28     _thread.start_new_thread(init_http_endpoints, (port, handler_class))
29
30 def start_https_endpoint(port, handler_class, keyfile, certfile, ca_certs):
31     _thread.start_new_thread(init_https_endpoints, (port, handler_class, keyfile, certfile, ca_certs))
32
33 def init_http_endpoints(port, handler_class, server_class=HTTPServer):
34     server = server_class(('', port), handler_class)
35     sa = server.socket.getsockname()
36     print("Serving HTTP on", sa[0], "port", sa[1], "for", handler_class, "...")
37     server.serve_forever()
38
39 def init_https_endpoints(port, handler_class, keyfile, certfile, ca_certs, server_class=HTTPServer):
40     server = server_class(('', port), handler_class)
41     server.socket = ssl.wrap_socket(server.socket, keyfile=keyfile, certfile=certfile,
42                                     ca_certs=ca_certs, server_side=True)
43     sa = server.socket.getsockname()
44     print("Serving HTTPS on", sa[0], "port", sa[1], "for", handler_class, "...")
45     server.serve_forever()