测试接口在 stream 模式和非 stream 模式下返回的内容是否一致。
()
| 4 | |
| 5 | |
| 6 | def test_stream_and_non_stream(): |
| 7 | """ |
| 8 | 测试接口在 stream 模式和非 stream 模式下返回的内容是否一致。 |
| 9 | """ |
| 10 | |
| 11 | # 构造 stream=True 的请求数据 |
| 12 | data = { |
| 13 | "stream": True, |
| 14 | "messages": [ |
| 15 | {"role": "system", "content": "You are a helpful assistant."}, |
| 16 | {"role": "user", "content": "牛顿的三大运动定律是什么?"}, |
| 17 | ], |
| 18 | "max_tokens": 100, |
| 19 | } |
| 20 | |
| 21 | # 构建请求 payload 并发送流式请求 |
| 22 | payload = build_request_payload(TEMPLATE, data) |
| 23 | response = send_request(URL, payload) |
| 24 | |
| 25 | # 按行解析流式响应 |
| 26 | resp_chunks = [] |
| 27 | for line in response.iter_lines(): |
| 28 | if not line: |
| 29 | continue |
| 30 | |
| 31 | decoded = line.decode("utf-8") |
| 32 | if decoded.startswith("data: "): |
| 33 | decoded = decoded[len("data: ") :] |
| 34 | |
| 35 | if decoded == "[DONE]": |
| 36 | break |
| 37 | |
| 38 | resp_chunks.append(json.loads(decoded)) |
| 39 | |
| 40 | # 拼接模型最终输出内容 |
| 41 | final_content = "".join( |
| 42 | chunk["choices"][0]["delta"]["content"] |
| 43 | for chunk in resp_chunks |
| 44 | if "choices" in chunk and "delta" in chunk["choices"][0] and "content" in chunk["choices"][0]["delta"] |
| 45 | ) |
| 46 | print(final_content) |
| 47 | |
| 48 | # 修改为 stream=False,发送普通请求 |
| 49 | data["stream"] = False |
| 50 | payload = build_request_payload(TEMPLATE, data) |
| 51 | response = send_request(URL, payload) |
| 52 | |
| 53 | # 打印格式化后的完整响应 |
| 54 | print(json.dumps(response.json(), indent=2, ensure_ascii=False)) |
| 55 | response_json = response.json() |
| 56 | |
| 57 | # 对比两种模式下输出是否一致 |
| 58 | assert final_content == response_json["choices"][0]["message"]["content"] |
| 59 | |
| 60 | |
| 61 | if __name__ == "__main__": |
no test coverage detected