Files
sfz/robust_test.go
T
aneurinandClaude Sonnet 5.5 37d2866fe9 Let WriteFiles write includes that leave the folder when asked
AllowParentPaths is off by default, so WriteFiles still refuses a path
with .. in it. Absolute paths are refused either way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-12-01 23:12:34 +00:00

410 lines
14 KiB
Go

package sfz
import (
"errors"
"fmt"
"io"
"reflect"
"strings"
"sync"
"testing"
"time"
)
// TestDefinesCannotOutgrowLimit checks that variables that hold variables stop
// at the byte limit, as a few lines of them would otherwise make gigabytes.
func TestDefinesCannotOutgrowLimit(t *testing.T) {
var b strings.Builder
// The names are as long as each other, so none is the start of another.
name := func(i int) string { return fmt.Sprintf("$N%c%c", 'a'+i/26, 'a'+i%26) }
fmt.Fprintf(&b, "#define %s xxxxxxxx\n", name(0))
for i := 1; i <= 40; i++ {
fmt.Fprintf(&b, "#define %s %s%s\n", name(i), name(i-1), name(i-1))
}
start := time.Now()
_, err := Parse(strings.NewReader(b.String()))
if !errors.Is(err, ErrInvalid) {
t.Errorf("err %v", err)
}
if d := time.Since(start); d > slowdown*5*time.Second {
t.Errorf("took %v", d)
}
}
// TestUseOfDefinesCountsAgainstLimit checks that an opcode that expands a large
// variable many times is counted, as flattening makes the text.
func TestUseOfDefinesCountsAgainstLimit(t *testing.T) {
text := "#define $A " + strings.Repeat("x", 100) + "\n" + strings.Repeat("<region> sample=$A.wav\n", 100)
if _, err := Parse(strings.NewReader(text), WithLimits(Limits{MaxBytes: 5000})); !errors.Is(err, ErrInvalid) {
t.Errorf("err %v", err)
}
if _, err := Parse(strings.NewReader(text), WithLimits(Limits{MaxBytes: 50000})); err != nil {
t.Errorf("err %v", err)
}
}
// countingReader counts the bytes read from it, and never ends.
type countingReader struct{ n int }
func (r *countingReader) Read(p []byte) (int, error) {
r.n += len(p)
for i := range p {
p[i] = ' '
}
return len(p), nil
}
// TestParseReadsNoMoreThanLimit checks that Parse refuses a reader that is
// past the limit without reading all of it, and accepts text that is at the
// limit.
func TestParseReadsNoMoreThanLimit(t *testing.T) {
var r countingReader
_, err := Parse(&r, WithLimits(Limits{MaxBytes: 1000}))
if !errors.Is(err, ErrInvalid) {
t.Errorf("err %v", err)
}
if r.n > 1<<16 {
t.Errorf("read %d bytes", r.n)
}
if _, err := Parse(io.LimitReader(&countingReader{}, 1000), WithLimits(Limits{MaxBytes: 1000})); err != nil {
t.Errorf("text at the limit: %v", err)
}
}
// TestLimitsDepth checks that WithLimits sets how deeply includes may nest.
func TestLimitsDepth(t *testing.T) {
m := map[string]string{"a": "#include \"b\"", "b": "#include \"c\"", "c": "<region>"}
_, err := Parse(strings.NewReader("#include \"a\""), WithResolver(files(m)), WithLimits(Limits{MaxDepth: 2}))
if !errors.Is(err, ErrInvalid) {
t.Errorf("err %v", err)
}
}
// TestLexScales checks that text a few megabytes long is read in a moment, in
// each shape of text whose reading time could grow with the square of its
// length.
func TestLexScales(t *testing.T) {
for name, text := range map[string]string{
"opcodes on one line": strings.Repeat("a=1 ", 1<<19),
"punctuation": strings.Repeat("!", 1<<20),
"unknown variable": "x=$" + strings.Repeat("b", 1<<20) + "\n<region>",
"long define name": "#define $" + strings.Repeat("b", 1<<20) + " 1\n<region> sample=$" + strings.Repeat("b", 1<<20),
} {
start := time.Now()
doc, err := Parse(strings.NewReader(text))
if err != nil {
t.Fatalf("%s: %v", name, err)
}
doc.Flatten()
doc.Validate()
if doc.String() != text {
t.Errorf("%s: not written back", name)
}
if d := time.Since(start); d > slowdown*3*time.Second {
t.Errorf("%s: took %v", name, d)
}
}
}
// TestByteOrderMark checks that a byte order mark is read as space, so that a
// directive after it is still one.
func TestByteOrderMark(t *testing.T) {
text := "\ufeff#define $A 1\n<region> sample=$A.wav\n"
doc := mustParse(t, text, nil)
if doc.String() != text {
t.Errorf("wrote %q", doc.String())
}
if got := doc.Flatten().Regions[0].Opcodes["sample"]; got != "1.wav" {
t.Errorf("sample %q", got)
}
for _, p := range doc.Validate() {
t.Errorf("problem %+v", p)
}
doc = mustParse(t, "\ufeff<region> sample=a.wav", nil)
if len(doc.Flatten().Regions) != 1 {
t.Error("region after the mark")
}
}
// TestWriteFilesStaysInFolder checks that WriteFiles refuses an include that
// leaves the folder, and writes nothing.
func TestWriteFilesStaysInFolder(t *testing.T) {
anyFile := func(string) ([]byte, error) { return []byte("<region> sample=a.wav\n"), nil }
for _, include := range []string{"../evil.sfz", "a/../../evil.sfz", "/evil.sfz", "..\\evil.sfz"} {
doc, err := Parse(strings.NewReader(fmt.Sprintf("#include %q\n", include)), WithResolver(anyFile))
if err != nil {
t.Fatal(err)
}
var written []string
err = doc.WriteFiles("out/main.sfz", func(p string, _ []byte) error { written = append(written, p); return nil }, WriteOptions{})
if !errors.Is(err, ErrInvalid) || len(written) != 0 {
t.Errorf("%s: err %v, wrote %q", include, err, written)
}
}
}
// TestWriteFilesAllowParentPaths checks that AllowParentPaths lets WriteFiles
// write an include that leaves the folder with ".." (also spelled with a
// backslash, which the resolver reads as a slash), and still refuses
// absolute paths.
func TestWriteFilesAllowParentPaths(t *testing.T) {
anyFile := func(string) ([]byte, error) { return []byte("<region> sample=a.wav\n"), nil }
for include, ok := range map[string]bool{"../Data/a.sfz": true, "../../a.sfz": true, "/evil.sfz": false, "..\\evil.sfz": true} {
doc, err := Parse(strings.NewReader(fmt.Sprintf("#include %q\n", include)), WithResolver(anyFile))
if err != nil {
t.Fatal(err)
}
var written []string
err = doc.WriteFiles("out/main.sfz", func(p string, _ []byte) error { written = append(written, p); return nil }, WriteOptions{AllowParentPaths: true})
if ok && (err != nil || len(written) != 2) {
t.Errorf("%s: err %v, wrote %q", include, err, written)
}
if !ok && (!errors.Is(err, ErrInvalid) || len(written) != 0) {
t.Errorf("%s: err %v, wrote %q", include, err, written)
}
}
}
// TestValidateOutsideFolder checks that Validate reports includes and samples
// that leave the folder.
func TestValidateOutsideFolder(t *testing.T) {
doc := mustParse(t, "#include \"../x.sfz\"\n<region> sample=../a.wav\n<region> sample=/a.wav\n<region> sample=C:\\a.wav\n<region> sample=ok/../b.wav\n", map[string]string{"../x.sfz": ""})
var codes []string
for _, p := range doc.Validate() {
codes = append(codes, p.Code)
}
want := []string{"include.outside", "sample.outside", "sample.outside", "sample.outside"}
if !reflect.DeepEqual(codes, want) {
t.Errorf("codes %q, want %q", codes, want)
}
}
// TestKeyswitchRangeOneEnd checks that a keyswitch range with only one end
// set is that one key.
func TestKeyswitchRangeOneEnd(t *testing.T) {
for text, want := range map[string]KeyswitchRange{
"<region> sample=a.wav sw_lokey=36": {Low: 36, High: 36},
"<region> sample=a.wav sw_hikey=40": {Low: 40, High: 40},
} {
got := parseText(t, text).Keyswitches
if got == nil || got.Low != want.Low || got.High != want.High {
t.Errorf("%s: %+v", text, got)
}
}
}
// TestInstrumentIsDeterministic checks that regions with many controller
// modulations read the same each time.
func TestInstrumentIsDeterministic(t *testing.T) {
text := "<region> sample=a.wav pitch_keycenter=77 lovel=3 hivel=71 " +
"volume_oncc131=0.1 volume_oncc133=0.37 volume_oncc134=0.7 volume_cc131=0.3 gain_oncc131=0.9 gain_oncc133=0.3 " +
"pitch_oncc131=3.3 pitch_oncc133=1.1 pitch_oncc134=1e16 tune_oncc131=-1e16 tune_oncc133=0.3 tune_oncc134=0.7 " +
"amplitude_oncc131=80 amplitude_oncc133=70 amplitude_oncc134=90 amplitude_oncc132=33\n"
want := parseText(t, text).Regions
for i := 0; i < 100; i++ {
if got := parseText(t, text).Regions; !reflect.DeepEqual(got, want) {
t.Fatalf("run %d: %+v, want %+v", i, got, want)
}
}
}
// writeCombinations are the write options a fuzzer tries.
var writeCombinations = []WriteOptions{
{}, {InlineIncludes: true}, {ExpandVariables: true}, {InlineIncludes: true, ExpandVariables: true},
{LineEnding: LF}, {LineEnding: CRLF, InlineIncludes: true},
}
// FuzzWrite checks that a document is written, and read back, with any
// options, and that without changes the zero value gives the text back.
func FuzzWrite(f *testing.F) {
for _, text := range roundTripTexts {
f.Add(text, "<region> sample=$S.wav")
}
f.Fuzz(func(t *testing.T, text, included string) {
resolver := func(string) ([]byte, error) { return []byte(included), nil }
doc, err := Parse(strings.NewReader(text), WithResolver(resolver))
if err != nil {
t.Skip()
}
for _, opts := range writeCombinations {
var b strings.Builder
if err := doc.Write(&b, opts); err != nil {
continue
}
if _, err := Parse(strings.NewReader(b.String()), WithResolver(resolver)); err != nil {
t.Skip()
}
}
var b strings.Builder
if err := doc.Write(&b, WriteOptions{}); err == nil && doc.String() != b.String() {
t.Fatalf("wrote %q, want %q", b.String(), doc.String())
}
doc.WriteFiles("main.sfz", func(string, []byte) error { return nil }, WriteOptions{})
})
}
// significant returns the kind and text of the nodes of a file that aren't
// whitespace.
func significant(nodes []*Node) []string {
var out []string
for _, n := range nodes {
if n.Kind != KindSpace {
out = append(out, n.Kind.String()+":"+n.Raw)
}
}
return out
}
// FuzzEdit checks that editing any document doesn't panic, that what is
// written reads back as the nodes that were edited, and that an edit that
// is refused changes nothing.
func FuzzEdit(f *testing.F) {
for _, text := range roundTripTexts {
f.Add(text, "lokey", "60")
}
f.Add("<region> sample=a.wav // c\n", "hikey", "3")
f.Add("<region> sample=a.wav", "x", "1\n<region>")
f.Fuzz(func(t *testing.T, text, name, value string) {
doc, err := Parse(strings.NewReader(text))
if err != nil {
t.Skip()
}
check := func(what string) {
for _, file := range doc.Files() {
if got, want := significant(lex(file.String())), significant(file.Nodes); !reflect.DeepEqual(got, want) {
t.Fatalf("%s: wrote %q, which reads as %q, not %q", what, file.String(), got, want)
}
}
}
for _, h := range doc.Headers() {
before := doc.String()
if err := h.Set(name, value); err != nil {
if doc.String() != before {
t.Fatalf("refused Set changed the text to %q", doc.String())
}
continue
}
check("Set")
h.Get(name)
h.Delete(name)
check("Delete")
}
if h, err := doc.AddHeader("region", nil); err == nil {
h.Set(name, value)
check("AddHeader")
}
if err := doc.SetDefine("$X", value); err == nil {
check("SetDefine")
}
doc.Flatten()
doc.Validate()
for _, f := range doc.Files() {
prev := f.String()
f.reposition()
if f.String() != prev {
t.Fatal("repositioning changed the text")
}
}
})
}
// FuzzBuild checks that an instrument read from any text builds into a
// document that reads, whichever the options.
func FuzzBuild(f *testing.F) {
for _, text := range roundTripTexts {
f.Add(text)
}
f.Add("<region> sample=a.wav sw_lokey=3 volume_oncc7=1 locc7=3 hicc7=9 lochan=2")
f.Fuzz(func(t *testing.T, text string) {
doc, err := Parse(strings.NewReader(text))
if err != nil {
t.Skip()
}
inst := doc.Flatten().Instrument()
for _, opts := range []BuildOptions{{}, {Variables: true, MinRepeat: 1}, {SplitFiles: true, RegionsPerFile: 1}} {
built, err := Build(inst, opts)
if err != nil {
if !errors.Is(err, ErrInvalid) {
t.Fatal(err)
}
continue
}
built.Validate()
built.Flatten().Instrument()
}
})
}
// TestBuildVariablesWithAbsoluteSamples checks that samples in the root, or in
// no common folder, build with a folder of variables.
func TestBuildVariablesWithAbsoluteSamples(t *testing.T) {
for _, samples := range [][]string{{"/"}, {"/a.wav", "/b/c.wav"}, {"/a/b.wav", "/a/c.wav"}, {"a/b.wav", "/a/c.wav"}} {
inst := &Instrument{}
for _, s := range samples {
r := defaultRegion()
r.Sample = s
inst.Regions = append(inst.Regions, r)
}
done := make(chan struct{})
go func() {
defer close(done)
if _, err := Build(inst, BuildOptions{Variables: true}); err != nil {
t.Error(err)
}
}()
select {
case <-done:
case <-time.After(slowdown * 5 * time.Second):
t.Fatalf("%q: Build didn't return", samples)
}
}
}
// TestEqualsInValue checks that a value may hold =, and that the next opcode
// starts only after whitespace.
func TestEqualsInValue(t *testing.T) {
for text, want := range map[string][]string{
"<region> sample=A=440.wav lokey=1": {"sample=A=440.wav", "lokey=1"},
"<region> sample=a b=c.wav": {"sample=a", "b=c.wav"},
"<region>sample=x.wav\n lokey=1\thikey=2": {"sample=x.wav", "lokey=1", "hikey=2"},
"label_cc1=Volume=Loud // note": {"label_cc1=Volume=Loud"},
// Without whitespace, what follows is part of the value.
"lokey=1hikey=2": {"lokey=1hikey=2"},
} {
doc := mustParse(t, text, nil)
var got []string
for _, n := range doc.Root.Nodes {
if n.Kind == KindOpcode {
got = append(got, n.Name+"="+n.Value)
}
}
if !reflect.DeepEqual(got, want) || doc.String() != text {
t.Errorf("%q: opcodes %q, want %q", text, got, want)
}
}
}
// TestConcurrentReads checks that a document that hasn't been edited can be
// read by several goroutines at once. It is run with the race detector.
func TestConcurrentReads(t *testing.T) {
doc := mustParse(t, "#define $A 1\n<group> volume=-3\n<region> sample=a.wav lokey=c4\n<region> sample=b.wav\n", nil)
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func() {
defer wg.Done()
doc.Validate()
inst := doc.Flatten().Instrument()
_ = doc.String()
for _, h := range doc.Headers() {
h.Get("sample")
h.Opcodes()
}
if _, err := inst.Patches(0, inst.Regions[0]); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
}