@@ -573,6 +573,58 @@ func TestCheckExitCode(expectedCode int) TestCheck {
573573 }
574574}
575575
576+ // GoldenReplacement describe patterns to be replaced in goldens
577+ type GoldenReplacement struct {
578+ // Line will be matched using this regex
579+ Pattern * regexp.Regexp
580+ // Content that will replace the matched regex
581+ // This is the format for repl in (*regexp.Regexp).ReplaceAll
582+ // You can use $ to represent groups $1, $2...
583+ Replacement string
584+ }
585+
586+ // goldenReplacePatterns replace the list of patterns with their given replacement
587+ func goldenReplacePatterns (golden string , replacements ... GoldenReplacement ) (string , error ) {
588+ var matchFailed []string
589+ var changedGolden = golden
590+
591+ for _ , replacement := range replacements {
592+ if ! replacement .Pattern .MatchString (changedGolden ) {
593+ matchFailed = append (matchFailed , replacement .Pattern .String ())
594+ continue
595+ }
596+ changedGolden = replacement .Pattern .ReplaceAllString (changedGolden , replacement .Replacement )
597+ }
598+
599+ if len (matchFailed ) > 0 {
600+ return changedGolden , fmt .Errorf ("failed to match regex in golden: %#q" , matchFailed )
601+ }
602+ return changedGolden , nil
603+ }
604+
605+ // TestCheckGoldenAndReplacePatterns assert stderr and stdout using golden,
606+ // golden are matched against given regex and edited with replacements
607+ func TestCheckGoldenAndReplacePatterns (replacements ... GoldenReplacement ) TestCheck {
608+ return func (t * testing.T , ctx * CheckFuncCtx ) {
609+ actual := marshalGolden (t , ctx )
610+ actual , actualReplaceErr := goldenReplacePatterns (actual , replacements ... )
611+
612+ goldenPath := getTestFilePath (t , ".golden" )
613+ // In order to avoid diff in goldens we set all timestamp to the same date
614+ if * UpdateGoldens {
615+ require .NoError (t , os .MkdirAll (path .Dir (goldenPath ), 0755 ))
616+ require .NoError (t , os .WriteFile (goldenPath , []byte (actual ), 0644 )) //nolint:gosec
617+ }
618+
619+ expected , err := os .ReadFile (goldenPath )
620+ require .NoError (t , err , "expected to find golden file %s" , goldenPath )
621+ expectedString , expectedReplaceErr := goldenReplacePatterns (string (expected ), replacements ... )
622+ assert .Equal (t , expectedString , actual )
623+ assert .Nil (t , actualReplaceErr , "failed to match test output with regexes" )
624+ assert .Nil (t , expectedReplaceErr , "failed to match stored golden with regexes" )
625+ }
626+ }
627+
576628// TestCheckGolden assert stderr and stdout using golden
577629func TestCheckGolden () TestCheck {
578630 return func (t * testing.T , ctx * CheckFuncCtx ) {
0 commit comments