Files
nomad/helper/hcl/parse_test.go
James Rasell c80c60965f node pool: Allow specifying node identity ttl in HCL or JSON spec. (#26825)
The node identity TTL defaults to 24hr but can be altered by
setting the node identity TTL parameter. In order to allow setting
and viewing the value, the field is now plumbed through the CLI
and HTTP API.

In order to parse the HCL, a new helper package has been created
which contains generic parsing and decoding functionality for
dealing with HCL that contains time durations. hclsimple can be
used when this functionality is not needed. In order to parse the
JSON, custom marshal and unmarshal functions have been created as
used in many other places.

The node pool init command has been updated to include this new
parameter, although commented out, so reference. The info command
now includes the TTL in its output too.
2025-09-24 14:20:34 +01:00

75 lines
1.7 KiB
Go

// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package hcl
import (
"testing"
"time"
"github.com/shoenig/test/must"
)
func TestParser_Parse_Duration(t *testing.T) {
type testConfig struct {
Interval time.Duration `hcl:"interval"`
Timeout *time.Duration `hcl:"timeout,optional"`
}
t.Run("string durations", func(t *testing.T) {
src := `
interval = "5s"
timeout = "2m"
`
var parsedConfig testConfig
p := NewParser()
diags := p.Parse([]byte(src), &parsedConfig, "durations.hcl")
must.False(t, diags.HasErrors())
must.Eq(t, 5*time.Second, parsedConfig.Interval)
must.Eq(t, 2*time.Minute, *parsedConfig.Timeout)
})
t.Run("numeric durations (nanoseconds)", func(t *testing.T) {
// 5s and 2m expressed directly in nanoseconds
src := `
interval = 5000000000
timeout = 120000000000
`
var parsedConfig testConfig
p := NewParser()
diags := p.Parse([]byte(src), &parsedConfig, "numeric.hcl")
must.False(t, diags.HasErrors())
must.Eq(t, 5*time.Second, parsedConfig.Interval)
must.Eq(t, 2*time.Minute, *parsedConfig.Timeout)
})
t.Run("invalid duration string", func(t *testing.T) {
src := `
interval = "notaduration"
`
var parsedConfig testConfig
p := NewParser()
diags := p.Parse([]byte(src), &parsedConfig, "invalid_string.hcl")
must.True(t, diags.HasErrors())
must.Len(t, 1, diags.Errs())
must.StrContains(t, diags.Error(), "Unsuitable duration value")
})
t.Run("wrong type", func(t *testing.T) {
src := `
interval = true
`
var parsedConfig testConfig
p := NewParser()
diags := p.Parse([]byte(src), &parsedConfig, "wrong_type.hcl")
must.True(t, diags.HasErrors())
must.Len(t, 1, diags.Errs())
must.StrContains(t, diags.Error(), "Unsuitable value: expected a string")
})
}