github.com/hashicorp/packer@v1.14.3/hcl2template/function/datetime_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: BUSL-1.1 3 4 package function 5 6 import ( 7 "fmt" 8 "regexp" 9 "testing" 10 "time" 11 12 "github.com/zclconf/go-cty/cty" 13 ) 14 15 // HCL template usage example: 16 // 17 // locals { 18 // emptyformat = legacy_isotime() 19 // golangformat = legacy_isotime("01-02-2006") 20 // } 21 22 func TestLegacyIsotime_empty(t *testing.T) { 23 got, err := LegacyIsotimeFunc.Call([]cty.Value{}) 24 if err != nil { 25 t.Fatalf("unexpected error: %s", err) 26 } 27 28 _, err = time.Parse(time.RFC3339, got.AsString()) 29 if err != nil { 30 t.Fatalf("Didn't get an RFC3339 string from empty case: %s", err) 31 } 32 33 } 34 35 func TestLegacyIsotime_inputs(t *testing.T) { 36 tests := []struct { 37 Value cty.Value 38 Want string 39 }{ 40 { 41 cty.StringVal("01-02-2006"), 42 `^\d{2}-\d{2}-\d{4}$`, 43 }, 44 { 45 cty.StringVal("Mon Jan 02, 2006"), 46 `^(Mon|Tue|Wed|Thu|Fri|Sat|Sun){1} (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec){1} \d{2}, \d{4}$`, 47 }, 48 } 49 50 for _, test := range tests { 51 t.Run(fmt.Sprintf("legacy_isotime(%#v)", test.Value), func(t *testing.T) { 52 got, err := LegacyIsotime(test.Value) 53 54 if err != nil { 55 t.Fatalf("unexpected error: %s", err) 56 } 57 re, err := regexp.Compile(test.Want) 58 if err != nil { 59 t.Fatalf("Bad regular expression test string: %#v", err) 60 } 61 62 if !re.MatchString(got.AsString()) { 63 t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) 64 } 65 }) 66 } 67 }