| 7 | ) |
| 8 | |
| 9 | func TestStateBackend(t *testing.T) { |
| 10 | ctx := context.Background() |
| 11 | backend := NewStateBackend() |
| 12 | |
| 13 | t.Run("Write and Read", func(t *testing.T) { |
| 14 | content := "line1\nline2\nline3" |
| 15 | result, err := backend.Write(ctx, "/test.txt", content) |
| 16 | if err != nil { |
| 17 | t.Fatalf("Write failed: %v", err) |
| 18 | } |
| 19 | |
| 20 | if result.Error != "" { |
| 21 | t.Fatalf("Write should succeed, got error: %s", result.Error) |
| 22 | } |
| 23 | |
| 24 | if result.BytesWritten != int64(len(content)) { |
| 25 | t.Errorf("Expected bytes written %d, got %d", len(content), result.BytesWritten) |
| 26 | } |
| 27 | |
| 28 | // 读取全部内容 |
| 29 | readContent, err := backend.Read(ctx, "/test.txt", 0, 0) |
| 30 | if err != nil { |
| 31 | t.Fatalf("Read failed: %v", err) |
| 32 | } |
| 33 | |
| 34 | if readContent != content { |
| 35 | t.Errorf("Expected content %q, got %q", content, readContent) |
| 36 | } |
| 37 | }) |
| 38 | |
| 39 | t.Run("Read with offset and limit", func(t *testing.T) { |
| 40 | content := "line1\nline2\nline3\nline4\nline5" |
| 41 | if _, err := backend.Write(ctx, "/test2.txt", content); err != nil { |
| 42 | t.Fatalf("Write failed: %v", err) |
| 43 | } |
| 44 | |
| 45 | // 读取第2-3行 (offset=1, limit=2) |
| 46 | readContent, err := backend.Read(ctx, "/test2.txt", 1, 2) |
| 47 | if err != nil { |
| 48 | t.Fatalf("Read failed: %v", err) |
| 49 | } |
| 50 | |
| 51 | expected := "line2\nline3" |
| 52 | if readContent != expected { |
| 53 | t.Errorf("Expected content %q, got %q", expected, readContent) |
| 54 | } |
| 55 | }) |
| 56 | |
| 57 | t.Run("Edit - Replace first", func(t *testing.T) { |
| 58 | content := "hello world\nhello again\nhello there" |
| 59 | if _, err := backend.Write(ctx, "/test3.txt", content); err != nil { |
| 60 | t.Fatalf("Write failed: %v", err) |
| 61 | } |
| 62 | |
| 63 | result, err := backend.Edit(ctx, "/test3.txt", "hello", "hi", false) |
| 64 | if err != nil { |
| 65 | t.Fatalf("Edit failed: %v", err) |
| 66 | } |