goaidb/protocol/bson_test.go

105 lines
2.6 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 protocol
import (
"strings"
"testing"
)
func TestParseBSON_EmptyDocument(t *testing.T) {
// 构造最小有效BSON文档仅包含长度和结束符
data := []byte{
5, 0, 0, 0, // 文档长度=5字节
0x00, // 结束符
}
result, err := ParseBSON(data)
if err != nil {
t.Fatalf("ParseBSON failed: %v", err)
}
if len(result) != 0 {
t.Errorf("Expected empty document, got %d elements", len(result))
}
}
func TestParseBSON_Int32(t *testing.T) {
// 构造包含Int32字段的BSON文档
data := []byte{
9, 0, 0, 0, // 文档长度=9字节
0x10, // Int32类型
't', 'e', 's', 't', 0x00, // 键名"test"
0x12, 0x34, 0x00, 0x00, // 值=0x00003412 (小端序)
0x00, // 结束符
}
result, err := ParseBSON(data)
if err != nil {
t.Fatalf("ParseBSON failed: %v", err)
}
value, ok := result["test"]
if !ok {
t.Error("Expected key 'test' not found")
return
}
if intValue, ok := value.(int32); !ok || intValue != 0x00003412 {
t.Errorf("Expected Int32 0x00003412, got %v (%T)", value, value)
}
}
func TestParseBSON_String(t *testing.T) {
// 构造包含字符串字段的BSON文档
data := []byte{
16, 0, 0, 0, // 文档长度=22字节
0x02, // String类型
'n', 'a', 'm', 'e', 0x00, // 键名"name"
5, 0, 0, 0, // 字符串长度=7字节含终止符
'h', 'e', 'l', 'l', 'o', 0x00, // 字符串内容
0x00, // 结束符
}
result, err := ParseBSON(data)
if err != nil {
t.Fatalf("ParseBSON failed: %v", err)
}
value, ok := result["name"]
if !ok {
t.Error("Expected key 'name' not found")
return
}
if strValue, ok := value.(string); !ok || strValue != "hello" {
t.Errorf("Expected string 'hello', got %q (%T)", value, value)
}
}
func TestParseBSON_ErrorCases(t *testing.T) {
// 测试数据过短的情况
shortData := []byte{4, 0, 0, 0} // 长度为4字节的文档仅包含长度字段
_, err := ParseBSON(shortData)
if err == nil {
t.Error("Expected error for short data")
}
// 测试无效元素类型
invalidTypeData := []byte{
6, 0, 0, 0, // 文档长度=6字节
0xFF, // 无效元素类型
'k', 'e', 'y', 0x00, // 键名"key"
0x00, // 结束符
}
_, err = ParseBSON(invalidTypeData)
if err == nil {
t.Error("Expected error for invalid element type")
} else if !containsError(err, "unsupported BSON element") {
t.Errorf("Expected unsupported element type error, got %v", err)
}
}
// Helper function to check if error message contains expected text
func containsError(err error, expected string) bool {
return err != nil && len(err.Error()) >= len(expected) && strings.Contains(err.Error(), expected)
}