package sfz import ( "errors" "fmt" "io" "reflect" "strings" "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 > 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(" 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 } 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) } } func TestLimitsDepth(t *testing.T) { m := map[string]string{"a": "#include \"b\"", "b": "#include \"c\"", "c": ""} _, 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 takes a moment to // read in each shape that was once quadratic. 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", "long define name": "#define $" + strings.Repeat("b", 1<<20) + " 1\n 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 > 3*time.Second { t.Errorf("%s: took %v", name, d) } } } func TestByteOrderMark(t *testing.T) { text := "\ufeff#define $A 1\n 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 sample=a.wav", nil) if len(doc.Flatten().Regions) != 1 { t.Error("region after the mark") } } func TestWriteFilesStaysInFolder(t *testing.T) { anyFile := func(string) ([]byte, error) { return []byte(" 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) } } } func TestValidateOutsideFolder(t *testing.T) { doc := mustParse(t, "#include \"../x.sfz\"\n sample=../a.wav\n sample=/a.wav\n sample=C:\\a.wav\n 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) } } func TestKeyswitchRangeOneEnd(t *testing.T) { for text, want := range map[string]KeyswitchRange{ " sample=a.wav sw_lokey=36": {Low: 36, High: 36}, " 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 := " 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, " 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{}) }) } // FuzzEdit checks that editing any document doesn't panic, and keeps the // layout it didn't change. func FuzzEdit(f *testing.F) { for _, text := range roundTripTexts { f.Add(text, "lokey", "60") } f.Fuzz(func(t *testing.T, text, name, value string) { doc, err := Parse(strings.NewReader(text)) if err != nil { t.Skip() } for _, h := range doc.Headers() { h.Set(name, value) h.Get(name) h.Delete(name) } doc.AddHeader("region", nil).Set(name, value) doc.SetDefine("$X", value) 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(" 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 { t.Fatal(err) } 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(5 * time.Second): t.Fatalf("%q: Build didn't return", samples) } } }