| 1 | package host |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "strconv" |
| 6 | "testing" |
| 7 | |
| 8 | "github.com/sylvinus/agent-vm/internal/bashref" |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | func setHost(t *testing.T, cpus, mem int) { |
| 15 | t.Helper() |
| 16 | oc, om := CPUs, MemGiB |
| 17 | t.Cleanup(func() { CPUs, MemGiB = oc, om }) |
| 18 | CPUs = func() int { return cpus } |
| 19 | MemGiB = func() int { return mem } |
| 20 | } |
| 21 | |
| 22 | func TestCapBash(t *testing.T) { |
| 23 | setHost(t, 8, 16) |
| 24 | stub := `_agent_vm_host_cpus() { echo 8; }; _agent_vm_host_mem_gib() { echo 16; }; _agent_vm_cap_resource "$@"` |
| 25 | for _, share := range []string{"", "1", "4", "0", "x", "08"} { |
| 26 | var env []string |
| 27 | if share != "" { |
| 28 | t.Setenv("AGENT_VM_HOST_SHARE", share) |
| 29 | env = []string{"AGENT_VM_HOST_SHARE=" + share} |
| 30 | } |
| 31 | for _, kind := range []string{"cpus", "memory"} { |
| 32 | for _, v := range []int{1, 2, 3, 4, 5, 8, 9, 16, 64} { |
| 33 | var warn bytes.Buffer |
| 34 | got := Cap(kind, v, &warn) |
| 35 | r := bashref.Script(t, "", env, stub, kind, strconv.Itoa(v)) |
| 36 | if strconv.Itoa(got)+"\n" != r.Stdout || warn.String() != r.Stderr { |
| 37 | t.Errorf("share %q, %s %d: %d %q, bash %q %q", share, kind, v, got, warn.String(), r.Stdout, r.Stderr) |
| 38 | } |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | if Cap("cpus", 0, nil) != 0 { |
| 43 | t.Error("nothing asked") |
| 44 | } |
| 45 | setHost(t, 0, 16) |
| 46 | if Cap("cpus", 64, nil) != 64 { |
| 47 | t.Error("an unknown host clamped") |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | |
| 52 | |
| 53 | func TestQemuBinaryFor(t *testing.T) { |
| 54 | for _, c := range []struct { |
| 55 | goarch, manager string |
| 56 | bin, cmd string |
| 57 | }{ |
| 58 | {"amd64", "apt-get", "qemu-system-x86_64", "sudo apt-get install qemu-system-x86 qemu-utils"}, |
| 59 | {"arm64", "apt-get", "qemu-system-aarch64", "sudo apt-get install qemu-system-arm qemu-utils"}, |
| 60 | {"amd64", "dnf", "qemu-system-x86_64", "sudo dnf install qemu-system-x86-core qemu-img"}, |
| 61 | {"arm64", "dnf", "qemu-system-aarch64", "sudo dnf install qemu-system-aarch64-core qemu-img"}, |
| 62 | {"amd64", "", "qemu-system-x86_64", "your distribution's QEMU package (with Nix, 'nix run github:sylvinus/agent-vm' brings its own)"}, |
| 63 | } { |
| 64 | if bin, cmd := qemuBinaryFor(c.goarch, c.manager); bin != c.bin || cmd != c.cmd { |
| 65 | t.Errorf("%s %q: %s %q", c.goarch, c.manager, bin, cmd) |
| 66 | } |
| 67 | } |
| 68 | } |