33
44from dotenv import load_dotenv
55from openai import OpenAI
6+ import json
7+ import json5
68
79
810class OpenAIClient :
@@ -11,22 +13,52 @@ def __init__(self, api_key=None):
1113 load_dotenv ()
1214 # print('OPENAI_API_KEY:', os.getenv('OPENAI_API_KEY'))
1315 api_key = os .getenv ('OPENAI_API_KEY' )
14- self .client = OpenAI (api_key = api_key )
16+ self .client = OpenAI (
17+ api_key = api_key ,
18+ base_url = 'https://api.chatanywhere.tech/v1'
19+ )
20+
21+ def parse_ai_response (self , response_str : str ):
22+ # print('AI return response string:', response_str)
23+ try :
24+ return json5 .loads (response_str )
25+ except ValueError as e :
26+ print (f'Cannot decode JSON5: { e } ' )
27+ # print('Response string was:', response_str)
28+ raise
1529
1630 def generate_api_test_cases (
17- self , method : str , api_path : str , request_sample : dict , response_sample : dict , resp_err_code : str = None ):
31+ self , method : str , api_path : str , request_sample : dict , response_sample : dict , max_cases_number : int ,
32+ max_tokens : int = 1500 , resp_err_code : str = None ):
1833 """Setup AI chat content, to generate API test cases."""
1934
20- user_prompt_content = textwrap .dedent (
21- """
22- Please according the API sample to generate test case:
23- method: {method}
24- api path: {api_path}
25- request sample: {request_sample}
26- response sample: {request_sample}
27- response error code (if have): {resp_err_code}
28- """
29- ).strip ()
35+ user_prompt_content = textwrap .dedent (f"""
36+ You are a Senior Software QA Engineer who designs test cases.
37+ Given the API details below, generate a JSON array of test cases.
38+ Each test case should have 'input' and 'expected' fields.
39+ Return ONLY a valid JSON array, without any extra text or explanation.
40+ Output MUST end with closing square bracket: `]`
41+ ONLY GENERATE { max_cases_number } CASES
42+
43+ Method: { method }
44+ API path: { api_path }
45+ Request sample: { json .dumps (request_sample , indent = 2 )}
46+ Response sample: { json .dumps (response_sample , indent = 2 )}
47+ Response error code: { resp_err_code if resp_err_code else 'None' }
48+
49+ Example output format:
50+ [
51+ {{
52+ "test_case_name": "test_with_valid_products",
53+ "input": {{ ... }},
54+ "expected": {{
55+ "status_code": 200,
56+ "response": {{ ... }}
57+ }}
58+ }},
59+ ...
60+ ]
61+ """ ).strip ()
3062
3163 prompt = [
3264 {
@@ -42,6 +74,6 @@ def generate_api_test_cases(
4274 model = 'gpt-4.1-nano' ,
4375 messages = prompt ,
4476 temperature = 0.3 ,
45- max_tokens = 10
77+ max_tokens = max_tokens
4678 )
4779 return response .choices [0 ].message .content
0 commit comments