test_v10.py 2.87 KB
"""v10 新增的几块纯逻辑:公式编译成 SQL、一次请求内的缓存、模型思考开关。"""
from __future__ import annotations

import pytest

from app.core import reqcache
from app.kernel import rules


def _sql(expr: str) -> str:
    return rules.to_sql(expr, lambda n: f"t.`{n}`", lambda o, a: f"{o}.`{a}`")


def test_公式编译成SQL_算术与比较():
    s = _sql("on_hand - reserved + in_transit")
    assert "t.`on_hand`" in s and "t.`reserved`" in s and "t.`in_transit`" in s
    assert "<" in _sql("available < order_point")


def test_公式编译成SQL_逻辑与条件():
    s = _sql("overstock and region_share > 0.5")
    assert " AND " in s.upper()
    s = _sql("0 if kind == '常规' else 30")
    assert "CASE" in s.upper() and "'常规'" in s


def test_公式编译成SQL_取关联对象的属性():
    assert "配件.`dealer_price`" in _sql("on_hand * 配件.dealer_price")


def test_公式编译成SQL_字符串里的引号被转义():
    assert "''" in _sql("name == \"a'b\"")


def test_公式编译成SQL_不认识的写法报错():
    with pytest.raises(rules.RuleError):
        _sql("__import__('os')")
    with pytest.raises(rules.RuleError):
        rules.to_sql("x + 1", lambda n: (_ for _ in ()).throw(rules.RuleError(f"没有 {n}")), lambda o, a: "")


def test_请求内缓存_同参数只算一次_返回的是副本():
    calls = []

    @reqcache.per_request
    def load(k):
        calls.append(k)
        return {"k": k, "items": [1]}

    load("a"); load("a")
    assert calls == ["a", "a"], "请求之外不缓存"
    tok = reqcache.begin()
    try:
        calls.clear()
        r1 = load("a")
        r1["items"].append(2)          # 调用方改了拿到的结果
        r2 = load("a")
        assert calls == ["a"] and r2["items"] == [1]
        reqcache.clear()               # 有写操作时会被清空
        load("a")
        assert calls == ["a", "a"]
    finally:
        reqcache.end(tok)


def test_请求内缓存_参数不能当键时直接算():
    @reqcache.per_request
    def total(xs):
        return sum(xs)

    tok = reqcache.begin()
    try:
        assert total([1, 2]) == 3 and total([1, 2]) == 3
    finally:
        reqcache.end(tok)


def test_模型思考开关(monkeypatch):
    from app.core import db, llm
    from app.governance import llmlog
    mode = {"v": "auto"}
    monkeypatch.setattr(db, "get_config", lambda k, d=None: mode["v"] if k == "LLM_THINKING" else "")
    with llmlog.feature("modeling_check"):
        assert llm._thinking() == {"enable_thinking": False}    # 有校验兜底的小步骤(对账、按错误改):不思考
    with llmlog.feature("ask"):
        assert llm._thinking() == {}                            # 回答问题:思考
    mode["v"] = "off"
    with llmlog.feature("ask"):
        assert llm._thinking() == {"enable_thinking": False}
    mode["v"] = "on"
    assert llm._thinking() == {}