|
| 1 | +import os |
| 2 | +import signal |
| 3 | +import socket |
| 4 | +import subprocess |
| 5 | +import sys |
| 6 | +import time |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +import pytest |
| 10 | +import requests |
| 11 | + |
| 12 | +FD_API_PORT = int(os.getenv("FD_API_PORT", 8188)) |
| 13 | +FD_ENGINE_QUEUE_PORT = int(os.getenv("FD_ENGINE_QUEUE_PORT", 8133)) |
| 14 | +FD_METRICS_PORT = int(os.getenv("FD_METRICS_PORT", 8233)) |
| 15 | +FD_CACHE_QUEUE_PORT = int(os.getenv("FD_CACHE_QUEUE_PORT", 8333)) |
| 16 | +PORTS_TO_CLEAN = [FD_API_PORT, FD_ENGINE_QUEUE_PORT, FD_METRICS_PORT, FD_CACHE_QUEUE_PORT] |
| 17 | + |
| 18 | +current_server_process: Optional[subprocess.Popen] = None |
| 19 | + |
| 20 | + |
| 21 | +def is_port_open(host: str, port: int, timeout=1.0): |
| 22 | + """ |
| 23 | + Check if a TCP port is open on the given host. |
| 24 | + Returns True if connection succeeds, False otherwise. |
| 25 | + """ |
| 26 | + try: |
| 27 | + with socket.create_connection((host, port), timeout): |
| 28 | + return True |
| 29 | + except Exception: |
| 30 | + return False |
| 31 | + |
| 32 | + |
| 33 | +def kill_process_on_port(port: int): |
| 34 | + """ |
| 35 | + Kill processes that are listening on the given port. |
| 36 | + Uses `lsof` to find process ids and sends SIGKILL. |
| 37 | + """ |
| 38 | + try: |
| 39 | + output = subprocess.check_output(f"lsof -i:{port} -t", shell=True).decode().strip() |
| 40 | + current_pid = os.getpid() |
| 41 | + parent_pid = os.getppid() |
| 42 | + for pid in output.splitlines(): |
| 43 | + pid = int(pid) |
| 44 | + if pid in (current_pid, parent_pid): |
| 45 | + print(f"Skip killing current process (pid={pid}) on port {port}") |
| 46 | + continue |
| 47 | + os.kill(pid, signal.SIGKILL) |
| 48 | + print(f"Killed process on port {port}, pid={pid}") |
| 49 | + except subprocess.CalledProcessError: |
| 50 | + pass |
| 51 | + |
| 52 | + |
| 53 | +def clean_ports(): |
| 54 | + """ |
| 55 | + Kill all processes occupying the ports listed in PORTS_TO_CLEAN. |
| 56 | + """ |
| 57 | + for port in PORTS_TO_CLEAN: |
| 58 | + kill_process_on_port(port) |
| 59 | + time.sleep(2) |
| 60 | + |
| 61 | + |
| 62 | +def start_api_server(api_key_cli: Optional[list[str]] = None, api_key_env: Optional[str] = None): |
| 63 | + global current_server_process |
| 64 | + clean_ports() |
| 65 | + |
| 66 | + env = os.environ.copy() |
| 67 | + if api_key_env is not None: |
| 68 | + env["FD_API_KEY"] = api_key_env |
| 69 | + else: |
| 70 | + env.pop("FD_API_KEY", None) |
| 71 | + base_path = os.getenv("MODEL_PATH") |
| 72 | + if base_path: |
| 73 | + model_path = os.path.join(base_path, "ERNIE-4.5-0.3B-Paddle") |
| 74 | + else: |
| 75 | + model_path = "./ERNIE-4.5-0.3B-Paddle" |
| 76 | + log_path = "server.log" |
| 77 | + |
| 78 | + cmd = [ |
| 79 | + sys.executable, |
| 80 | + "-m", |
| 81 | + "fastdeploy.entrypoints.openai.api_server", |
| 82 | + "--model", |
| 83 | + model_path, |
| 84 | + "--port", |
| 85 | + str(FD_API_PORT), |
| 86 | + "--tensor-parallel-size", |
| 87 | + "1", |
| 88 | + "--engine-worker-queue-port", |
| 89 | + str(FD_ENGINE_QUEUE_PORT), |
| 90 | + "--metrics-port", |
| 91 | + str(FD_METRICS_PORT), |
| 92 | + "--cache-queue-port", |
| 93 | + str(FD_CACHE_QUEUE_PORT), |
| 94 | + "--max-model-len", |
| 95 | + "32768", |
| 96 | + "--max-num-seqs", |
| 97 | + "128", |
| 98 | + "--quantization", |
| 99 | + "wint4", |
| 100 | + "--graph-optimization-config", |
| 101 | + '{"cudagraph_capture_sizes": [1], "use_cudagraph":true}', |
| 102 | + ] |
| 103 | + |
| 104 | + if api_key_cli is not None: |
| 105 | + for key in api_key_cli: |
| 106 | + cmd.extend(["--api-key", key]) |
| 107 | + |
| 108 | + with open(log_path, "w") as logfile: |
| 109 | + process = subprocess.Popen(cmd, stdout=logfile, stderr=subprocess.STDOUT, start_new_session=True, env=env) |
| 110 | + |
| 111 | + for _ in range(300): |
| 112 | + if is_port_open("127.0.0.1", FD_API_PORT): |
| 113 | + print(f"API server started (port: {FD_API_PORT}, cli_key: {api_key_cli}, env_key: {api_key_env})") |
| 114 | + current_server_process = process |
| 115 | + return process |
| 116 | + time.sleep(1) |
| 117 | + else: |
| 118 | + if process.poll() is None: |
| 119 | + os.killpg(process.pid, signal.SIGTERM) |
| 120 | + raise RuntimeError(f"API server failed to start in 5 minutes (port: {FD_API_PORT})") |
| 121 | + |
| 122 | + |
| 123 | +def stop_api_server(): |
| 124 | + global current_server_process |
| 125 | + if current_server_process and current_server_process.poll() is None: |
| 126 | + try: |
| 127 | + os.killpg(current_server_process.pid, signal.SIGTERM) |
| 128 | + current_server_process.wait(timeout=10) |
| 129 | + print(f"API server stopped (pid: {current_server_process.pid})") |
| 130 | + except Exception as e: |
| 131 | + print(f"Failed to stop server: {e}") |
| 132 | + current_server_process = None |
| 133 | + clean_ports() |
| 134 | + |
| 135 | + |
| 136 | +@pytest.fixture(scope="function", autouse=True) |
| 137 | +def teardown_server(): |
| 138 | + yield |
| 139 | + stop_api_server() |
| 140 | + os.environ.pop("FD_API_KEY", None) |
| 141 | + |
| 142 | + |
| 143 | +@pytest.fixture(scope="function") |
| 144 | +def api_url(): |
| 145 | + return f"http://0.0.0.0:{FD_API_PORT}/v1/chat/completions" |
| 146 | + |
| 147 | + |
| 148 | +@pytest.fixture |
| 149 | +def common_headers(): |
| 150 | + return {"Content-Type": "application/json"} |
| 151 | + |
| 152 | + |
| 153 | +@pytest.fixture |
| 154 | +def valid_auth_headers(): |
| 155 | + return {"Content-Type": "application/json", "Authorization": "Bearer {api_key}"} |
| 156 | + |
| 157 | + |
| 158 | +@pytest.fixture |
| 159 | +def test_payload(): |
| 160 | + return {"messages": [{"role": "user", "content": "hello"}], "temperature": 0.9, "max_tokens": 100} |
| 161 | + |
| 162 | + |
| 163 | +def test_api_key_cli_only(api_url, common_headers, valid_auth_headers, test_payload): |
| 164 | + test_api_key = ["cli_test_key_123", "cli_test_key_456"] |
| 165 | + start_api_server(api_key_cli=test_api_key) |
| 166 | + |
| 167 | + response = requests.post(api_url, json=test_payload, headers=common_headers) |
| 168 | + assert response.status_code == 401 |
| 169 | + assert "error" in response.json() |
| 170 | + assert "unauthorized" in response.json()["error"].lower() |
| 171 | + |
| 172 | + invalid_headers = valid_auth_headers.copy() |
| 173 | + invalid_headers["Authorization"] = invalid_headers["Authorization"].format(api_key="wrong_key") |
| 174 | + response = requests.post(api_url, json=test_payload, headers=invalid_headers) |
| 175 | + assert response.status_code == 401 |
| 176 | + |
| 177 | + valid_headers = valid_auth_headers.copy() |
| 178 | + valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key=test_api_key[0]) |
| 179 | + response = requests.post(api_url, json=test_payload, headers=valid_headers) |
| 180 | + assert response.status_code == 200 |
| 181 | + |
| 182 | + valid_headers = valid_auth_headers.copy() |
| 183 | + valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key=test_api_key[1]) |
| 184 | + response = requests.post(api_url, json=test_payload, headers=valid_headers) |
| 185 | + assert response.status_code == 200 |
| 186 | + |
| 187 | + |
| 188 | +def test_api_key_env_only(api_url, common_headers, valid_auth_headers, test_payload): |
| 189 | + test_api_key = "env_test_key_456,env_test_key_789" |
| 190 | + start_api_server(api_key_env=test_api_key) |
| 191 | + |
| 192 | + response = requests.post(api_url, json=test_payload, headers=common_headers) |
| 193 | + assert response.status_code == 401 |
| 194 | + |
| 195 | + valid_headers = valid_auth_headers.copy() |
| 196 | + valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key="env_test_key_456") |
| 197 | + response = requests.post(api_url, json=test_payload, headers=valid_headers) |
| 198 | + assert response.status_code == 200 |
| 199 | + |
| 200 | + valid_headers = valid_auth_headers.copy() |
| 201 | + valid_headers["Authorization"] = valid_headers["Authorization"].format(api_key="env_test_key_789") |
| 202 | + response = requests.post(api_url, json=test_payload, headers=valid_headers) |
| 203 | + assert response.status_code == 200 |
| 204 | + |
| 205 | + |
| 206 | +def test_api_key_cli_priority_over_env(api_url, valid_auth_headers, test_payload): |
| 207 | + cli_key = ["cli_priority_key_789"] |
| 208 | + env_key = "env_low_priority_key_000" |
| 209 | + start_api_server(api_key_cli=cli_key, api_key_env=env_key) |
| 210 | + |
| 211 | + env_headers = valid_auth_headers.copy() |
| 212 | + env_headers["Authorization"] = env_headers["Authorization"].format(api_key=env_key) |
| 213 | + response = requests.post(api_url, json=test_payload, headers=env_headers) |
| 214 | + assert response.status_code == 401 |
| 215 | + |
| 216 | + cli_headers = valid_auth_headers.copy() |
| 217 | + cli_headers["Authorization"] = cli_headers["Authorization"].format(api_key=cli_key[0]) |
| 218 | + response = requests.post(api_url, json=test_payload, headers=cli_headers) |
| 219 | + assert response.status_code == 200 |
| 220 | + |
| 221 | + |
| 222 | +def test_api_key_not_set(api_url, common_headers, valid_auth_headers, test_payload): |
| 223 | + start_api_server(api_key_cli=None, api_key_env=None) |
| 224 | + |
| 225 | + response = requests.post(api_url, json=test_payload, headers=common_headers) |
| 226 | + assert response.status_code == 200 |
| 227 | + |
| 228 | + cli_headers = valid_auth_headers.copy() |
| 229 | + cli_headers["Authorization"] = cli_headers["Authorization"].format(api_key="some_api_key") |
| 230 | + response = requests.post(api_url, json=test_payload, headers=cli_headers) |
| 231 | + assert response.status_code == 200 |
0 commit comments