Skip to content

Commit

Permalink
Add randIntn function (#1475)
Browse files Browse the repository at this point in the history
## Changes
<!-- Summary of your changes that are easy to understand -->
Add support for `math/rand.Intn` to DAB templates.

## Tests
<!-- How is this tested? -->
Unit tests.
  • Loading branch information
arpitjasa-db authored Jun 6, 2024
1 parent 8c9fff3 commit 35186d5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions libs/template/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"math/rand"
"net/url"
"os"
"regexp"
Expand Down Expand Up @@ -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 {
Expand Down
19 changes: 19 additions & 0 deletions libs/template/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package template
import (
"context"
"os"
"strconv"
"strings"
"testing"

Expand Down Expand Up @@ -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()
Expand Down
1 change: 1 addition & 0 deletions libs/template/testdata/random-int/template/hello.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{print (random_int 10)}}

0 comments on commit 35186d5

Please sign in to comment.