add error and cocurrent test

This commit is contained in:
kingecg 2025-06-07 18:13:29 +08:00
parent 35c27f7cc7
commit 8ab875003a
1 changed files with 52 additions and 1 deletions

View File

@ -1,7 +1,9 @@
package document
import (
"fmt"
"os"
"sync"
"testing"
)
@ -57,3 +59,52 @@ func TestDocumentStore(t *testing.T) {
t.Errorf("Expected error after DeleteDocument")
}
}
func TestErrorHandling(t *testing.T) {
// 测试无效文档(包含不支持的类型)
dir := "./testdb_error"
defer os.RemoveAll(dir)
ds, _ := NewDocumentStore(dir)
invalidDoc := struct {
F func()
}{}
if err := ds.StoreDocument("invalid", invalidDoc); err == nil {
t.Error("Expected error for invalid document")
}
}
func TestConcurrentAccess(t *testing.T) {
// 测试并发写入同一ID
dir := "./testdb_concurrent"
defer os.RemoveAll(dir)
numGoroutines := 10
var wg sync.WaitGroup
key := "concurrent_test"
ds, _ := NewDocumentStore(dir)
wg.Add(numGoroutines)
for i := 0; i < numGoroutines; i++ {
go func(i int) {
defer wg.Done()
testDoc := TestDoc{
ID: key,
Name: fmt.Sprintf("Test%d", i),
}
err := ds.StoreDocument(key, testDoc)
if err != nil {
t.Errorf("StoreDocument failed: %v", err)
}
}(i)
}
wg.Wait()
// 验证最终值是否为最后一个写入
var result TestDoc
if err := ds.GetDocument(key, &result); err != nil {
t.Errorf("GetDocument failed: %v", err)
}
}