From 63d5a27b80fac3c63206652131e118efe4de6ed1 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Mon, 17 Apr 2017 16:25:59 +0200 Subject: [PATCH] Add 'now' function and function tests Signed-off-by: Knut Ahlers --- Makefile | 5 ++- functions/func_now.go | 9 +++++ functions/func_test.go | 77 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 1 deletion(-) create mode 100644 functions/func_now.go create mode 100644 functions/func_test.go diff --git a/Makefile b/Makefile index a44ded0..c1cb724 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,6 @@ -ci: +ci: test curl -sSLo golang.sh https://raw.githubusercontent.com/Luzifer/github-publish/master/golang.sh bash golang.sh + +test: + go test -v ./functions diff --git a/functions/func_now.go b/functions/func_now.go new file mode 100644 index 0000000..66076ca --- /dev/null +++ b/functions/func_now.go @@ -0,0 +1,9 @@ +package functions + +import "time" + +func init() { + registerFunction("now", func(name string, v ...string) string { + return time.Now().Format(name) + }) +} diff --git a/functions/func_test.go b/functions/func_test.go new file mode 100644 index 0000000..40ca439 --- /dev/null +++ b/functions/func_test.go @@ -0,0 +1,77 @@ +package functions + +import ( + "bytes" + "fmt" + "io/ioutil" + "math/rand" + "os" + "testing" + "text/template" + "time" +) + +func renderHelper(tpl string, ctx map[string]interface{}) string { + t, err := template.New("mytemplate").Funcs(GetFunctionMap()).Parse(tpl) + if err != nil { + panic(err) + } + + buf := bytes.NewBufferString("") + if err := t.Execute(buf, ctx); err != nil { + panic(err) + } + + return buf.String() +} + +func randomString() string { + const chars = "abcdefghijklmnopqrstuvwxyz0123456789" + r := rand.New(rand.NewSource(time.Now().UnixNano())) + + result := make([]byte, 32) + for i := range result { + result[i] = chars[r.Intn(len(chars))] + } + + return string(result) +} + +func Test_GetFunctionMap(t *testing.T) { + f := GetFunctionMap() + if f == nil || len(f) < 1 { + t.Fatal("No functions were registered.") + } +} + +func Test_env(t *testing.T) { + result := randomString() + os.Setenv("KORVIKE_TESTING", result) + + if r := renderHelper(`{{env "KORVIKE_TESTING"}}`, nil); r != result { + t.Errorf("[env] did not receive expected string: %q (expected %q)", r, result) + } +} + +func Test_file(t *testing.T) { + f, err := ioutil.TempFile("", "") + if err != nil { + panic(err) + } + + p := f.Name() + result := randomString() + fmt.Fprint(f, result) + f.Close() + defer os.Remove(p) + + if r := renderHelper(fmt.Sprintf("{{file %q}}", p), nil); r != result { + t.Errorf("[file] did not receive expected string: %q (expected %q)", r, result) + } +} + +func Test_now(t *testing.T) { + if _, err := time.Parse(time.RFC3339Nano, renderHelper(fmt.Sprintf("{{now %q}}", time.RFC3339Nano), nil)); err != nil { + t.Errorf("[now] did not produce expected time format") + } +}