package sfz import ( "strings" "testing" ) func write(t *testing.T, doc *Document, opts WriteOptions) string { t.Helper() var b strings.Builder if err := doc.Write(&b, opts); err != nil { t.Fatal(err) } return b.String() } var writeFiles = map[string]string{ "x.sfz": "// kit\n sample=$S.wav\n", } const writeMain = "#define $S kick\n#include \"x.sfz\"\n#define $S snare\n sample=$S.wav\n" func TestWriteZeroValue(t *testing.T) { doc := mustParse(t, writeMain, writeFiles) if got := write(t, doc, WriteOptions{}); got != writeMain { t.Errorf("got %q", got) } } func TestInlineIncludes(t *testing.T) { doc := mustParse(t, writeMain, writeFiles) got := write(t, doc, WriteOptions{InlineIncludes: true}) want := "#define $S kick\n// kit\n sample=$S.wav\n \n#define $S snare\n sample=$S.wav\n" if got != want { t.Errorf("got %q want %q", got, want) } // The single file reads as the document did. flat := mustParse(t, got, nil).Flatten() if len(flat.Regions) != 2 || flat.Regions[0].Opcodes["sample"] != "kick.wav" || flat.Regions[1].Opcodes["sample"] != "snare.wav" { t.Errorf("regions %+v", flat.Regions) } } func TestExpandVariables(t *testing.T) { doc := mustParse(t, writeMain, writeFiles) got := write(t, doc, WriteOptions{InlineIncludes: true, ExpandVariables: true}) want := "// kit\n sample=kick.wav\n \n sample=snare.wav\n" if got != want { t.Errorf("got %q want %q", got, want) } // Without inlining, the included file needs the variable, so only the files // written together are expanded. if err := doc.Write(new(strings.Builder), WriteOptions{ExpandVariables: true}); err == nil { t.Error("expanding variables beside includes didn't fail") } out := map[string]string{} err := doc.WriteFiles("m.sfz", func(p string, d []byte) error { out[p] = string(d); return nil }, WriteOptions{ExpandVariables: true}) if err != nil { t.Fatal(err) } if out["m.sfz"] != "#include \"x.sfz\"\n sample=snare.wav\n" || out["x.sfz"] != "// kit\n sample=kick.wav\n" { t.Errorf("files %q", out) } // A file included twice with different values can't be written once. twice := mustParse(t, "#define $S a\n#include \"x.sfz\"\n#define $S b\n#include \"x.sfz\"\n", writeFiles) err = twice.WriteFiles("m.sfz", func(string, []byte) error { return nil }, WriteOptions{ExpandVariables: true}) if err == nil { t.Error("a file written two ways didn't fail") } } func TestLineEndings(t *testing.T) { doc := mustParse(t, "\r\nsample=a.wav\n", nil) if got := write(t, doc, WriteOptions{LineEnding: LF}); got != "\nsample=a.wav\n" { t.Errorf("LF %q", got) } if got := write(t, doc, WriteOptions{LineEnding: CRLF}); got != "\r\nsample=a.wav\r\n" { t.Errorf("CRLF %q", got) } if got := write(t, doc, WriteOptions{}); got != "\r\nsample=a.wav\n" { t.Errorf("kept %q", got) } }