import os import sys import importlib.util import numpy as np import pandas as pd import pytest NMSE_THRESHOLD = 3e-5 # 读取所有需要测试的formula.py路径 with open(os.path.join(os.path.dirname(__file__), './filtered_formula_py.txt')) as f: formula_py_list = [line.strip() for line in f if line.strip()] def dynamic_import_formula(formula_path): # 动态导入formula.py,并注入np spec = importlib.util.spec_from_file_location('formula', formula_path) module = importlib.util.module_from_spec(spec) setattr(module, 'np', np) sys.modules['formula'] = module spec.loader.exec_module(module) # 取第一个非__开头的函数 func = None for name in dir(module): if not name.startswith('__') and callable(getattr(module, name)): func = getattr(module, name) break return func def find_all_csv_files(formula_path): # 返回同级目录下所有csv文件 base_dir = os.path.dirname(formula_path) csv_files = [] for fname in os.listdir(base_dir): if fname.endswith('.csv'): fpath = os.path.join(base_dir, fname) # 排除空文件 if os.path.getsize(fpath) > 0: csv_files.append(fpath) return csv_files def calc_nmse(y_true, y_pred): y_true = np.asarray(y_true) y_pred = np.asarray(y_pred) mse = np.mean((y_true - y_pred) ** 2) var = np.mean((y_true - np.mean(y_true)) ** 2) if var == 0: return np.inf if mse > 0 else 0 return mse / var @pytest.mark.parametrize('formula_path', formula_py_list) def test_formula(formula_path): func = dynamic_import_formula(formula_path) csv_files = find_all_csv_files(formula_path) assert csv_files, f'No csv files found for {formula_path}' for csv_file in csv_files: df = pd.read_csv(csv_file) if df.shape[1] < 2: continue # 跳过只有一列的csv target_col = df.columns[-1] # 只取最后一列为target input_cols = df.columns[:-1] # 前面所有列为输入 # 只测前1000行,防止超大 df = df.iloc[:1000] y_true = df[target_col].values y_pred = [] for _, row in df.iterrows(): try: y_pred.append(func(*(row[col] for col in input_cols))) except Exception as e: pytest.fail(f'Error in {formula_path} {csv_file} row: {e}') nmse = calc_nmse(y_true, y_pred) assert nmse < NMSE_THRESHOLD, f'{formula_path} {csv_file} nmse={nmse} >= {NMSE_THRESHOLD}'