nixbuild/derivation_test.go
Yonah 69c6128ff5
exec: replace global state with interface
This is cleaner, and finally enables writing tests for the nix invoking functions.
2025-07-18 13:40:46 +09:00

113 lines
2.3 KiB
Go

package nixbuild_test
import (
"encoding/json"
"os"
"os/exec"
"reflect"
"slices"
"syscall"
"testing"
"git.gensokyo.uk/yonah/nixbuild"
"hakurei.app/command"
)
func init() {
stubCommandInit = append(stubCommandInit, func(c command.Command) {
c.NewCommand(nixbuild.CommandDerivation, "emit samples for various `nix derivation` cases", func(args []string) error {
if len(args) == 0 {
return syscall.ENOSYS
}
switch args[0] {
default:
return syscall.EINVAL
case nixbuild.CommandDerivationShow:
if len(args) != 2 {
return syscall.ENOSYS
}
switch args[1] {
default:
return syscall.EINVAL
case nixbuild.FlagStdin:
var testName string
if want, err := nixbuild.ReadStdin(os.Stdin); err != nil {
return err
} else {
for n, w := range instWant {
if slices.Equal(w, want) {
testName = n
break
}
}
if testName == "" {
return syscall.ENOSYS
}
}
if sample, ok := drvShow[testName]; !ok {
return syscall.ENOSYS
} else {
_, err := os.Stdout.Write(sample)
return err
}
}
}
})
})
}
func TestDerivationShow(t *testing.T) {
stubNixCommand(t)
testCases := []struct {
name string
}{
{"getchoo atlas"},
{"getchoo glados"},
{"pluiedev pappardelle"},
}
for _, tc := range testCases {
got, err := nixbuild.DerivationShow(
newStubContext(t.Context(), nil, os.Stdout, os.Stderr),
slices.Values(instWant[tc.name]),
)
if err != nil {
t.Fatalf("DerivationShow: error = %v", err)
}
var want nixbuild.DerivationMap
if err = json.Unmarshal(drvShow[tc.name], &want); err != nil {
t.Fatalf("cannot unmarshal: %v", err)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("DerivationShow: %#v, want %#v", got, want)
}
}
}
func TestDerivationShowAlreadySet(t *testing.T) {
stubNixCommand(t)
if _, err := nixbuild.DerivationShow(
newStubContextCommand(func(cmd *exec.Cmd) { cmd.Stdout = os.Stdout }, t.Context(), nil, os.Stdout, os.Stderr),
nil,
); err == nil {
t.Errorf("DerivationShow unexpectedly succeeded")
}
}
func BenchmarkShowUnmarshal(b *testing.B) {
var v nixbuild.DerivationMap
data := drvShow["pluiedev pappardelle"]
for b.Loop() {
if err := json.Unmarshal(data, &v); err != nil {
b.Fatalf("Unmarshal: error = %v", err)
}
}
}