|
| 1 | +# Copyright The OpenTelemetry Authors |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import re |
| 16 | +import unittest |
| 17 | +from http import HTTPStatus |
| 18 | +from http.server import BaseHTTPRequestHandler, HTTPServer |
| 19 | +from threading import Thread |
| 20 | + |
| 21 | + |
| 22 | +class HttpTestBase(unittest.TestCase): |
| 23 | + DEFAULT_RESPONSE = b"Hello!" |
| 24 | + |
| 25 | + class Handler(BaseHTTPRequestHandler): |
| 26 | + protocol_version = "HTTP/1.1" # Support keep-alive. |
| 27 | + # timeout = 3 # No timeout -- if shutdown hangs, make sure to close your connection |
| 28 | + |
| 29 | + STATUS_RE = re.compile(r"/status/(\d+)") |
| 30 | + |
| 31 | + def do_GET(self): # pylint:disable=invalid-name |
| 32 | + status_match = self.STATUS_RE.fullmatch(self.path) |
| 33 | + status = 200 |
| 34 | + if status_match: |
| 35 | + status = int(status_match.group(1)) |
| 36 | + if status == 200: |
| 37 | + body = HttpTestBase.DEFAULT_RESPONSE |
| 38 | + self.send_response(HTTPStatus.OK) |
| 39 | + self.send_header("Content-Length", str(len(body))) |
| 40 | + self.end_headers() |
| 41 | + self.wfile.write(body) |
| 42 | + else: |
| 43 | + self.send_error(status) |
| 44 | + |
| 45 | + @classmethod |
| 46 | + def create_server(cls): |
| 47 | + server_address = ("127.0.0.1", 0) # Only bind to localhost. |
| 48 | + return HTTPServer(server_address, cls.Handler) |
| 49 | + |
| 50 | + @classmethod |
| 51 | + def run_server(cls): |
| 52 | + httpd = cls.create_server() |
| 53 | + worker = Thread( |
| 54 | + target=httpd.serve_forever, daemon=True, name="Test server worker" |
| 55 | + ) |
| 56 | + worker.start() |
| 57 | + return worker, httpd |
| 58 | + |
| 59 | + @classmethod |
| 60 | + def setUpClass(cls): |
| 61 | + super().setUpClass() |
| 62 | + cls.server_thread, cls.server = cls.run_server() |
| 63 | + |
| 64 | + @classmethod |
| 65 | + def tearDownClass(cls): |
| 66 | + cls.server.shutdown() |
| 67 | + cls.server_thread.join() |
| 68 | + super().tearDownClass() |
0 commit comments