github.com/stefanmcshane/helm@v0.0.0-20221213002717-88a4a2c6e77d/internal/test/test.go (about) 1 /* 2 Copyright The Helm Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package test 18 19 import ( 20 "bytes" 21 "flag" 22 "io/ioutil" 23 "path/filepath" 24 25 "github.com/pkg/errors" 26 ) 27 28 // UpdateGolden writes out the golden files with the latest values, rather than failing the test. 29 var updateGolden = flag.Bool("update", false, "update golden files") 30 31 // TestingT describes a testing object compatible with the critical functions from the testing.T type 32 type TestingT interface { 33 Fatal(...interface{}) 34 Fatalf(string, ...interface{}) 35 HelperT 36 } 37 38 // HelperT describes a test with a helper function 39 type HelperT interface { 40 Helper() 41 } 42 43 // AssertGoldenString asserts that the given string matches the contents of the given file. 44 func AssertGoldenString(t TestingT, actual, filename string) { 45 t.Helper() 46 47 if err := compare([]byte(actual), path(filename)); err != nil { 48 t.Fatalf("%v\n", err) 49 } 50 } 51 52 // AssertGoldenFile asserts that the content of the actual file matches the contents of the expected file 53 func AssertGoldenFile(t TestingT, actualFileName string, expectedFilename string) { 54 t.Helper() 55 56 actual, err := ioutil.ReadFile(actualFileName) 57 if err != nil { 58 t.Fatalf("%v", err) 59 } 60 AssertGoldenString(t, string(actual), expectedFilename) 61 } 62 63 func path(filename string) string { 64 if filepath.IsAbs(filename) { 65 return filename 66 } 67 return filepath.Join("testdata", filename) 68 } 69 70 func compare(actual []byte, filename string) error { 71 actual = normalize(actual) 72 if err := update(filename, actual); err != nil { 73 return err 74 } 75 76 expected, err := ioutil.ReadFile(filename) 77 if err != nil { 78 return errors.Wrapf(err, "unable to read testdata %s", filename) 79 } 80 expected = normalize(expected) 81 if !bytes.Equal(expected, actual) { 82 return errors.Errorf("does not match golden file %s\n\nWANT:\n'%s'\n\nGOT:\n'%s'", filename, expected, actual) 83 } 84 return nil 85 } 86 87 func update(filename string, in []byte) error { 88 if !*updateGolden { 89 return nil 90 } 91 return ioutil.WriteFile(filename, normalize(in), 0666) 92 } 93 94 func normalize(in []byte) []byte { 95 return bytes.Replace(in, []byte("\r\n"), []byte("\n"), -1) 96 }