hyapp-server/server/admin/internal/modules/dashboard/aslan_mongo_dashboard_test.go
2026-07-03 21:03:23 +08:00

59 lines
2.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package dashboard
import (
"testing"
"go.mongodb.org/mongo-driver/v2/bson"
)
// 复合 $group 的 _id 子文档经 driver 解码进 bson.M 后,嵌套值默认是 bson.D 而不是 bson.M
// 这个测试锁死我们对两种形态的兼容,防止聚合行被静默丢弃(表现为"成功但全零")。
func TestAslanMongoDayCountryHandlesDecodedShapes(t *testing.T) {
raw, err := bson.Marshal(bson.M{"_id": bson.M{"day": "2026-07-02", "country": "sa"}, "amount": int64(5)})
if err != nil {
t.Fatalf("marshal fixture: %v", err)
}
row := bson.M{}
if err := bson.Unmarshal(raw, &row); err != nil {
t.Fatalf("unmarshal fixture: %v", err)
}
if _, isM := row["_id"].(bson.M); isM {
t.Log("driver decoded nested document as bson.M")
} else if _, isD := row["_id"].(bson.D); isD {
t.Log("driver decoded nested document as bson.D (must be supported)")
} else {
t.Fatalf("unexpected nested _id type %T", row["_id"])
}
day, country := aslanMongoDayCountry(row["_id"])
if day != "2026-07-02" || country != "SA" {
t.Fatalf("expected day/country from decoded _id, got %q/%q", day, country)
}
// 直接构造 bson.D 与 bson.M 两种形态都必须可读。
for _, value := range []any{
bson.D{{Key: "day", Value: "2026-07-01"}, {Key: "country", Value: "eg"}},
bson.M{"day": "2026-07-01", "country": "eg"},
} {
day, country := aslanMongoDayCountry(value)
if day != "2026-07-01" || country != "EG" {
t.Fatalf("expected 2026-07-01/EG for %T, got %q/%q", value, day, country)
}
}
}
func TestAslanMongoDocumentConversion(t *testing.T) {
if doc := aslanMongoDocument(bson.D{{Key: "day", Value: "2026-07-02"}, {Key: "type", Value: int32(1)}}); doc == nil || doc["day"] != "2026-07-02" {
t.Fatalf("bson.D conversion failed: %v", doc)
}
if doc := aslanMongoDocument(bson.M{"user": int64(7)}); doc == nil || doc["user"] != int64(7) {
t.Fatalf("bson.M passthrough failed: %v", doc)
}
if doc := aslanMongoDocument(nil); doc != nil {
t.Fatalf("nil should convert to nil, got %v", doc)
}
if doc := aslanMongoDocument("scalar"); doc != nil {
t.Fatalf("scalar should convert to nil, got %v", doc)
}
}