Files
Reims-Go/pkg/drivertest/console.go
T

89 lines
2.9 KiB
Go

package drivertest
import (
"context"
"image/png"
"os"
"path/filepath"
"testing"
"unicode/utf8"
)
// CapConsole is the capability of drivers that serve their own console.
const CapConsole = "console"
// ConsolePointerRequest is one pointer action of the console contract.
type ConsolePointerRequest struct {
Action string
X, Y int
Width int
Height int
Button string
}
// ConsoleSuiteDriver is implemented by drivers that serve their own console.
// ConsoleScreenshot writes one PNG frame to path.
type ConsoleSuiteDriver interface {
ConsoleScreenshot(ctx context.Context, name, path string) error
ConsolePointer(ctx context.Context, name string, req ConsolePointerRequest) error
ConsoleKey(ctx context.Context, name, key string, modifiers []string) error
ConsoleType(ctx context.Context, name, text string) (int, error)
}
// runConsole checks the console of a running VM: a decodable frame, pointer,
// key and typing calls. A driver that implements the interface without
// declaring the capability must refuse every call.
func runConsole(t *testing.T, cfg *Config, cd ConsoleSuiteDriver) {
d, name := cfg.Driver, cfg.VMName
ctx := context.Background()
declared := has(d.Capabilities(), CapConsole)
if err := d.Create(ctx, cfg.createReq(d, name)); err != nil {
t.Fatalf("Create: %v", err)
}
if err := d.Start(ctx, name); err != nil {
t.Fatalf("Start: %v", err)
}
waitState(t, d, name, "running", cfg.Settle)
path := filepath.Join(t.TempDir(), "frame.png")
if !declared {
if err := cd.ConsoleScreenshot(ctx, name, path); err == nil {
t.Error("a console frame was served without the console capability")
}
if err := cd.ConsoleKey(ctx, name, "a", nil); err == nil {
t.Error("a key was pressed without the console capability")
}
return
}
if err := cd.ConsoleScreenshot(ctx, name, path); err != nil {
t.Fatalf("ConsoleScreenshot: %v", err)
}
f, err := os.Open(path)
if err != nil {
t.Fatalf("the frame file is missing: %v", err)
}
defer f.Close()
img, err := png.Decode(f)
if err != nil {
t.Fatalf("the frame is not a PNG: %v", err)
}
if b := img.Bounds(); b.Dx() < 1 || b.Dy() < 1 {
t.Errorf("the frame is %dx%d", b.Dx(), b.Dy())
}
if err := cd.ConsolePointer(ctx, name, ConsolePointerRequest{Action: "click", Button: "left"}); err != nil {
t.Errorf("ConsolePointer click: %v", err)
}
if err := cd.ConsolePointer(ctx, name, ConsolePointerRequest{Action: "move", X: 10, Y: 10, Width: 100, Height: 100}); err != nil {
t.Errorf("ConsolePointer move: %v", err)
}
if err := cd.ConsoleKey(ctx, name, "enter", nil); err != nil {
t.Errorf("ConsoleKey: %v", err)
}
const text = "hello"
if n, err := cd.ConsoleType(ctx, name, text); err != nil || n != utf8.RuneCountInString(text) {
t.Errorf("ConsoleType = %d, %v; want %d", n, err, utf8.RuneCountInString(text))
}
if err := cd.ConsoleKey(ctx, "no-such-vm-for-console", "a", nil); err == nil {
t.Error("a key was pressed on a VM that does not exist")
}
}