Files
Reims-Go/internal/guesttools/keymap_status_test.go
T

81 lines
2.4 KiB
Go

package guesttools
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestKeymapConfirmationFollowsGuestConnection(t *testing.T) {
for _, agentVersion := range []int{14, CurrentAgentVersion} {
t.Run(fmt.Sprintf("agent_%d", agentVersion), func(t *testing.T) {
srv := NewTransportServer(nil)
cfg := VMConfig{VMName: "mac", Token: "token", SharedDir: t.TempDir()}
srv.RegisterVM(cfg)
srv.SetKeymapCarrier(cfg.VMName, true)
request := func(handler http.HandlerFunc, method, path, body string) {
t.Helper()
req := httptest.NewRequest(method, path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+cfg.Token)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("%s %s: status %d: %s", method, path, w.Code, w.Body)
}
}
report := func(active bool) {
t.Helper()
body := fmt.Sprintf(`{"mount_mode":"sync","agent_version":%d,"keymap_active":%t}`, agentVersion, active)
request(srv.handleStatus, http.MethodPost, "/v1/status", body)
}
check := func(connected, active bool) {
t.Helper()
got := srv.Status(cfg.VMName, KeymapStatusMaxAge)
if got.Connected != connected || got.KeymapActive != active {
t.Fatalf("guest connected/keymap active = %t/%t, want %t/%t", got.Connected, got.KeymapActive, connected, active)
}
}
report(true)
check(true, true)
// The guest can still be handling files after its last status report expires.
srv.mu.Lock()
vm := srv.vms[normalizeVMRegistryKey(cfg.VMName)]
vm.lastStatus = time.Now().Add(-2 * KeymapStatusMaxAge)
vm.lastSeen = time.Now().Add(-KeymapStatusMaxAge / 2)
srv.mu.Unlock()
request(srv.handleListFiles, http.MethodGet, "/v1/files", "")
check(true, true)
// A resumed connection without a fresh report cannot restore the mapping.
srv.mu.Lock()
vm.lastSeen = time.Now().Add(-2 * KeymapStatusMaxAge)
srv.mu.Unlock()
check(false, false)
request(srv.handleConfig, http.MethodGet, "/v1/config", "")
check(true, false)
report(true)
check(true, true)
report(false)
check(true, false)
report(true)
srv.SetKeymapCarrier(cfg.VMName, false)
srv.SetKeymapCarrier(cfg.VMName, true)
check(true, false)
report(true)
cfg.Token = "replacement"
srv.RegisterVM(cfg)
request(srv.handleConfig, http.MethodGet, "/v1/config", "")
check(true, false)
report(true)
check(true, true)
})
}
}