test_example_validation.py
9.5 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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# AIfeng/2025-01-27 14:30:00
"""
豆包ASR示例文件测试验证
验证example.py的可运行性和依赖完整性
"""
import unittest
import subprocess
import sys
import os
from pathlib import Path
import tempfile
import json
class TestExampleValidation(unittest.TestCase):
"""
示例文件验证测试
"""
def setUp(self):
"""测试初始化"""
self.project_root = Path(__file__).parent.parent
self.asr_path = self.project_root / 'asr' / 'doubao'
self.example_path = self.asr_path / 'example.py'
def test_example_file_exists(self):
"""测试示例文件是否存在"""
self.assertTrue(self.example_path.exists(), f"示例文件不存在: {self.example_path}")
def test_example_file_syntax(self):
"""测试示例文件语法是否正确"""
try:
# 使用python -m py_compile检查语法
result = subprocess.run(
[sys.executable, '-m', 'py_compile', str(self.example_path)],
capture_output=True,
text=True,
cwd=str(self.asr_path)
)
self.assertEqual(result.returncode, 0, f"语法错误: {result.stderr}")
except Exception as e:
self.fail(f"语法检查失败: {e}")
def test_required_dependencies(self):
"""测试必需的依赖是否存在"""
required_files = [
'__init__.py',
'asr_client.py',
'config_manager.py',
'protocol.py',
'service_factory.py',
'audio_utils.py'
]
for file_name in required_files:
file_path = self.asr_path / file_name
self.assertTrue(file_path.exists(), f"依赖文件不存在: {file_path}")
def test_import_check(self):
"""测试导入检查"""
# 创建临时测试脚本
test_script = """# -*- coding: utf-8 -*-
import sys
from pathlib import Path
# 添加ASR路径
sys.path.insert(0, str(Path(__file__).parent))
try:
# 测试example.py的导入是否成功
import example
print("SUCCESS: example.py imported successfully")
# 检查关键函数是否存在
required_attrs = ['ASRExamples', 'run_all_examples', 'create_sample_config']
for attr in required_attrs:
if hasattr(example, attr):
print(f"SUCCESS: Found {attr}")
else:
print(f"WARNING: Missing {attr}")
except ImportError as e:
print(f"IMPORT_ERROR: {e}")
sys.exit(1)
except Exception as e:
print(f"OTHER_ERROR: {e}")
sys.exit(1)
"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
f.write(test_script)
temp_script = f.name
try:
result = subprocess.run(
[sys.executable, temp_script],
capture_output=True,
text=True,
cwd=str(self.asr_path)
)
self.assertEqual(result.returncode, 0,
f"导入测试失败: {result.stdout} {result.stderr}")
self.assertIn("SUCCESS", result.stdout, "导入测试未成功")
finally:
os.unlink(temp_script)
def test_environment_variables_check(self):
"""测试环境变量检查"""
# 创建环境变量检查脚本
env_check_script = """# -*- coding: utf-8 -*-
import os
# 检查必需的环境变量
required_vars = ['DOUBAO_APP_KEY', 'DOUBAO_ACCESS_KEY']
missing_vars = []
for var in required_vars:
if not os.getenv(var):
missing_vars.append(var)
if missing_vars:
print(f"MISSING_ENV_VARS: {','.join(missing_vars)}")
else:
print("ENV_VARS_OK: All required environment variables are set")
"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
f.write(env_check_script)
temp_script = f.name
try:
result = subprocess.run(
[sys.executable, temp_script],
capture_output=True,
text=True
)
# 这个测试只是检查,不强制要求环境变量存在
if "MISSING_ENV_VARS" in result.stdout:
print(f"警告: 缺少环境变量 - {result.stdout.strip()}")
else:
print("环境变量检查通过")
finally:
os.unlink(temp_script)
def test_config_file_creation(self):
"""测试配置文件创建功能"""
# 创建配置文件测试脚本
config_test_script = """# -*- coding: utf-8 -*-
import sys
from pathlib import Path
import json
import tempfile
# 添加路径
sys.path.insert(0, str(Path(__file__).parent))
try:
# 测试通过example.py访问ConfigManager
import example
# 检查是否能访问create_sample_config函数
if hasattr(example, 'create_sample_config'):
# 尝试创建示例配置
config_path = example.create_sample_config()
print(f"CONFIG_TEST_SUCCESS: Sample config created at {config_path}")
else:
print("CONFIG_TEST_SUCCESS: example.py imported without config creation")
except Exception as e:
print(f"CONFIG_TEST_ERROR: {e}")
sys.exit(1)
"""
with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
f.write(config_test_script)
temp_script = f.name
try:
result = subprocess.run(
[sys.executable, temp_script],
capture_output=True,
text=True,
cwd=str(self.asr_path)
)
self.assertEqual(result.returncode, 0,
f"配置测试失败: {result.stdout} {result.stderr}")
self.assertIn("CONFIG_TEST_SUCCESS", result.stdout, "配置测试未成功")
finally:
os.unlink(temp_script)
def test_audio_file_availability(self):
"""测试音频文件可用性"""
# 检查项目中的音频文件
audio_extensions = ['.wav', '.mp3', '.m4a', '.flac']
audio_dirs = [
self.project_root / 'audio',
self.project_root / 'test' / 'audio',
self.project_root / 'samples'
]
found_audio_files = []
for audio_dir in audio_dirs:
if audio_dir.exists():
for ext in audio_extensions:
found_audio_files.extend(list(audio_dir.glob(f'*{ext}')))
# 检查根目录下的音频文件
for ext in audio_extensions:
found_audio_files.extend(list(self.project_root.glob(f'*{ext}')))
if found_audio_files:
print(f"找到音频文件: {[str(f) for f in found_audio_files[:3]]}")
else:
print("警告: 未找到测试音频文件")
def test_example_help_output(self):
"""测试示例文件帮助输出"""
try:
# 尝试运行example.py --help或查看文档字符串
result = subprocess.run(
[sys.executable, str(self.example_path), '--help'],
capture_output=True,
text=True,
cwd=str(self.asr_path),
timeout=10
)
# 如果--help不支持,至少文件应该能被python解析
if result.returncode != 0:
# 尝试简单的语法检查
result = subprocess.run(
[sys.executable, '-c', f'import ast; ast.parse(open("{self.example_path}").read())'],
capture_output=True,
text=True,
cwd=str(self.asr_path)
)
self.assertEqual(result.returncode, 0, f"文件解析失败: {result.stderr}")
except subprocess.TimeoutExpired:
print("示例文件运行超时(可能在等待输入)")
except Exception as e:
print(f"示例文件测试异常: {e}")
def run_validation_tests():
"""运行验证测试"""
print("=== 豆包ASR示例文件验证测试 ===")
# 创建测试套件
suite = unittest.TestLoader().loadTestsFromTestCase(TestExampleValidation)
# 运行测试
runner = unittest.TextTestRunner(verbosity=2)
result = runner.run(suite)
# 输出总结
print(f"\n=== 测试总结 ===")
print(f"总测试数: {result.testsRun}")
print(f"成功: {result.testsRun - len(result.failures) - len(result.errors)}")
print(f"失败: {len(result.failures)}")
print(f"错误: {len(result.errors)}")
if result.failures:
print("\n失败的测试:")
for test, traceback in result.failures:
error_msg = traceback.split('AssertionError: ')[-1].split('\n')[0]
print(f"- {test}: {error_msg}")
if result.errors:
print("\n错误的测试:")
for test, traceback in result.errors:
error_msg = traceback.split('\n')[-2]
print(f"- {test}: {error_msg}")
return result.wasSuccessful()
if __name__ == '__main__':
success = run_validation_tests()
if success:
print("\n✅ 示例文件验证通过,可以进行测试")
else:
print("\n❌ 示例文件验证失败,需要修复问题")
sys.exit(0 if success else 1)