mirror of https://github.com/databricks/cli.git
Add randIntn function (#1475)
## 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.
This commit is contained in:
parent
8c9fff3cb9
commit
35186d5ddb
|
@ -4,6 +4,7 @@ import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math/rand"
|
||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
@ -46,6 +47,10 @@ func loadHelpers(ctx context.Context) template.FuncMap {
|
||||||
"regexp": func(expr string) (*regexp.Regexp, error) {
|
"regexp": func(expr string) (*regexp.Regexp, error) {
|
||||||
return regexp.Compile(expr)
|
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
|
// A key value pair. This is used with the map function to generate maps
|
||||||
// to use inside a template
|
// to use inside a template
|
||||||
"pair": func(k string, v any) pair {
|
"pair": func(k string, v any) pair {
|
||||||
|
|
|
@ -3,6 +3,7 @@ package template
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
@ -50,6 +51,24 @@ func TestTemplateRegexpCompileFunction(t *testing.T) {
|
||||||
assert.Contains(t, content, "1:fool")
|
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) {
|
func TestTemplateUrlFunction(t *testing.T) {
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
tmpDir := t.TempDir()
|
tmpDir := t.TempDir()
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
{{print (random_int 10)}}
|
Loading…
Reference in New Issue