Files
Reims-Go/internal/console/manager_test.go
T

104 lines
2.5 KiB
Go

package console
import (
"context"
"encoding/json"
"sync"
"sync/atomic"
"testing"
"time"
)
type fakeQMPSession struct {
mu sync.Mutex
commands []string
closed atomic.Bool
onExec func(cmd string)
}
func (f *fakeQMPSession) Execute(cmd string, _ any) error {
f.mu.Lock()
f.commands = append(f.commands, cmd)
f.mu.Unlock()
if f.onExec != nil {
f.onExec(cmd)
}
return nil
}
func (f *fakeQMPSession) Query(cmd string, _ any) (json.RawMessage, error) {
return json.RawMessage(`[]`), f.Execute(cmd, nil)
}
func (f *fakeQMPSession) Screendump(string) (string, error) {
return "ppm", f.Execute("screendump", nil)
}
func (f *fakeQMPSession) Close() error {
f.closed.Store(true)
return nil
}
func TestManagerReleasesConnectionAfterOperation(t *testing.T) {
m := NewManager()
var sessions []*fakeQMPSession
m.dial = func(context.Context, string) (qmpSession, error) {
s := &fakeQMPSession{}
sessions = append(sessions, s)
return s, nil
}
dir := t.TempDir()
if _, err := m.Screendump(context.Background(), dir, "frame.ppm"); err != nil {
t.Fatalf("Screendump: %v", err)
}
if len(sessions) != 1 || !sessions[0].closed.Load() {
t.Fatalf("expected QMP connection to close immediately after Screendump, sessions=%d closed=%v",
len(sessions), len(sessions) > 0 && sessions[0].closed.Load())
}
if err := m.SendAbsoluteClickAndPaste(context.Background(), dir, 0.5, 0.5, false, "meta_l", 5*time.Millisecond); err != nil {
t.Fatalf("SendAbsoluteClickAndPaste: %v", err)
}
if len(sessions) != 2 || !sessions[1].closed.Load() {
t.Fatalf("expected second QMP connection to close immediately after SendAbsoluteClickAndPaste")
}
}
func TestManagerSerializesSameVMOperations(t *testing.T) {
m := NewManager()
var active atomic.Int32
var maxActive atomic.Int32
m.dial = func(context.Context, string) (qmpSession, error) {
return &fakeQMPSession{
onExec: func(string) {
cur := active.Add(1)
for {
prev := maxActive.Load()
if cur <= prev || maxActive.CompareAndSwap(prev, cur) {
break
}
}
time.Sleep(15 * time.Millisecond)
active.Add(-1)
},
}, nil
}
dir := t.TempDir()
var wg sync.WaitGroup
for range 4 {
wg.Add(1)
go func() {
defer wg.Done()
if _, err := m.Screendump(context.Background(), dir, "frame.ppm"); err != nil {
t.Errorf("Screendump: %v", err)
}
}()
}
wg.Wait()
if got := maxActive.Load(); got != 1 {
t.Fatalf("expected max 1 concurrent QMP operation per VM, got %d", got)
}
}