_verify_api.py 5.34 KB
import sys, types, datetime
from decimal import Decimal

def stub(name):
    m = types.ModuleType(name); sys.modules[name] = m; return m

# requests 桩(indicator_client 仅用 requests.post,验证时由 fake_post 接管)
req = stub('requests'); req.post = lambda *a, **k: None; req.Timeout = Exception; req.ConnectionError = Exception
sys.modules['requests'] = req

# config
cfg = stub('config')
cfg.Config = type('C', (), {'INDICATOR_API_URL':'http://dc.glsx.com.cn/data',
                            'INDICATOR_API_TIMEOUT':10, 'INDICATOR_API_RETRY':1})()

# ================= Test A: indicator_client bizs 序列化 =================
import importlib.util
spec = importlib.util.spec_from_file_location('indicator_client', r'F:/data-report/data-process/indicator_client.py')
ic = importlib.util.module_from_spec(spec); spec.loader.exec_module(ic)

captured = {}
class FakeResp:
    status_code = 200
    def json(self): return {'code':200, 'content':[]}
def fake_post(url, json=None, timeout=None):
    captured['url'] = url; captured['json'] = json; return FakeResp()
ic.requests.post = fake_post

client = ic.IndicatorClient()
client.fetch('2026-08-01', '2026-08-31', [1, 3], ['A036'])
print("A1 payload(bizs多值):", captured['json'])
assert captured['json'].get('bizs') == '1,3'; assert 'biz' not in captured['json']
client.fetch('2026-08-01', '2026-08-31', 2, ['A036'])
print("A2 payload(biz单值):", captured['json'])
assert captured['json'].get('biz') == 2; assert 'bizs' not in captured['json']
print(">>> Test A 通过:bizs 多值='1,3',单值 biz=2")

# ================= Test B: output_value_processor G/I/L 计算 =================
models = stub('models')
class FakeQuery:
    def filter_by(self, **k): return self
    def delete(self): return 0
    def order_by(self, *a): return self
    def all(self): return []
class SaasBusinessAchievement:
    query = FakeQuery()
    def __init__(self, **kw): self.__dict__.update(kw)
models.SaasBusinessAchievement = SaasBusinessAchievement
models.DataProcessTask = object
class FakeSession:
    def __init__(self): self.added=[]
    def add_all(self, rows): self.added.extend(rows)
    def flush(self): pass
    def commit(self): pass
    def rollback(self): pass
class FakeDB: session = FakeSession()
models.db = FakeDB()
oss = stub('oss_utils'); oss.upload_file = lambda p,k: 'http://fake/'+k
ru = stub('report_utils')
ru.mark_task_failed = lambda *a,**k: None
ru.cleanup_tmp_dir = lambda *a,**k: None
ru.download_all_files = lambda *a,**k: {'SAAS门店预算分解表':'x', '关系表':'y'}
ru.parse_operator_relation = lambda *a,**k: {}
ru.safe_div_pct_decimal = lambda n,d: (round(n/d*100,2) if (n is not None and d) else None)

MOCK_213 = [
    {'region_operator':'华东','store_name':'郑州鸿启汽车贸易有限公司','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('100000'),'biz_type':'2.1'},
    {'region_operator':'华东','store_name':'新乡市天驰汽车销售有限公司','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('80000'),'biz_type':'2.1'},
    {'region_operator':'华东','store_name':'上海XX店','resident_type':'服务商','store_kind':'新增','budget_corrected':Decimal('20000'),'biz_type':'2.3'},
    {'region_operator':'华北','store_name':'北京YY店','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('60000'),'biz_type':'2.1'},
]
MOCK_11 = [
    {'region_operator':'华南','store_name':'广州ZZ店','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('50000'),'biz_type':'1.1'},
    {'region_operator':'华南','store_name':'深圳WW店','resident_type':'服务商','store_kind':'新增','budget_corrected':Decimal('10000'),'biz_type':'1.1'},
]
ru.parse_saas_achieve_details = lambda p,k,i: (MOCK_11 if '轻改' in k else MOCK_213)
API_DATA = {
    '郑州鸿启汽车贸易有限公司': {'A036': Decimal('12225')},
    '新乡市天驰汽车销售有限公司': {'A036': Decimal('3945')},
    '上海XX店': {'A036': Decimal('555')},
    # '北京YY店' 故意不返回 → 华北组应落 NULL
    '广州ZZ店': {'A036': Decimal('888')},
    '深圳WW店': {'A036': Decimal('999')},
}
def fake_fetch(start_str, end_str, biz_code, item_codes):
    assert biz_code in ([1,3], [2]), f"biz_code 错误: {biz_code}"
    return API_DATA
ru.fetch_indicator_data = fake_fetch

spec2 = importlib.util.spec_from_file_location('ovp', r'F:/data-report/data-process/output_value_processor.py')
ovp = importlib.util.module_from_spec(spec2); spec.loader.exec_module(ovp)

class FakeTask:
    id=777; month='2026-08'
    period_start=datetime.date(2026,8,1); period_end=datetime.date(2026,8,31)

proc = ovp.OutputValueProcessor()
proc._process_output_value(FakeTask())

rows = models.db.session.added
print(f"\n>>> 入库 {len(rows)} 行")
ok = True
for r in rows:
    g=r.daily_new_gmv; i=r.existing_actual; l=r.new_actual
    print(f"  {r.business_type}/{r.region_operator:6s} G={g} I={i} L={l}")
    if r.region_operator=='华东':
        ok = ok and (i==Decimal('16170') and l==Decimal('555') and g==Decimal('16725'))
    elif r.region_operator=='华北':
        ok = ok and (i is None and l is None and g is None)
    elif r.region_operator=='华南':
        ok = ok and (i==Decimal('888') and l==Decimal('999') and g==Decimal('1887'))
assert ok, "G/I/L 数值不符预期"
print(">>> Test B 通过:store_name 匹配、G=I+L、未匹配门店(华北)落 NULL")