package vmstart import ( "context" "github.com/Nwflower/reims-go/internal/host" "sync/atomic" "testing" "time" ) func TestWaitForCommitMemoryImmediateWhenSufficient(t *testing.T) { waited := false ok := waitForCommitMemory( context.Background(), "8G", time.Second, 5*time.Millisecond, func() (float64, bool) { return 11.7, true }, func(float64, float64) { waited = true }, ) if !ok { t.Fatal("want true when commit memory is already sufficient") } if waited { t.Fatal("onWait should not be called when memory is already sufficient") } } func TestWaitForCommitMemoryReclaimsAfterExit(t *testing.T) { var calls atomic.Int32 samples := []float64{6.7, 6.7, 11.7} var waitCalls int var gotAvail, gotNeed float64 ok := waitForCommitMemory( context.Background(), "8G", time.Second, 5*time.Millisecond, func() (float64, bool) { idx := int(calls.Add(1)) - 1 if idx >= len(samples) { idx = len(samples) - 1 } return samples[idx], true }, func(avail, needed float64) { waitCalls++ gotAvail, gotNeed = avail, needed }, ) if !ok { t.Fatal("want true once Windows reclaims commit memory") } if waitCalls != 1 { t.Fatalf("onWait calls = %d, want 1", waitCalls) } if gotAvail != 6.7 || gotNeed != 8+host.StartMarginGB { t.Fatalf("onWait = (%.1f, %.1f), want (6.7, %.1f)", gotAvail, gotNeed, 8+host.StartMarginGB) } } func TestWaitForCommitMemoryTimeoutAndCancel(t *testing.T) { ok := waitForCommitMemory( context.Background(), "8G", 30*time.Millisecond, 5*time.Millisecond, func() (float64, bool) { return 6.7, true }, nil, ) if ok { t.Fatal("want false when commit memory stays below threshold") } ctx, cancel := context.WithCancel(context.Background()) cancel() ok = waitForCommitMemory( ctx, "8G", time.Second, 5*time.Millisecond, func() (float64, bool) { return 6.7, true }, nil, ) if ok { t.Fatal("want false when context is cancelled") } if !waitForCommitMemory(context.Background(), "8G", time.Second, 5*time.Millisecond, func() (float64, bool) { return 0, false }, nil) { t.Fatal("want true when CommitAvailGB probe is unavailable") } }