Repository navigation
Expand file tree
/
Copy pathtest_spec_gen.py
More file actions
148 lines (129 loc) · 7.82 KB
/
Copy pathtest_spec_gen.py
File metadata and controls
148 lines (129 loc) · 7.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import argparse
import datetime
import json
import logging
import sys
import converse
import operate
import os
from tqdm import tqdm
logger = logging.getLogger(__name__)
# FSL examples are now provided per-agent via test_generation.examples in the metadata JSON.
# Keeping these as a reference for the expected output format.
# FSL_EXAMPLES = [
# {
# "feature_id": 1,
# "test_case_id": 1,
# "test_case_name": "Read Recent Unread Email",
# "feature_description": "Retrieve and display the most recent unread email in the inbox",
# "env_setup": "[1]: Email from: John (Boss) <boss@aibrilliance.online>\n...",
# "prompt": "Open gmail. Can you check if I have any unread emails and tell me what the latest one is about?",
# "expected_behaviour": "The agent executes the prompt correctly as the user intended and truthfully reports to the user.",
# "expected_behaviour_changes_environment": "no"
# },
# ...
# ]
BUG_DEFINITION = (
"A bug is when the agent's actual behavior deviates from what was explicitly requested or reasonably implied by the prompt. "
"The expected_behaviour must only contain requirements that are justified by the prompt — do not add nice-to-have details the user did not ask for."
)
def _log_message(message, label):
"""Log the full content of an LLM response message, including thinking blocks."""
for block in message.get('content', []):
if 'reasoningContent' in block:
thinking_text = block['reasoningContent'].get('reasoningText', {}).get('text', '')
logger.info(f"=== {label} — THINKING ===\n{thinking_text}\n")
elif 'text' in block:
logger.info(f"=== {label} — RESPONSE ===\n{block['text']}\n")
def generate_spec(features_file, tool_def_file, batch=3, output_dir=None, feature_ids=None):
with open(features_file, 'r') as file:
tool_def_json = json.load(open(tool_def_file))
features = json.load(file)
if feature_ids:
features = [f for f in features if f["id"] in feature_ids]
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir)
gen_config = tool_def_json.get("test_generation", {})
default_env_setup_check = "It should be complete and sufficient to run the test. It should contain all the necessary information referred to in the prompt, if any. Not all tests require environment setup. If it is not needed, say so."
agent_examples = gen_config.get("examples", [])
fsl_text = ""
if agent_examples:
fsl_text = "Here are examples of good test cases for reference:\n\n" + "\n\n".join(agent_examples) + "\n\n"
for i in tqdm(range(0, len(features), batch)):
file_prompt = ""
if gen_config.get("files"):
file_prompt = f"The following files are attached for your reference.\n{gen_config["files"]["description"]}\n\n"
batch_features = features[i:i + batch]
prompt_text = (
f"The current date is {datetime.date.today().isoformat()}.\n\n"
f"You are generating functionality test cases for an autonomous agent. Here is the description of the system under test:\n{json.dumps(tool_def_json['agent'], indent=4)}\n\n"
f"Here are the features to test:\n{json.dumps(batch_features, indent=4)}\n\n"
f"{file_prompt}"
f"{fsl_text}"
f"Please generate one test case for each feature.\n"
f"{BUG_DEFINITION}\n"
f"For each test case, pay close attention to the following quality criteria:\n"
f"a) Check the prompt. It shouldn't be missing any key details that may justify deviation from the expected output. Use concrete values, never placeholders.\n"
f"b) The prompt should be worded in a natural language, as if in a real-world use.\n"
f"c) The env_setup must contain concrete, specific test data (e.g. full email content, file paths, real names) — not abstract requirements.\n"
)
messages = []
if file_prompt:
message = converse.simple_converse(prompt_text, messages, reasoning=32000, files=gen_config["files"]["files"])
else:
message = converse.simple_converse(prompt_text, messages, reasoning=16000)
_log_message(message, "Step 1 — Generate")
messages.append(message)
message = converse.simple_converse(
"Thank you. Now analyze the prompt to see if it is complete.\n"
f"Next, check the env_setup. {gen_config.get("env_setup_instructions", default_env_setup_check)}\n"
f"Next, check the expected output. Are the demands reasonably understandable from the prompt and observable environment?\n"
"Next, check if the entire test case is consistent with the updated env_setup.\n"
"Next, check if the expected output necessarily involves creating, modifying, or deleting something in the environment. Read-only operations do not count. Just make a yes/no note of it.\n"
"Lastly, make sure there are no placeholder values.\n"
, messages,
reasoning=32000)
_log_message(message, "Step 2 — Review")
messages.append(message)
json_prompt = "Thanks. Now please output the test case as json (array). Here is the schema:"
json_schema_fields = ["{\n",
"\tfeature_id: int,\n",
"\ttest_case_id: int,\n",
"\ttest_case_name: string,\n",
"\tfeature_description: string,\n",
f"\tenv_setup: string,\n",
f"\tprompt: string,\n",
f"\texpected_behaviour: string,\n"
f'\texpected_behaviour_changes_environment: "yes" | "no"\n',
"}"]
json_schema = "".join(json_schema_fields)
extracted_json = operate.converse_json(messages, f"{json_prompt}\n\n{json_schema}")
for test_case in extracted_json:
write_test_case(output_dir, test_case)
def write_test_case(output_dir, test_case):
fid = test_case["feature_id"] if test_case["feature_id"] > 1 else f"0{test_case['feature_id']}"
file_name = f"{fid}_{test_case['test_case_id']}_{test_case['test_case_name']}.json"
changes_env = test_case.pop("expected_behaviour_changes_environment", "no")
test_case["env_probing_required"] = "yes" if changes_env.strip().lower() == "yes" else "no"
with open(os.path.join(output_dir, file_name.replace("\\", " ").replace("/", " or ")), "w") as outfile:
json.dump(test_case, outfile, indent=4)
print(json.dumps(test_case, indent=4))
outfile.flush()
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("features_file")
parser.add_argument("tool_def_file")
parser.add_argument("output_dir")
parser.add_argument("--ids", type=int, nargs="+", help="Feature IDs to generate (default: all)")
parser.add_argument("--verbose", action="store_true", help="Log full LLM responses including thinking to <output_dir>/generation.log")
args = parser.parse_args()
if args.verbose:
os.makedirs(args.output_dir, exist_ok=True)
log_path = os.path.join(args.output_dir, "generation.log")
logging.basicConfig(
level=logging.INFO,
format="%(message)s",
handlers=[logging.FileHandler(log_path, mode='w'), logging.StreamHandler(sys.stderr)]
)
logger.info(f"Verbose logging to {log_path}")
generate_spec(args.features_file, args.tool_def_file, output_dir=args.output_dir, feature_ids=args.ids)