github.com/noqcks/syft@v0.0.0-20230920222752-a9e2c4e288e5/syft/formats/internal/testutils/snapshot.go (about) 1 package testutils 2 3 import ( 4 "bytes" 5 "testing" 6 7 "github.com/google/go-cmp/cmp" 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/anchore/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 { 68 requireEqual(t, expected, actual) 69 } 70 } 71 72 func requireEqual(t *testing.T, expected any, actual any) { 73 if diff := cmp.Diff(expected, actual); diff != "" { 74 t.Logf("expected: %s", expected) 75 t.Logf("actual: %s", actual) 76 t.Fatalf("mismatched output: %s", diff) 77 } 78 } 79 80 type ImageSnapshotTestConfig struct { 81 Image string 82 UpdateImageSnapshot bool 83 } 84 85 func AssertEncoderAgainstGoldenImageSnapshot(t *testing.T, imgCfg ImageSnapshotTestConfig, cfg EncoderSnapshotTestConfig) { 86 if imgCfg.UpdateImageSnapshot { 87 // grab the latest image contents and persist 88 imagetest.UpdateGoldenFixtureImage(t, imgCfg.Image) 89 } 90 91 AssertEncoderAgainstGoldenSnapshot(t, cfg) 92 }