Add e2e test harness for testing editor logic without Gio display

- internal/test/e2e/: FrameCapture, Harness, ElementAssertions, helpers
- internal/editor/logic.go: Add done channel and Done() method for graceful shutdown
- internal/editor/mock_setup.go: Mock filesystem for tests
- internal/browser/: Browser layout and search logic
- internal/io/: Worker pool for async tasks
- Update architecture docs and spec
This commit is contained in:
gmp
2026-05-31 08:56:30 -04:00
parent a1ef84609f
commit 6a43e3c0db
34 changed files with 8514 additions and 286 deletions
+429
View File
@@ -0,0 +1,429 @@
// Package mock provides a configurable mock filesystem for testing
// the IO worker pool without touching the real disk.
package mock
import (
"fmt"
"os"
"path/filepath"
"sync"
"time"
)
// File represents a file or directory in the mock filesystem.
type File struct {
Path string
Name string
Content []byte
ModTime time.Time
Size int64
IsDir bool
}
// DirEntry mimics fs.DirEntry behavior for the mock.
type DirEntry struct {
name string
isDir bool
modTime time.Time
size int64
}
func (d DirEntry) Name() string { return d.name }
func (d DirEntry) IsDir() bool { return d.isDir }
func (d DirEntry) Info() (os.FileInfo, error) {
return &mockFileInfo{name: d.name, isDir: d.isDir, modTime: d.modTime, size: d.size}, nil
}
// mockFileInfo implements os.FileInfo for the mock.
type mockFileInfo struct {
name string
isDir bool
modTime time.Time
size int64
}
func (fi *mockFileInfo) Name() string { return fi.name }
func (fi *mockFileInfo) Size() int64 { return fi.size }
func (fi *mockFileInfo) Mode() os.FileMode { return 0644 }
func (fi *mockFileInfo) ModTime() time.Time { return fi.modTime }
func (fi *mockFileInfo) IsDir() bool { return fi.isDir }
func (fi *mockFileInfo) Sys() any { return nil }
// FileChangeEvent represents an external filesystem change.
type FileChangeEvent struct {
Path string
EventType string // "Created", "Modified", "Deleted"
Time time.Time
}
// notifyEvent is a pending notification collected while holding the lock.
type notifyEvent struct {
path string
eventType string
}
// FileSystem is a thread-safe in-memory filesystem for testing.
type FileSystem struct {
mu sync.RWMutex
files map[string]*File // path -> file
delay time.Duration // uniform delay applied to all operations
changes chan FileChangeEvent // async change notifications (nil = no notifications)
}
// NewFileSystem creates an empty mock filesystem.
func NewFileSystem() *FileSystem {
return &FileSystem{
files: make(map[string]*File),
}
}
// SetDelay sets a uniform delay applied to all IO operations.
func (fs *FileSystem) SetDelay(d time.Duration) {
fs.mu.Lock()
defer fs.mu.Unlock()
fs.delay = d
}
// SetChangeEvents sets the channel for async change notifications.
// Pass nil to disable notifications.
func (fs *FileSystem) SetChangeEvents(ch chan FileChangeEvent) {
fs.mu.Lock()
defer fs.mu.Unlock()
fs.changes = ch
}
// sendNotifications sends any pending notification events.
// Caller must NOT hold the mutex.
func (fs *FileSystem) sendNotifications(events []notifyEvent) {
fs.mu.RLock()
ch := fs.changes
fs.mu.RUnlock()
if ch == nil {
return
}
for _, e := range events {
select {
case ch <- FileChangeEvent{
Path: e.path,
EventType: e.eventType,
Time: time.Now(),
}:
default:
// Drop event if channel is full (non-blocking)
}
}
}
// CreateFile creates a file with the given content at the specified path.
func (fs *FileSystem) CreateFile(path string, content []byte) error {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
name := filepath.Base(path)
now := time.Now()
f := &File{
Path: path,
Name: name,
Content: content,
ModTime: now,
Size: int64(len(content)),
IsDir: false,
}
fs.files[path] = f
// Collect notification while holding the lock
var events []notifyEvent
if fs.changes != nil {
events = append(events, notifyEvent{path, "Created"})
}
fs.mu.Unlock()
// Send notifications outside the lock (avoids deadlock)
fs.sendNotifications(events)
return nil
}
// ReadFile returns the content of a file at the given path.
func (fs *FileSystem) ReadFile(path string) ([]byte, error) {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
f, ok := fs.files[path]
if !ok {
fs.mu.Unlock()
return nil, fmt.Errorf("file not found: %s", path)
}
content := append([]byte(nil), f.Content...)
fs.mu.Unlock()
return content, nil
}
// WriteFile replaces the content of a file at the given path.
func (fs *FileSystem) WriteFile(path string, content []byte) error {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
f, ok := fs.files[path]
if !ok {
fs.mu.Unlock()
return fmt.Errorf("file not found: %s", path)
}
f.Content = content
f.Size = int64(len(content))
f.ModTime = time.Now()
var events []notifyEvent
if fs.changes != nil {
events = append(events, notifyEvent{path, "Modified"})
}
fs.mu.Unlock()
fs.sendNotifications(events)
return nil
}
// DeleteFile removes a file at the given path.
func (fs *FileSystem) DeleteFile(path string) error {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
if _, ok := fs.files[path]; !ok {
fs.mu.Unlock()
return fmt.Errorf("file not found: %s", path)
}
delete(fs.files, path)
var events []notifyEvent
if fs.changes != nil {
events = append(events, notifyEvent{path, "Deleted"})
}
fs.mu.Unlock()
fs.sendNotifications(events)
return nil
}
// CreateDir creates a directory at the given path.
func (fs *FileSystem) CreateDir(path string) error {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
name := filepath.Base(path)
f := &File{
Path: path,
Name: name,
ModTime: time.Now(),
IsDir: true,
}
fs.files[path] = f
var events []notifyEvent
if fs.changes != nil {
events = append(events, notifyEvent{path, "Created"})
}
fs.mu.Unlock()
fs.sendNotifications(events)
return nil
}
// ReadDir returns a list of entries in the given directory.
func (fs *FileSystem) ReadDir(path string) ([]DirEntry, error) {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
dirPath := filepath.Clean(path)
if _, ok := fs.files[dirPath]; !ok {
fs.mu.Unlock()
return nil, fmt.Errorf("directory not found: %s", path)
}
var entries []DirEntry
for _, f := range fs.files {
if f.Path == dirPath {
continue
}
parent := filepath.Dir(f.Path)
if parent == dirPath {
entries = append(entries, DirEntry{
name: f.Name,
isDir: f.IsDir,
modTime: f.ModTime,
size: f.Size,
})
}
}
// Sort by name
for i := 0; i < len(entries); i++ {
for j := i + 1; j < len(entries); j++ {
if entries[i].name > entries[j].name {
entries[i], entries[j] = entries[j], entries[i]
}
}
}
fs.mu.Unlock()
return entries, nil
}
// DirExists returns true if the path exists and is a directory.
func (fs *FileSystem) DirExists(path string) bool {
fs.mu.RLock()
defer fs.mu.RUnlock()
f, ok := fs.files[path]
return ok && f.IsDir
}
// FileExists returns true if the path exists and is a file.
func (fs *FileSystem) FileExists(path string) bool {
fs.mu.RLock()
defer fs.mu.RUnlock()
f, ok := fs.files[path]
return ok && !f.IsDir
}
// GetFile returns the file at the given path, or nil if not found.
func (fs *FileSystem) GetFile(path string) *File {
fs.mu.RLock()
defer fs.mu.RUnlock()
return fs.files[path]
}
// SetFileContent atomically replaces the content of an existing file.
func (fs *FileSystem) SetFileContent(path string, content []byte) {
fs.mu.Lock()
if fs.delay > 0 {
fs.mu.Unlock()
time.Sleep(fs.delay)
fs.mu.Lock()
}
f, ok := fs.files[path]
if !ok {
fs.mu.Unlock()
return
}
f.Content = content
f.Size = int64(len(content))
f.ModTime = time.Now()
var events []notifyEvent
if fs.changes != nil {
events = append(events, notifyEvent{path, "Modified"})
}
fs.mu.Unlock()
fs.sendNotifications(events)
}
// AddFile adds a file without triggering change notifications.
// Useful for pre-populating the filesystem before tests.
func (fs *FileSystem) AddFile(path string, content []byte, modTime time.Time) {
fs.mu.Lock()
defer fs.mu.Unlock()
name := filepath.Base(path)
f := &File{
Path: path,
Name: name,
Content: content,
ModTime: modTime,
Size: int64(len(content)),
IsDir: false,
}
fs.files[path] = f
}
// AddDir adds a directory without triggering change notifications.
func (fs *FileSystem) AddDir(path string, modTime time.Time) {
fs.mu.Lock()
defer fs.mu.Unlock()
name := filepath.Base(path)
f := &File{
Path: path,
Name: name,
ModTime: modTime,
IsDir: true,
}
fs.files[path] = f
}
// RemoveFile removes a file without triggering change notifications.
func (fs *FileSystem) RemoveFile(path string) {
fs.mu.Lock()
defer fs.mu.Unlock()
delete(fs.files, path)
}
// ListPaths returns all file paths in the filesystem, optionally filtered by prefix.
func (fs *FileSystem) ListPaths(prefix string) []string {
fs.mu.RLock()
defer fs.mu.RUnlock()
var paths []string
for path := range fs.files {
if prefix == "" || filepath.HasPrefix(path, prefix) {
paths = append(paths, path)
}
}
return paths
}
// Count returns the number of files and directories in the mock filesystem.
func (fs *FileSystem) Count() (files int, dirs int) {
fs.mu.RLock()
defer fs.mu.RUnlock()
for _, f := range fs.files {
if f.IsDir {
dirs++
} else {
files++
}
}
return
}
+311
View File
@@ -0,0 +1,311 @@
package mock
import (
"fmt"
"sync"
"testing"
"time"
)
func TestFileSystem_CreateFile(t *testing.T) {
fs := NewFileSystem()
content := []byte("hello world")
err := fs.CreateFile("/test/hello.txt", content)
if err != nil {
t.Fatalf("CreateFile failed: %v", err)
}
f := fs.GetFile("/test/hello.txt")
if f == nil {
t.Fatal("File not found after creation")
}
if string(f.Content) != "hello world" {
t.Errorf("Content = %q, want %q", string(f.Content), "hello world")
}
if f.Name != "hello.txt" {
t.Errorf("Name = %q, want %q", f.Name, "hello.txt")
}
if f.Size != int64(len(content)) {
t.Errorf("Size = %d, want %d", f.Size, len(content))
}
if f.IsDir {
t.Error("IsDir should be false for a file")
}
}
func TestFileSystem_ReadFile(t *testing.T) {
fs := NewFileSystem()
fs.CreateFile("/test/data.txt", []byte("data"))
content, err := fs.ReadFile("/test/data.txt")
if err != nil {
t.Fatalf("ReadFile failed: %v", err)
}
if string(content) != "data" {
t.Errorf("ReadFile returned %q, want %q", string(content), "data")
}
}
func TestFileSystem_ReadFile_NotFound(t *testing.T) {
fs := NewFileSystem()
_, err := fs.ReadFile("/nonexistent.txt")
if err == nil {
t.Fatal("Expected error for nonexistent file, got nil")
}
}
func TestFileSystem_WriteFile(t *testing.T) {
fs := NewFileSystem()
fs.CreateFile("/test/update.txt", []byte("original"))
err := fs.WriteFile("/test/update.txt", []byte("updated"))
if err != nil {
t.Fatalf("WriteFile failed: %v", err)
}
content, _ := fs.ReadFile("/test/update.txt")
if string(content) != "updated" {
t.Errorf("Content = %q, want %q", string(content), "updated")
}
}
func TestFileSystem_WriteFile_NotFound(t *testing.T) {
fs := NewFileSystem()
err := fs.WriteFile("/nonexistent.txt", []byte("data"))
if err == nil {
t.Fatal("Expected error for nonexistent file, got nil")
}
}
func TestFileSystem_DeleteFile(t *testing.T) {
fs := NewFileSystem()
fs.CreateFile("/test/delete.txt", []byte("to delete"))
err := fs.DeleteFile("/test/delete.txt")
if err != nil {
t.Fatalf("DeleteFile failed: %v", err)
}
if fs.FileExists("/test/delete.txt") {
t.Error("File should not exist after deletion")
}
}
func TestFileSystem_DeleteFile_NotFound(t *testing.T) {
fs := NewFileSystem()
err := fs.DeleteFile("/nonexistent.txt")
if err == nil {
t.Fatal("Expected error for nonexistent file, got nil")
}
}
func TestFileSystem_CreateDir(t *testing.T) {
fs := NewFileSystem()
err := fs.CreateDir("/test/dir")
if err != nil {
t.Fatalf("CreateDir failed: %v", err)
}
if !fs.DirExists("/test/dir") {
t.Error("Dir should exist after creation")
}
f := fs.GetFile("/test/dir")
if f == nil {
t.Fatal("Directory file not found")
}
if !f.IsDir {
t.Error("IsDir should be true for a directory")
}
if f.Name != "dir" {
t.Errorf("Name = %q, want %q", f.Name, "dir")
}
}
func TestFileSystem_ReadDir(t *testing.T) {
fs := NewFileSystem()
fs.CreateDir("/test/dir")
fs.CreateFile("/test/dir/a.txt", []byte("a"))
fs.CreateFile("/test/dir/b.txt", []byte("b"))
fs.CreateFile("/test/dir/c.txt", []byte("c"))
entries, err := fs.ReadDir("/test/dir")
if err != nil {
t.Fatalf("ReadDir failed: %v", err)
}
if len(entries) != 3 {
t.Fatalf("Expected 3 entries, got %d", len(entries))
}
// Check alphabetical order
if entries[0].Name() != "a.txt" {
t.Errorf("First entry = %q, want %q", entries[0].Name(), "a.txt")
}
if entries[1].Name() != "b.txt" {
t.Errorf("Second entry = %q, want %q", entries[1].Name(), "b.txt")
}
if entries[2].Name() != "c.txt" {
t.Errorf("Third entry = %q, want %q", entries[2].Name(), "c.txt")
}
}
func TestFileSystem_ReadDir_Empty(t *testing.T) {
fs := NewFileSystem()
fs.CreateDir("/test/empty")
entries, err := fs.ReadDir("/test/empty")
if err != nil {
t.Fatalf("ReadDir failed: %v", err)
}
if len(entries) != 0 {
t.Errorf("Expected 0 entries, got %d", len(entries))
}
}
func TestFileSystem_FileExists(t *testing.T) {
fs := NewFileSystem()
fs.CreateFile("/test/exist.txt", []byte("data"))
if !fs.FileExists("/test/exist.txt") {
t.Error("File should exist")
}
if fs.FileExists("/test/noexist.txt") {
t.Error("Nonexistent file should not exist")
}
}
func TestFileSystem_DirExists(t *testing.T) {
fs := NewFileSystem()
fs.CreateDir("/test/dir")
if !fs.DirExists("/test/dir") {
t.Error("Directory should exist")
}
if fs.DirExists("/test/noexist") {
t.Error("Nonexistent directory should not exist")
}
}
func TestFileSystem_Count(t *testing.T) {
fs := NewFileSystem()
fs.CreateFile("/test/a.txt", []byte("a"))
fs.CreateFile("/test/b.txt", []byte("b"))
fs.CreateDir("/test/dir")
files, dirs := fs.Count()
if files != 2 {
t.Errorf("Files = %d, want 2", files)
}
if dirs != 1 {
t.Errorf("Dirs = %d, want 1", dirs)
}
}
func TestFileSystem_SetDelay(t *testing.T) {
fs := NewFileSystem()
fs.SetDelay(50 * time.Millisecond)
start := time.Now()
fs.ReadFile("/nonexistent.txt") // Will fail but delay should still apply
elapsed := time.Since(start)
if elapsed < 40*time.Millisecond {
t.Errorf("Expected delay ~50ms, got %v", elapsed)
}
}
func TestFileSystem_SetChangeEvents(t *testing.T) {
fs := NewFileSystem()
ch := make(chan FileChangeEvent, 10)
fs.SetChangeEvents(ch)
fs.CreateFile("/test/notify.txt", []byte("data"))
select {
case event := <-ch:
if event.Path != "/test/notify.txt" {
t.Errorf("Event path = %q, want %q", event.Path, "/test/notify.txt")
}
if event.EventType != "Created" {
t.Errorf("Event type = %q, want %q", event.EventType, "Created")
}
case <-time.After(100 * time.Millisecond):
t.Fatal("Expected change event, got none")
}
}
func TestFileSystem_SetChangeEvents_NilChannel(t *testing.T) {
fs := NewFileSystem()
fs.SetChangeEvents(nil) // Disable notifications
// Should not panic
fs.CreateFile("/test/silent.txt", []byte("data"))
}
func TestFileSystem_AddFile(t *testing.T) {
fs := NewFileSystem()
modTime := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
fs.AddFile("/test/pre.txt", []byte("pre"), modTime)
f := fs.GetFile("/test/pre.txt")
if f == nil {
t.Fatal("File not found after AddFile")
}
if !f.ModTime.Equal(modTime) {
t.Errorf("ModTime = %v, want %v", f.ModTime, modTime)
}
}
func TestFileSystem_RemoveFile(t *testing.T) {
fs := NewFileSystem()
fs.AddFile("/test/remove.txt", []byte("data"), time.Now())
fs.RemoveFile("/test/remove.txt")
if fs.FileExists("/test/remove.txt") {
t.Error("File should not exist after RemoveFile")
}
}
func TestFileSystem_ListPaths(t *testing.T) {
fs := NewFileSystem()
fs.CreateFile("/test/a.txt", []byte("a"))
fs.CreateFile("/test/b.txt", []byte("b"))
fs.CreateFile("/other/c.txt", []byte("c"))
paths := fs.ListPaths("/test/")
if len(paths) != 2 {
t.Errorf("ListPaths returned %d paths, want 2", len(paths))
}
pathsAll := fs.ListPaths("")
if len(pathsAll) != 3 {
t.Errorf("ListPaths with empty prefix returned %d paths, want 3", len(pathsAll))
}
}
func TestFileSystem_ConcurrentAccess(t *testing.T) {
fs := NewFileSystem()
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func(n int) {
defer wg.Done()
path := fmt.Sprintf("/test/concurrent_%d.txt", n)
fs.CreateFile(path, []byte(fmt.Sprintf("content %d", n)))
fs.ReadFile(path)
fs.DeleteFile(path)
}(i)
}
wg.Wait()
}