github.com/kastenhq/syft@v0.0.0-20230821225854-0710af25cdbe/syft/formats/internal/testutils/snapshot.go (about) 1 package testutils 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/sergi/go-diff/diffmatchpatch" 8 "github.com/stretchr/testify/assert" 9 "github.com/stretchr/testify/require" 10 11 "github.com/anchore/go-testutils" 12 "github.com/anchore/stereoscope/pkg/imagetest" 13 "github.com/kastenhq/syft/syft/sbom" 14 ) 15 16 type imageCfg struct { 17 fromSnapshot bool 18 } 19 20 type ImageOption func(cfg *imageCfg) 21 22 func FromSnapshot() ImageOption { 23 return func(cfg *imageCfg) { 24 cfg.fromSnapshot = true 25 } 26 } 27 28 type EncoderSnapshotTestConfig struct { 29 Subject sbom.SBOM 30 Format sbom.Format 31 UpdateSnapshot bool 32 PersistRedactionsInSnapshot bool 33 IsJSON bool 34 Redactor Redactor 35 } 36 37 func AssertEncoderAgainstGoldenSnapshot(t *testing.T, cfg EncoderSnapshotTestConfig) { 38 t.Helper() 39 var buffer bytes.Buffer 40 41 err := cfg.Format.Encode(&buffer, cfg.Subject) 42 assert.NoError(t, err) 43 actual := buffer.Bytes() 44 45 if cfg.UpdateSnapshot && !cfg.PersistRedactionsInSnapshot { 46 // replace the expected snapshot contents with the current (unredacted) encoder contents 47 testutils.UpdateGoldenFileContents(t, actual) 48 return 49 } 50 51 var expected []byte 52 if cfg.Redactor != nil { 53 actual = cfg.Redactor.Redact(actual) 54 expected = cfg.Redactor.Redact(testutils.GetGoldenFileContents(t)) 55 } else { 56 expected = testutils.GetGoldenFileContents(t) 57 } 58 59 if cfg.UpdateSnapshot && cfg.PersistRedactionsInSnapshot { 60 // replace the expected snapshot contents with the current (redacted) encoder contents 61 testutils.UpdateGoldenFileContents(t, actual) 62 return 63 } 64 65 if cfg.IsJSON { 66 require.JSONEq(t, string(expected), string(actual)) 67 } else if !bytes.Equal(expected, actual) { 68 dmp := diffmatchpatch.New() 69 diffs := dmp.DiffMain(string(expected), string(actual), true) 70 t.Logf("len: %d\nexpected: %s", len(expected), expected) 71 t.Logf("len: %d\nactual: %s", len(actual), actual) 72 t.Errorf("mismatched output:\n%s", dmp.DiffPrettyText(diffs)) 73 } 74 } 75 76 type ImageSnapshotTestConfig struct { 77 Image string 78 UpdateImageSnapshot bool 79 } 80 81 func AssertEncoderAgainstGoldenImageSnapshot(t *testing.T, imgCfg ImageSnapshotTestConfig, cfg EncoderSnapshotTestConfig) { 82 if imgCfg.UpdateImageSnapshot { 83 // grab the latest image contents and persist 84 imagetest.UpdateGoldenFixtureImage(t, imgCfg.Image) 85 } 86 87 AssertEncoderAgainstGoldenSnapshot(t, cfg) 88 }