Skip to content

Commit

Permalink
stub panicking from generate
Browse files Browse the repository at this point in the history
  • Loading branch information
endorama committed Feb 16, 2023
1 parent 4114f37 commit 3aa3d48
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
3 changes: 2 additions & 1 deletion pkg/genlib/generator_with_text_template.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package genlib

import (
"bytes"
"fmt"
"github.com/Masterminds/sprig/v3"
"text/template"
"time"
Expand Down Expand Up @@ -40,7 +41,7 @@ func NewGeneratorWithTextTemplate(tpl []byte, cfg Config, fields Fields) (*Gener
templateFns["generate"] = func(field string) interface{} {
bindF, ok := fieldMap[field]
if !ok {
return "<missing field>"
panic(fmt.Errorf("missing field: '%s' (is it present in fields.yml?)", field))
}

value, err := bindF(state, nil)
Expand Down
22 changes: 16 additions & 6 deletions pkg/genlib/generator_with_text_template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -364,12 +364,7 @@ func testSingleTWithTextTemplate[T any](t *testing.T, fld Field, yaml []byte, te
t.Errorf("Expected map size 1, got %d", len(m))
}

v, ok := m[fld.Name]

if !ok {
t.Errorf("Missing key %v", fld.Name)

}
v, _ := m[fld.Name]

return v
}
Expand All @@ -383,3 +378,18 @@ func makeGeneratorWithTextTemplate(t *testing.T, cfg Config, fields Fields, temp

return g, NewGenState()
}

func Test_PanicOnMissingField(t *testing.T) {
fld := Field{}

template := []byte(`{"alpha":"{{generate "alpha"}}"}`)
t.Logf("with template: %s", string(template))

defer func() {
r := recover()
t.Log(r)
}()
a := testSingleTWithTextTemplate[string](t, fld, nil, template)
fmt.Printf("a: %s\n", a)
t.Errorf("should have triggered a panic")
}

0 comments on commit 3aa3d48

Please sign in to comment.