fix(go): avoid gb32960 decimal float tails

This commit is contained in:
lingniu
2026-07-03 14:47:11 +08:00
parent 96e9382d73
commit a0a4997e79
2 changed files with 122 additions and 49 deletions

View File

@@ -2,8 +2,10 @@ package gb32960
import (
"encoding/hex"
"encoding/json"
"fmt"
"math"
"strings"
"testing"
"lingniu-vehicle-ingest/go/vehicle-gateway/internal/envelope"
@@ -213,6 +215,54 @@ func TestParseFrameKeepsParsingRealFuelCellReportUntilUnknownExtension(t *testin
}
}
func TestScaledDecimalFieldsDoNotLeakBinaryFloatTails(t *testing.T) {
unit := parseDriveMotorData([]byte{
0x01,
0x01,
0x02,
0x5d,
0x6c, 0xc6,
0x4e, 0x20,
0x64,
0x15, 0xb8,
0x27, 0x6e, // 10094 -> 9.4A after -1000 offset.
})
data, err := json.Marshal(unit)
if err != nil {
t.Fatal(err)
}
text := string(data)
if !strings.Contains(text, `"controller_current_a":9.4`) {
t.Fatalf("controller_current_a should render as 9.4 without float tail: %s", text)
}
if strings.Contains(text, "999999") || strings.Contains(text, "000000000000") {
t.Fatalf("scaled decimal field leaked binary float tail: %s", text)
}
aux := parseGdFCAuxiliaryData([]byte{
0x01,
0x01, 0x74,
0x00, 0x05,
0xff, 0xff,
0x00, 0x05,
0x01, 0x74,
0xff, 0xff,
0x00, 0x05,
0x00, 0x84, // 132 -> 13.2V.
})
data, err = json.Marshal(aux)
if err != nil {
t.Fatal(err)
}
text = string(data)
if !strings.Contains(text, `"low_voltage_battery_voltage_v":13.2`) {
t.Fatalf("low voltage should render as 13.2 without float tail: %s", text)
}
if strings.Contains(text, "13.200000000000") {
t.Fatalf("auxiliary scaled decimal leaked binary float tail: %s", text)
}
}
func assertFloatField(t *testing.T, env envelope.FrameEnvelope, key string, want float64) {
t.Helper()
got, ok := env.Fields[key].(float64)