github.com/google/yamlfmt@v0.12.2-0.20240514121411-7f77800e2681/metadata_test.go (about) 1 // Copyright 2024 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package yamlfmt_test 16 17 import ( 18 "errors" 19 "testing" 20 21 "github.com/google/yamlfmt" 22 "github.com/google/yamlfmt/internal/collections" 23 ) 24 25 type errorChecker func(t *testing.T, errs collections.Errors) 26 27 func checkErrNil(t *testing.T, errs collections.Errors) { 28 combinedErr := errs.Combine() 29 if combinedErr != nil { 30 t.Fatalf("expected error to be nil, got: %v", combinedErr) 31 } 32 } 33 34 func TestReadMetadata(t *testing.T) { 35 testCases := []struct { 36 name string 37 content string 38 expected collections.Set[yamlfmt.Metadata] 39 errCheck errorChecker 40 }{ 41 { 42 name: "contains no metadata", 43 content: "", 44 expected: collections.Set[yamlfmt.Metadata]{}, 45 errCheck: checkErrNil, 46 }, 47 { 48 name: "has ignore metadata", 49 content: "# !yamlfmt!:ignore\na: 1", 50 expected: collections.Set[yamlfmt.Metadata]{ 51 {Type: yamlfmt.MetadataIgnore, LineNum: 1}: {}, 52 }, 53 errCheck: checkErrNil, 54 }, 55 { 56 name: "has bad metadata", 57 content: "# !yamlfmt!fjghgh", 58 expected: collections.Set[yamlfmt.Metadata]{}, 59 errCheck: func(t *testing.T, errs collections.Errors) { 60 if len(errs) != 1 { 61 t.Fatalf("expected 1 error, got %d:\n%v", len(errs), errs.Combine()) 62 } 63 if errors.Unwrap(errs[0]) != yamlfmt.ErrMalformedMetadata { 64 t.Fatalf("expected ErrMalformedMetadata, got: %v", errs[0]) 65 } 66 }, 67 }, 68 { 69 name: "has unrecognized metadata type", 70 content: "# !yamlfmt!:lulsorandom", 71 expected: collections.Set[yamlfmt.Metadata]{}, 72 errCheck: func(t *testing.T, errs collections.Errors) { 73 if len(errs) != 1 { 74 t.Fatalf("expected 1 error, got %d:\n%v", len(errs), errs.Combine()) 75 } 76 if errors.Unwrap(errs[0]) != yamlfmt.ErrUnrecognizedMetadata { 77 t.Fatalf("expected ErrUnrecognizedMetadata, got: %v", errs[0]) 78 } 79 }, 80 }, 81 } 82 83 for _, tc := range testCases { 84 t.Run(tc.name, func(t *testing.T) { 85 md, err := yamlfmt.ReadMetadata([]byte(tc.content), "test.yaml") 86 if !md.Equals(tc.expected) { 87 t.Fatalf("Mismatched metadata:\nexpected: %v\ngot: %v", tc.expected, md) 88 } 89 t.Logf("got error: %v", err) 90 tc.errCheck(t, err) 91 }) 92 } 93 }