package document import ( "fmt" "os" "sync" "testing" ) // 测试用结构体 type TestDoc struct { ID string `bson:"_id"` Name string `bson:"name"` Age int `bson:"age"` } func TestDocumentStore(t *testing.T) { // 测试目录 dir := "./testdb" defer os.RemoveAll(dir) // 初始化文档存储 ds, err := NewDocumentStore(dir) if err != nil { t.Fatalf("Failed to create document store: %v", err) } defer ds.storage.Close() // 测试文档ID和数据 docID := "doc123" doc := map[string]interface{}{ "_id": docID, "name": "Test Document", } // 测试基本操作(使用默认collection) collection := "test_collection" if err := ds.StoreDocument(collection, docID, doc); err != nil { t.Errorf("StoreDocument failed: %v", err) } // 验证存储结果 var result map[string]interface{} if err := ds.GetDocument(collection, docID, &result); err != nil { t.Errorf("GetDocument failed: %v", err) } // 验证删除功能 if err := ds.DeleteDocument(collection, docID); err != nil { t.Errorf("DeleteDocument failed: %v", err) } // 删除后验证 if err := ds.GetDocument(collection, docID, &result); err == nil { t.Error("Expected error after DeleteDocument") } } func TestErrorHandling(t *testing.T) { // 测试无效文档(包含不支持的类型) dir := "./testdb_error" defer os.RemoveAll(dir) ds, _ := NewDocumentStore(dir) // 测试存储非map文档 invalidDoc := struct { F func() }{} if err := ds.StoreDocument("invalid", "doc1", invalidDoc); err == nil { t.Error("Expected error for invalid document") } // 测试存储nil文档 if err := ds.StoreDocument("invalid", "doc2", nil); err == nil { t.Error("Expected error for nil document") } } func TestConcurrentAccess(t *testing.T) { // 测试并发写入同一ID dir := "./testdb_concurrent" defer os.RemoveAll(dir) numGoroutines := 10 var wg sync.WaitGroup key := "concurrent_test" ds, err := NewDocumentStore(dir) if err != nil { t.Fatalf("Failed to create document store: %v", err) } defer ds.storage.Close() wg.Add(numGoroutines) for i := 0; i < numGoroutines; i++ { go func(i int) { defer wg.Done() testDoc := map[string]interface{}{ "_id": key, "name": fmt.Sprintf("Test%d", i), } err := ds.StoreDocument(key, fmt.Sprintf("doc%d", i), testDoc) if err != nil { t.Errorf("StoreDocument failed: %v", err) } }(i) } wg.Wait() // 验证最终值是否为最后一个写入 var result map[string]interface{} if err := ds.GetDocument(key, "doc9", &result); err != nil { t.Errorf("GetDocument failed: %v", err) } }