|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import re |
| 4 | +import threading |
| 5 | +from http import HTTPStatus |
| 6 | +from http.server import HTTPServer, SimpleHTTPRequestHandler |
| 7 | +from typing import Type |
| 8 | +from unittest import TestCase |
| 9 | +from urllib.parse import urlparse, parse_qs |
| 10 | + |
| 11 | + |
| 12 | +class MockHandler(SimpleHTTPRequestHandler): |
| 13 | + protocol_version = "HTTP/1.1" |
| 14 | + default_request_version = "HTTP/1.1" |
| 15 | + logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + pattern_for_language = re.compile("python/(\\S+)", re.IGNORECASE) |
| 18 | + pattern_for_package_identifier = re.compile("slackclient/(\\S+)") |
| 19 | + |
| 20 | + def is_valid_user_agent(self): |
| 21 | + user_agent = self.headers["User-Agent"] |
| 22 | + return self.pattern_for_language.search( |
| 23 | + user_agent |
| 24 | + ) and self.pattern_for_package_identifier.search(user_agent) |
| 25 | + |
| 26 | + def is_valid_token(self): |
| 27 | + if self.path.startswith("oauth"): |
| 28 | + return True |
| 29 | + return "Authorization" in self.headers and ( |
| 30 | + str(self.headers["Authorization"]).startswith("Bearer xoxb-") |
| 31 | + or str(self.headers["Authorization"]).startswith("Bearer xapp-") |
| 32 | + ) |
| 33 | + |
| 34 | + def set_common_headers(self): |
| 35 | + self.send_header("content-type", "application/json;charset=utf-8") |
| 36 | + self.send_header("connection", "close") |
| 37 | + self.end_headers() |
| 38 | + |
| 39 | + invalid_auth = { |
| 40 | + "ok": False, |
| 41 | + "error": "invalid_auth", |
| 42 | + } |
| 43 | + |
| 44 | + not_found = { |
| 45 | + "ok": False, |
| 46 | + "error": "test_data_not_found", |
| 47 | + } |
| 48 | + |
| 49 | + def _handle(self): |
| 50 | + try: |
| 51 | + if self.is_valid_token() and self.is_valid_user_agent(): |
| 52 | + parsed_path = urlparse(self.path) |
| 53 | + |
| 54 | + len_header = self.headers.get("Content-Length") or 0 |
| 55 | + content_len = int(len_header) |
| 56 | + post_body = self.rfile.read(content_len) |
| 57 | + request_body = None |
| 58 | + if post_body: |
| 59 | + try: |
| 60 | + post_body = post_body.decode("utf-8") |
| 61 | + if post_body.startswith("{"): |
| 62 | + request_body = json.loads(post_body) |
| 63 | + else: |
| 64 | + request_body = { |
| 65 | + k: v[0] for k, v in parse_qs(post_body).items() |
| 66 | + } |
| 67 | + except UnicodeDecodeError: |
| 68 | + pass |
| 69 | + else: |
| 70 | + if parsed_path and parsed_path.query: |
| 71 | + request_body = { |
| 72 | + k: v[0] for k, v in parse_qs(parsed_path.query).items() |
| 73 | + } |
| 74 | + |
| 75 | + body = {"ok": False, "error": "internal_error"} |
| 76 | + if self.path == "/auth.test": |
| 77 | + body = { |
| 78 | + "ok": True, |
| 79 | + "url": "https://xyz.slack.com/", |
| 80 | + "team": "Testing Workspace", |
| 81 | + "user": "bot-user", |
| 82 | + "team_id": "T111", |
| 83 | + "user_id": "W11", |
| 84 | + "bot_id": "B111", |
| 85 | + "enterprise_id": "E111", |
| 86 | + "is_enterprise_install": False, |
| 87 | + } |
| 88 | + if self.path == "/apps.connections.open": |
| 89 | + body = { |
| 90 | + "ok": True, |
| 91 | + "url": "ws://localhost:3011/link/?ticket=xxx&app_id=yyy", |
| 92 | + } |
| 93 | + if self.path == "/api.test" and request_body: |
| 94 | + body = {"ok": True, "args": request_body} |
| 95 | + else: |
| 96 | + body = self.invalid_auth |
| 97 | + |
| 98 | + if not body: |
| 99 | + body = self.not_found |
| 100 | + |
| 101 | + self.send_response(HTTPStatus.OK) |
| 102 | + self.set_common_headers() |
| 103 | + self.wfile.write(json.dumps(body).encode("utf-8")) |
| 104 | + self.wfile.close() |
| 105 | + |
| 106 | + except Exception as e: |
| 107 | + self.logger.error(str(e), exc_info=True) |
| 108 | + raise |
| 109 | + |
| 110 | + def do_GET(self): |
| 111 | + self._handle() |
| 112 | + |
| 113 | + def do_POST(self): |
| 114 | + self._handle() |
| 115 | + |
| 116 | + |
| 117 | +class MockServerThread(threading.Thread): |
| 118 | + def __init__( |
| 119 | + self, test: TestCase, handler: Type[SimpleHTTPRequestHandler] = MockHandler |
| 120 | + ): |
| 121 | + threading.Thread.__init__(self) |
| 122 | + self.handler = handler |
| 123 | + self.test = test |
| 124 | + |
| 125 | + def run(self): |
| 126 | + self.server = HTTPServer(("localhost", 8888), self.handler) |
| 127 | + self.test.server_url = "http://localhost:8888" |
| 128 | + self.test.host, self.test.port = self.server.socket.getsockname() |
| 129 | + self.test.server_started.set() # threading.Event() |
| 130 | + |
| 131 | + self.test = None |
| 132 | + try: |
| 133 | + self.server.serve_forever() |
| 134 | + finally: |
| 135 | + self.server.server_close() |
| 136 | + |
| 137 | + def stop(self): |
| 138 | + self.server.shutdown() |
| 139 | + self.join() |
| 140 | + |
| 141 | + |
| 142 | +def setup_mock_web_api_server(test: TestCase): |
| 143 | + test.server_started = threading.Event() |
| 144 | + test.thread = MockServerThread(test) |
| 145 | + test.thread.start() |
| 146 | + |
| 147 | + test.server_started.wait() |
| 148 | + |
| 149 | + |
| 150 | +def cleanup_mock_web_api_server(test: TestCase): |
| 151 | + test.thread.stop() |
| 152 | + |
| 153 | + test.thread = None |
0 commit comments