go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/config/vars/vars_test.go (about) 1 // Copyright 2020 The LUCI Authors. 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 vars 16 17 import ( 18 "context" 19 "fmt" 20 "testing" 21 22 . "github.com/smartystreets/goconvey/convey" 23 . "go.chromium.org/luci/common/testing/assertions" 24 ) 25 26 func TestVarSet(t *testing.T) { 27 t.Parallel() 28 29 ctx := context.Background() 30 31 Convey("Works", t, func() { 32 vs := VarSet{} 33 vs.Register("a", func(context.Context) (string, error) { return "a_val", nil }) 34 vs.Register("b", func(context.Context) (string, error) { return "b_val", nil }) 35 36 out, err := vs.RenderTemplate(ctx, "${a}") 37 So(err, ShouldBeNil) 38 So(out, ShouldEqual, "a_val") 39 40 out, err = vs.RenderTemplate(ctx, "${a}${b}") 41 So(err, ShouldBeNil) 42 So(out, ShouldEqual, "a_valb_val") 43 44 out, err = vs.RenderTemplate(ctx, "${a}_${b}_${a}") 45 So(err, ShouldBeNil) 46 So(out, ShouldEqual, "a_val_b_val_a_val") 47 }) 48 49 Convey("Error in the callback", t, func() { 50 vs := VarSet{} 51 vs.Register("a", func(context.Context) (string, error) { return "", fmt.Errorf("boom") }) 52 53 _, err := vs.RenderTemplate(ctx, "zzz_${a}") 54 So(err, ShouldErrLike, "boom") 55 }) 56 57 Convey("Missing var", t, func() { 58 vs := VarSet{} 59 vs.Register("a", func(context.Context) (string, error) { return "a_val", nil }) 60 61 _, err := vs.RenderTemplate(ctx, "zzz_${a}_${zzz}_${a}") 62 So(err, ShouldErrLike, `no placeholder named "zzz" is registered`) 63 }) 64 65 Convey("Double registration", t, func() { 66 vs := VarSet{} 67 vs.Register("a", func(context.Context) (string, error) { return "a_val", nil }) 68 69 So(func() { vs.Register("a", func(context.Context) (string, error) { return "a_val", nil }) }, ShouldPanic) 70 }) 71 }