From 35186d5ddbfd47e81773ef95853f741e73763ff4 Mon Sep 17 00:00:00 2001 From: Arpit Jasapara <87999496+arpitjasa-db@users.noreply.github.com> Date: Thu, 6 Jun 2024 00:11:23 -0700 Subject: [PATCH] Add randIntn function (#1475) ## Changes Add support for `math/rand.Intn` to DAB templates. ## Tests Unit tests. --- libs/template/helpers.go | 5 +++++ libs/template/helpers_test.go | 19 +++++++++++++++++++ .../testdata/random-int/template/hello.tmpl | 1 + 3 files changed, 25 insertions(+) create mode 100644 libs/template/testdata/random-int/template/hello.tmpl diff --git a/libs/template/helpers.go b/libs/template/helpers.go index d15a801d..b3dea329 100644 --- a/libs/template/helpers.go +++ b/libs/template/helpers.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "math/rand" "net/url" "os" "regexp" @@ -46,6 +47,10 @@ func loadHelpers(ctx context.Context) template.FuncMap { "regexp": func(expr string) (*regexp.Regexp, error) { return regexp.Compile(expr) }, + // Alias for https://pkg.go.dev/math/rand#Intn. Returns, as an int, a non-negative pseudo-random number in the half-open interval [0,n). + "random_int": func(n int) int { + return rand.Intn(n) + }, // A key value pair. This is used with the map function to generate maps // to use inside a template "pair": func(k string, v any) pair { diff --git a/libs/template/helpers_test.go b/libs/template/helpers_test.go index a07b26f8..c0848c8d 100644 --- a/libs/template/helpers_test.go +++ b/libs/template/helpers_test.go @@ -3,6 +3,7 @@ package template import ( "context" "os" + "strconv" "strings" "testing" @@ -50,6 +51,24 @@ func TestTemplateRegexpCompileFunction(t *testing.T) { assert.Contains(t, content, "1:fool") } +func TestTemplateRandIntFunction(t *testing.T) { + ctx := context.Background() + tmpDir := t.TempDir() + + ctx = root.SetWorkspaceClient(ctx, nil) + helpers := loadHelpers(ctx) + r, err := newRenderer(ctx, nil, helpers, "./testdata/random-int/template", "./testdata/random-int/library", tmpDir) + require.NoError(t, err) + + err = r.walk() + assert.NoError(t, err) + + assert.Len(t, r.files, 1) + randInt, err := strconv.Atoi(strings.TrimSpace(string(r.files[0].(*inMemoryFile).content))) + assert.Less(t, randInt, 10) + assert.Empty(t, err) +} + func TestTemplateUrlFunction(t *testing.T) { ctx := context.Background() tmpDir := t.TempDir() diff --git a/libs/template/testdata/random-int/template/hello.tmpl b/libs/template/testdata/random-int/template/hello.tmpl new file mode 100644 index 00000000..46dc63fb --- /dev/null +++ b/libs/template/testdata/random-int/template/hello.tmpl @@ -0,0 +1 @@ +{{print (random_int 10)}}