github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/application/files_test.go (about) 1 // Copyright © 2023 Alibaba Group Holding Ltd. 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 application 16 17 import ( 18 "os" 19 "path/filepath" 20 "testing" 21 22 "github.com/google/go-cmp/cmp" 23 v2 "github.com/sealerio/sealer/types/api/v2" 24 ) 25 26 func Test_mergeProcessor_Process(t *testing.T) { 27 tests := []struct { 28 source string 29 patch string 30 expected string 31 wantErr bool 32 }{ 33 { 34 source: "a: b\nb: c", 35 patch: "b: d", 36 expected: "a: b\nb: d\n", 37 wantErr: false, 38 }, 39 { 40 source: "a: b\n## ---\nb: c", 41 patch: "b: d", 42 expected: "a: b\nb: d\n", 43 wantErr: false, 44 }, 45 { 46 source: "a: b\n---\nb: c", 47 patch: "b: d", 48 expected: "a: b\nb: d\n\n---\nb: d\n", 49 wantErr: false, 50 }, 51 } 52 // prepare a tmp dir to write test files 53 appRoot, err := os.MkdirTemp("", "sealer-unit-test") 54 if err != nil { 55 t.Fatal(err) 56 } 57 defer func() { 58 _ = os.RemoveAll(appRoot) 59 }() 60 61 testFile := filepath.Join(appRoot, "test.yaml") 62 for _, tt := range tests { 63 // prepare source file 64 f, err := os.Create(testFile) 65 if err != nil { 66 t.Fatal(err) 67 } 68 _, err = f.WriteString(tt.source) 69 if err != nil { 70 t.Fatal(err) 71 } 72 73 r := mergeProcessor{ 74 AppFile: v2.AppFile{ 75 Path: "test.yaml", 76 Strategy: v2.MergeStrategy, 77 Data: tt.patch, 78 }, 79 } 80 81 if err := r.Process(appRoot); err != nil && !tt.wantErr { 82 t.Errorf("mergeProcessor.Process() error = %v", err) 83 } else { 84 output, err := os.ReadFile(testFile) 85 if err != nil { 86 t.Fatal(err) 87 } 88 89 if diff := cmp.Diff(string(output), tt.expected); diff != "" { 90 t.Errorf("test failed expected=%s; output=%s; diff=%s", tt.expected, string(output), diff) 91 } 92 } 93 } 94 }