package assert import ( "encoding/json" "encoding/xml" "errors" "os" "strings" "testing" ) func pathExists(path string) bool { _, err := os.Stat(path) return !errors.Is(err, os.ErrNotExist) } func ensureSuffix(s, suffix string) string { if !strings.HasSuffix(s, suffix) { s = s + suffix } return s } func writeSnapshot(t *testing.T, path, actual string) { f, err := os.Create(path) if err != nil { t.Fatalf("Failed to create snapshot file: %s", err) } _, err = f.Write([]byte(actual)) if err != nil { t.Fatalf("Failed to write to snapshot file: %s", err) } err = f.Close() if err != nil { t.Fatalf("Failed to close snapshot file: %s", err) } } func TextSnapshot(t *testing.T, path, actual string) { if !pathExists(path) { writeSnapshot(t, path, actual) t.Errorf("Snapshot file created: %s", path) return } actual = ensureSuffix(actual, "\n") content, err := os.ReadFile(path) if err != nil { t.Fatalf("Failed to read snapshot file: %s", err) } expected := string(content) expected = ensureSuffix(expected, "\n") if expected != actual { t.Errorf("Value doesn't match snapshot %s:\n\nExpected:\n%s\n\nActual:\n%s\n", path, expected, actual) } if os.Getenv("UPDATE_SNAPSHOTS") == "" { return } writeSnapshot(t, path, actual) t.Logf("Snapshot file %s updated\n", path) } func JsonSnapshot(t *testing.T, path string, actual any) { data, err := json.MarshalIndent(actual, "", " ") if err != nil { t.Fatalf("Snapshot failed to serialize actual to JSON: %s", err) } TextSnapshot(t, path, string(data)) } func XmlSnapshot(t *testing.T, path string, actual any) { data, err := xml.MarshalIndent(actual, "", " ") if err != nil { t.Fatalf("Snapshot failed to serialize actual to XML: %s", err) } TextSnapshot(t, path, string(data)) }