feat(server-go): 风险评分引擎(#9,公式/分级/阶段与环境系数)接入巡检

This commit is contained in:
weijuesen
2026-08-12 17:02:06 +08:00
parent 971e1546f0
commit 93301f0bf3
3 changed files with 209 additions and 0 deletions
+85
View File
@@ -0,0 +1,85 @@
package service
import "testing"
func f(v float64) *float64 { return &v }
func TestComputeRiskScoreWeights(t *testing.T) {
// 全 10.5*1 + 0.2*1 + 0.15*1 + 0.15*1 = 1 → 100
if s := ComputeRiskScore(RiskInput{AI: 1, Env: 1, Stage: 1, Uniformity: 1}); s != 100 {
t.Errorf("全 1 应得 100,实际 %.2f", s)
}
// 仅 AI 置信度 10.5*1 = 0.5 → 50
if s := ComputeRiskScore(RiskInput{AI: 1}); s != 50 {
t.Errorf("仅 AI=1 应得 50,实际 %.2f", s)
}
// 0.5*0.8 + 0.2*0.5 = 0.5
if s := ComputeRiskScore(RiskInput{AI: 0.8, Env: 0.5}); s != 50 {
t.Errorf("0.8/0.5 应得 50,实际 %.2f", s)
}
}
func TestComputeRiskScoreClamps(t *testing.T) {
if s := ComputeRiskScore(RiskInput{AI: 2, Env: 2, Stage: 2, Uniformity: 2}); s > 100 {
t.Errorf("应钳制到 100,实际 %.2f", s)
}
if s := ComputeRiskScore(RiskInput{AI: -1}); s < 0 {
t.Errorf("应钳制到 0,实际 %.2f", s)
}
}
func TestRiskLevelBoundaries(t *testing.T) {
cases := map[float64]string{
0: "green",
30: "green",
30.5: "yellow",
60: "yellow",
61: "orange",
80: "orange",
81: "red",
100: "red",
}
for score, want := range cases {
if got := RiskLevel(score); got != want {
t.Errorf("RiskLevel(%.1f) = %s, want %s", score, got, want)
}
}
}
func TestStageCoefficientMapping(t *testing.T) {
if StageCoefficient("pupa") <= 0 {
t.Error("蛹期应有风险系数")
}
if StageCoefficient("") != 0 {
t.Error("空阶段应为 0")
}
if StageCoefficient("unknown") != 0 {
t.Error("未知阶段应为 0")
}
if StageCoefficient("pupa") <= StageCoefficient("egg") {
t.Error("蛹期系数应高于卵期")
}
}
func TestEnvCoefficientRules(t *testing.T) {
// 湿度 >=80 → 高(真菌病)
if c := EnvCoefficient(f(25), f(85)); c < 0.7 {
t.Errorf("湿度 85 应 ≥0.7,实际 %.2f", c)
}
// 湿度 75-80 → 中
if c := EnvCoefficient(f(25), f(78)); c < 0.3 {
t.Errorf("湿度 78 应 ≥0.3,实际 %.2f", c)
}
// 温度突变 >30 → 中(核型多角体病诱发)
if c := EnvCoefficient(f(32), f(60)); c < 0.3 {
t.Errorf("温度 32 应 ≥0.3,实际 %.2f", c)
}
// 舒适环境 → 0
if c := EnvCoefficient(f(25), f(60)); c != 0 {
t.Errorf("舒适环境应为 0,实际 %.2f", c)
}
// 缺数据 → 0
if c := EnvCoefficient(nil, nil); c != 0 {
t.Errorf("无数据应为 0,实际 %.2f", c)
}
}