-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.py
More file actions
188 lines (152 loc) · 8.06 KB
/
test.py
File metadata and controls
188 lines (152 loc) · 8.06 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import subprocess
import time
import random
import sys
# ==========================================
# 配置区
# ==========================================
MAIN_CLASS = "SortAlgorithms"
TIMEOUT_LIMIT = 5.0 # 极限 5 秒压测!
def run_java_test(input_str):
"""运行 Java 程序并捕获输出,严格限制超时"""
try:
start_time = time.time()
process = subprocess.Popen(
['java', '-Dfile.encoding=UTF-8', MAIN_CLASS],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding='utf-8'
)
# communicate 会向标准输入写入数据,并等待程序结束或超时
stdout, stderr = process.communicate(input=input_str, timeout=TIMEOUT_LIMIT)
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
exit_code = process.returncode
return stdout.strip().split('\n'), exit_code, elapsed, stderr
except subprocess.TimeoutExpired as e:
process.kill()
out_str = e.stdout if e.stdout else ""
err_str = e.stderr if e.stderr else ""
debug_info = f"\n--- ⏳ 超时前捕获到的 Java 输出 ---\n[标准输出]:\n{out_str}\n[Debug输出]:\n{err_str}-----------------------------------"
return ["TIMEOUT"], -1, TIMEOUT_LIMIT * 1000, debug_info
except Exception as e:
return ["ERROR"], -1, 0, str(e)
def is_sorted(output_lines):
"""检查输出的数字部分是否严格从小到大排序"""
if len(output_lines) <= 2: return True
try:
# 从第二行开始是排好序的数字
nums = [int(line.strip()) for line in output_lines[1:] if line.strip()]
for i in range(len(nums) - 1):
if nums[i] > nums[i+1]:
return False
return True
except:
return False
def generate_test_cases():
"""构造涵盖所有规则、边界、极其严格的异常处理和性能极限的全维度测试用例"""
cases = []
print("⏳ 正在生成测试数据,包含 100 万级别压测数据,请稍候...")
# === 1. 核心规则测试 (Core Rules) ===
cases.append(("1. BubbleSort (<50)", "9,6,2,1\n", "BubbleSort"))
c_counting = [random.randint(0, 500) for _ in range(100)]
cases.append(("2. CountingSort", ",".join(map(str, c_counting)) + "\n", "CountingSort"))
c_merge = [random.randint(0, 5000) for _ in range(12000)]
cases.append(("3. MergeSort (Large)", ",".join(map(str, c_merge)) + "\n", "MergeSort"))
c_insertion = list(range(1000))
for _ in range(40):
idx = random.randint(0, 998)
c_insertion[idx], c_insertion[idx+1] = c_insertion[idx+1], c_insertion[idx]
cases.append(("4. Insertion (Nearly Sorted)", ",".join(map(str, c_insertion)) + "\n", "InsertionSort"))
c_quick = [random.randint(0, 50000) for _ in range(9999)]
cases.append(("5. QuickSort (Medium Array)", ",".join(map(str, c_quick)) + "\n", "QuickSort"))
# === 2. 严格模式与异常测试 (Strict Mode & Exceptions) ===
# 真正的 EOF(没有换行符,完全空流)
cases.append(("6. True EOF (No input)", "", "BubbleSort"))
# 以下按照老师的要求,只要触发 NumberFormatException 全部静默退出 (SILENT)
cases.append(("7. Strict: Empty Line (Enter)", "\n", "SILENT"))
cases.append(("8. Strict: Pure Spaces", " \n", "SILENT"))
cases.append(("9. Strict: Space after comma", "1, 2\n", "SILENT"))
cases.append(("10. Strict: Space before comma", "1 ,2\n", "SILENT"))
cases.append(("11. Strict: Trailing comma", "1,2,\n", "SILENT"))
cases.append(("12. Strict: Multiple commas", "1,,2\n", "SILENT"))
cases.append(("13. Strict: Letters", "A,B,C\n", "SILENT"))
cases.append(("14. Strict: Floats", "1.1,2.2\n", "SILENT"))
# === 3. 边界精确打击 (Threshold Boundaries) ===
c_range999 = list(range(1000))
random.shuffle(c_range999)
cases.append(("15. Range Exactly 999", ",".join(map(str, c_range999)) + "\n", "CountingSort"))
c_range1000 = list(range(1001))
random.shuffle(c_range1000)
cases.append(("16. Range Exactly 1000", ",".join(map(str, c_range1000)) + "\n", "QuickSort"))
c_len10000 = [random.randint(0, 50000) for _ in range(10000)]
cases.append(("17. Length Exactly 10000", ",".join(map(str, c_len10000)) + "\n", "MergeSort"))
# === 4. 负数处理 (Negative Integers) ===
cases.append(("18. Negatives (Short)", "-50,-10,0,-20,10\n", "BubbleSort"))
c_neg_count = [random.randint(-500, 400) for _ in range(100)]
cases.append(("19. Negatives Range (Counting)", ",".join(map(str, c_neg_count)) + "\n", "CountingSort"))
# === 5. 终极性能压测 (1 Million Elements, < 5s) ===
c_1million = [random.randint(0, 1000000) for _ in range(1000000)]
cases.append(("20. ONE MILLION ELEMENTS (Merge)", ",".join(map(str, c_1million)) + "\n", "MergeSort"))
print("✅ 测试数据生成完毕!开始极限测试...\n")
return cases
def run_tester():
print(f"{'Test Case':<34} | {'Expected Strategy':<15} | {'Time':<6} | {'Result'}")
print("-" * 75)
cases = generate_test_cases()
pass_count = 0
for name, input_str, expected in cases:
output, exit_code, duration, err = run_java_test(input_str)
actual_strategy = "N/A"
sorted_ok = False
if output and len(output) > 0 and "Strategy:" in output[0]:
actual_strategy = output[0].replace("Strategy: ", "").strip()
sorted_ok = is_sorted(output)
# 结果判定逻辑
if expected == "SILENT":
# 期望静默退出:无输出(或全是空行),且 Exit Code 为 0
strat_ok = (len(output) == 0 or (len(output) == 1 and output[0] == ""))
sorted_ok = True
else:
strat_ok = (actual_strategy == expected)
# 判断通过条件
if strat_ok and sorted_ok and exit_code == 0:
status = "✅ PASS"
pass_count += 1
elif output[0] == "TIMEOUT":
status = "⏳ TLE"
elif exit_code != 0:
status = f"💥 CRASH ({exit_code})"
else:
status = "❌ FAIL"
print(f"{name:<34} | {expected:<15} | {int(duration):<4}ms | {status}")
# 错误排查打印
if status != "✅ PASS":
if output[0] == "TIMEOUT":
print(f" [Error] Time Limit Exceeded (> 5s)")
print(f"{err}")
elif exit_code != 0:
print(f" [Error] Program returned non-zero exit code")
print(f" [Error Details] {err}")
elif not strat_ok and expected != "SILENT":
print(f" [Error] Strategy mismatch: Expected '{expected}', Got '{actual_strategy}'")
elif not strat_ok and expected == "SILENT":
print(f" [Error] Expected silent exit, but got output: '{output[0]}'")
elif not sorted_ok:
print(f" [Error] Array not sorted correctly!")
else:
# 针对 100 万压测,专门打印它的成功 Debug 日志,让你感受速度!
if "ONE MILLION" in name and err and err.strip():
print(f" [🚀 极限压测性能报告] ->\n {err.strip().replace(chr(10), chr(10)+' ')}")
print("-" * 75)
print(f"Final Score: {pass_count}/{len(cases)}")
if pass_count == len(cases):
print("\n🎉 恭喜!你的代码无懈可击!完美通过了极严苛模式和 100 万并发极限测试,准备拿满分吧!")
if __name__ == "__main__":
print("正在编译 Java 代码...")
compile_process = subprocess.run(["javac", "-encoding", "UTF-8", MAIN_CLASS + ".java"])
if compile_process.returncode != 0:
print("❌ 编译失败,请检查 Java 语法错误。")
sys.exit(1)
run_tester()