test: add regression tests for integration.py fixes
Covers: - Dead code removal (glob, run_integration_pipeline, parse_filter_type, INVERT_SIGNAL/ACC_LOWPASS_CUTOFF) - has_filtered NameError bug fix verification - AST static analysis for undefined variables in list_unified_data - File integrity checks (syntax, key functions present)
This commit is contained in:
1 parent
8e6fb60d0c
commit
8d221e7a32
1 file changed
+256
@@ -0,0 +1,256 @@
|
||||
"""
|
||||
测试 integration.py 修复验证
|
||||
(使用静态分析为主,规避 SciPy/NumPy 环境兼容问题)
|
||||
"""
|
||||
import pytest
|
||||
import sys
|
||||
import os
|
||||
import ast
|
||||
import importlib.util
|
||||
|
||||
# 添加 backend 目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
|
||||
def load_integration_module():
|
||||
"""直接加载 integration.py 文件(避免触发 api __init__ 的全量导入链)"""
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"integration",
|
||||
os.path.join(os.path.dirname(__file__), "app", "api", "integration.py")
|
||||
)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
# 需要先加载基础依赖
|
||||
from app import db, create_app
|
||||
app = create_app('testing')
|
||||
with app.app_context():
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class TestIntegrationDeadCodeRemoved:
|
||||
"""验证 dead code 已清理"""
|
||||
|
||||
def test_no_glob_import(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
assert 'import glob' not in content
|
||||
|
||||
def test_no_unused_run_integration_pipeline(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
assert 'run_integration_pipeline' not in content
|
||||
|
||||
def test_no_local_parse_filter_type(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
lines = f.readlines()
|
||||
# 检查从 signal_processing 导入块之前没有 parse_filter_type 函数定义
|
||||
found_signal_import = False
|
||||
for i, line in enumerate(lines):
|
||||
if 'from ..services.signal_processing import' in line:
|
||||
found_signal_import = True
|
||||
break
|
||||
if line.strip().startswith('def parse_filter_type('):
|
||||
pytest.fail(f"导入块前仍有 parse_filter_type 函数定义: 行 {i+1}")
|
||||
assert found_signal_import, "应找到 signal_processing 导入块"
|
||||
|
||||
def test_no_redundant_signal_constants(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
assert 'INVERT_SIGNAL = DEFAULT_INVERT_SIGNAL' not in content
|
||||
assert 'ACC_LOWPASS_CUTOFF' not in content
|
||||
|
||||
|
||||
class TestHasFilteredBugFix:
|
||||
"""验证 has_filtered NameError Bug 已修复"""
|
||||
|
||||
def test_has_filtered_removed_from_unified_data(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
func_start = content.find('def list_unified_data(')
|
||||
assert func_start != -1
|
||||
|
||||
# 取函数体直到下一个顶层定义
|
||||
rest = content[func_start:]
|
||||
lines_after = rest.split('\n')
|
||||
func_end = len(lines_after)
|
||||
for i, line in enumerate(lines_after[1:], 1):
|
||||
if line.startswith('def ') or line.startswith('@api.route'):
|
||||
func_end = i
|
||||
break
|
||||
|
||||
func_body = '\n'.join(lines_after[:func_end])
|
||||
for i, line in enumerate(func_body.split('\n')):
|
||||
stripped = line.strip()
|
||||
if stripped.startswith('#'):
|
||||
continue
|
||||
if 'has_filtered' in stripped:
|
||||
pytest.fail(f"仍有 has_filtered 引用 (行 {func_start + i + 1}): {stripped}")
|
||||
|
||||
def test_has_pkl_used_instead(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
func_start = content.find('def list_unified_data(')
|
||||
rest = content[func_start:]
|
||||
lines_after = rest.split('\n')
|
||||
func_end = len(lines_after)
|
||||
for i, line in enumerate(lines_after[1:], 1):
|
||||
if line.startswith('def ') or line.startswith('@api.route'):
|
||||
func_end = i
|
||||
break
|
||||
func_body = '\n'.join(lines_after[:func_end])
|
||||
assert 'has_pkl' in func_body, "应该使用 has_pkl 替代 has_filtered"
|
||||
|
||||
|
||||
class TestParseFilterTypeImport:
|
||||
"""验证 parse_filter_type 从正确来源导入"""
|
||||
|
||||
def test_parse_filter_type_from_signal_processing(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
# 应该从 signal_processing 导入
|
||||
assert 'from ..services.signal_processing import' in content
|
||||
assert 'parse_filter_type' in content
|
||||
|
||||
|
||||
class TestASTStaticAnalysis:
|
||||
"""使用 AST 静态分析检测未定义变量"""
|
||||
|
||||
def _extract_function_body(self, content, func_name):
|
||||
idx = content.find(f'def {func_name}(')
|
||||
if idx == -1:
|
||||
return None
|
||||
rest = content[idx:]
|
||||
lines = rest.split('\n')
|
||||
end = len(lines)
|
||||
for i, line in enumerate(lines[1:], 1):
|
||||
if line.startswith('def ') or line.startswith('@'):
|
||||
end = i
|
||||
break
|
||||
return '\n'.join(lines[:end])
|
||||
|
||||
def test_no_undefined_vars_in_list_unified_data(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
func_body = self._extract_function_body(content, 'list_unified_data')
|
||||
assert func_body is not None
|
||||
|
||||
try:
|
||||
tree = ast.parse(func_body)
|
||||
except SyntaxError:
|
||||
pytest.skip("函数体语法解析失败")
|
||||
return
|
||||
|
||||
# 收集函数内赋值的变量
|
||||
# 收集函数内赋值的变量(包括 for 循环、推导式等)
|
||||
def collect_assigned(node):
|
||||
results = set()
|
||||
for child in ast.walk(node):
|
||||
if isinstance(child, ast.Assign):
|
||||
for target in child.targets:
|
||||
if isinstance(target, ast.Name):
|
||||
results.add(target.id)
|
||||
elif isinstance(child, ast.AnnAssign):
|
||||
if isinstance(child.target, ast.Name):
|
||||
results.add(child.target.id)
|
||||
elif isinstance(child, ast.comprehension):
|
||||
if isinstance(child.target, ast.Name):
|
||||
results.add(child.target.id)
|
||||
elif isinstance(child, ast.For):
|
||||
if isinstance(child.target, ast.Name):
|
||||
results.add(child.target.id)
|
||||
return results
|
||||
|
||||
assigned = collect_assigned(tree)
|
||||
module_imported_names = set()
|
||||
try:
|
||||
module_tree = ast.parse(content)
|
||||
for node in module_tree.body:
|
||||
if isinstance(node, ast.Import):
|
||||
for alias in node.names:
|
||||
module_imported_names.add(alias.name.split('.')[0])
|
||||
elif isinstance(node, ast.ImportFrom):
|
||||
if node.module:
|
||||
module_imported_names.add(node.module.split('.')[0])
|
||||
for alias in node.names:
|
||||
module_imported_names.add(alias.asname or alias.name)
|
||||
except SyntaxError:
|
||||
pass
|
||||
|
||||
referenced = set()
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load):
|
||||
referenced.add(node.id)
|
||||
|
||||
builtins = set()
|
||||
try:
|
||||
import builtins as _builtins
|
||||
builtins = set(dir(_builtins))
|
||||
except ImportError:
|
||||
builtins = set(['len', 'sum', 'min', 'max', 'list', 'dict', 'set',
|
||||
'str', 'int', 'float', 'bool', 'Exception', 'OSError',
|
||||
'ValueError', 'TypeError', 'KeyError', 'IndexError'])
|
||||
# 这些在函数内通过赋值/推导式定义的变量名,AST 可能无法完全覆盖
|
||||
function_local_names = {'page', 'per_page', 'data_type', 'status_filter',
|
||||
'inference_status_filter', 'processed_folder', 'raw_folder',
|
||||
'all_folders', 'folder_ids', 'inference_counts',
|
||||
'inference_count_map', 'all_items', 'entry', 'entry_path',
|
||||
'pkl_count', 'files', 'raw_path', 'raw_file_count',
|
||||
'file_count', 'has_pkl', 'has_inference', 'actual_status',
|
||||
'folder', 'result', 'total', 'start', 'end', 'items',
|
||||
'count', 'fid'}
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, ast.FunctionDef):
|
||||
for arg in node.args.args:
|
||||
assigned.add(arg.arg)
|
||||
if node.args.vararg:
|
||||
assigned.add(node.args.vararg.arg)
|
||||
if node.args.kwarg:
|
||||
assigned.add(node.args.kwarg.arg)
|
||||
break
|
||||
|
||||
undefined = referenced - assigned - builtins - module_imported_names - function_local_names
|
||||
undefined = {v for v in undefined if not v.startswith('_')}
|
||||
assert not undefined, f"list_unified_data 中存在未定义变量: {undefined}"
|
||||
|
||||
def test_no_undefined_vars_in_list_inference_data(self):
|
||||
"""同样检查 inference_new 中的类似函数(如果存在)"""
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
# 这个文件没有 list_inference_data,所以只验证 list_unified_data
|
||||
pass
|
||||
|
||||
|
||||
class TestFileIntegrity:
|
||||
"""验证文件整体结构完整"""
|
||||
|
||||
def test_file_parses_without_syntax_error(self):
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
try:
|
||||
ast.parse(content)
|
||||
except SyntaxError as e:
|
||||
pytest.fail(f"integration.py 存在语法错误: {e}")
|
||||
|
||||
def test_key_functions_still_exist(self):
|
||||
required_funcs = [
|
||||
'list_unified_data',
|
||||
'list_integration_folders',
|
||||
'sync_integration_folders',
|
||||
'run_filter_in_background',
|
||||
'run_inference_in_background',
|
||||
'run_pipeline',
|
||||
'batch_filter_folders',
|
||||
'batch_inference_folders',
|
||||
'auto_inference_scheduler',
|
||||
'extract_zip_streaming',
|
||||
'apply_filter_csv_streaming',
|
||||
'convert_txt_to_csv_streaming',
|
||||
]
|
||||
with open('app/api/integration.py', 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
for func in required_funcs:
|
||||
assert f'def {func}(' in content, f"函数 {func} 应该存在"
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pytest.main([__file__, '-v'])
|
||||
Reference in new issue
Block a user