goaidb/protocol/parser_test.go

66 lines
1.5 KiB
Go
Raw Normal View History

2025-06-06 22:12:24 +08:00
package protocol
import (
"testing"
)
func TestParseUpdate(t *testing.T) {
// 构造测试数据最小有效Update消息
data := []byte{
// Header
16, 0, 0, 0, // MessageLength (16 bytes)
1, 0, 0, 0, // RequestID
0, 0, 0, 0, // ResponseTo
209, 7, 0, 0, // OpCode (OP_UPDATE)
// UpdateFlags (Upsert=1)
1, 0, 0, 0,
// DatabaseName "test\x00collection\x00"
't', 'e', 's', 't', 0,
// CollectionName "coll\x00"
'c', 'o', 'l', 'l', 0,
// Query文档最小BSON文档
5, 0, 0, 0, 0, // BSON长度 + 空文档
// Update文档
5, 0, 0, 0, 0, // BSON长度 + 空文档
}
msg, err := ParseMessage(data)
if err != nil {
t.Fatalf("ParseMessage failed: %v", err)
}
if msg.OpCode != OP_UPDATE {
t.Errorf("Expected OP_UPDATE, got %d", msg.OpCode)
}
updateMsg, ok := msg.Body.(*UpdateMessage)
if !ok {
t.Fatalf("Expected UpdateMessage, got %T", msg.Body)
}
if updateMsg.Flags != Upsert {
t.Errorf("Expected Upsert flag, got %v", updateMsg.Flags)
}
if updateMsg.DatabaseName != "test" {
t.Errorf("Expected database 'test', got '%s'", updateMsg.DatabaseName)
}
if updateMsg.CollName != "coll" {
t.Errorf("Expected collection 'coll', got '%s'", updateMsg.CollName)
}
}
func TestParseInvalidUpdate(t *testing.T) {
// 测试短数据包
shortData := []byte{1, 0, 0, 0} // 长度不足4字节
_, err := parseUpdate(shortData) // 使用空标识符丢弃未使用的返回值
if err == nil {
t.Error("Expected error for short data")
}
}