github.com/hashicorp/terraform-plugin-sdk@v1.17.2/internal/lang/funcs/datetime_test.go (about) 1 package funcs 2 3 import ( 4 "fmt" 5 "testing" 6 "time" 7 8 "github.com/zclconf/go-cty/cty" 9 ) 10 11 func TestTimestamp(t *testing.T) { 12 currentTime := time.Now().UTC() 13 result, err := Timestamp() 14 if err != nil { 15 t.Fatalf("err: %s", err) 16 } 17 resultTime, err := time.Parse(time.RFC3339, result.AsString()) 18 if err != nil { 19 t.Fatalf("Error parsing timestamp: %s", err) 20 } 21 22 if resultTime.Sub(currentTime).Seconds() > 10.0 { 23 t.Fatalf("Timestamp Diff too large. Expected: %s\nReceived: %s", currentTime.Format(time.RFC3339), result.AsString()) 24 } 25 26 } 27 28 func TestTimeadd(t *testing.T) { 29 tests := []struct { 30 Time cty.Value 31 Duration cty.Value 32 Want cty.Value 33 Err bool 34 }{ 35 { 36 cty.StringVal("2017-11-22T00:00:00Z"), 37 cty.StringVal("1s"), 38 cty.StringVal("2017-11-22T00:00:01Z"), 39 false, 40 }, 41 { 42 cty.StringVal("2017-11-22T00:00:00Z"), 43 cty.StringVal("10m1s"), 44 cty.StringVal("2017-11-22T00:10:01Z"), 45 false, 46 }, 47 { // also support subtraction 48 cty.StringVal("2017-11-22T00:00:00Z"), 49 cty.StringVal("-1h"), 50 cty.StringVal("2017-11-21T23:00:00Z"), 51 false, 52 }, 53 { // Invalid format timestamp 54 cty.StringVal("2017-11-22"), 55 cty.StringVal("-1h"), 56 cty.UnknownVal(cty.String), 57 true, 58 }, 59 { // Invalid format duration (day is not supported by ParseDuration) 60 cty.StringVal("2017-11-22T00:00:00Z"), 61 cty.StringVal("1d"), 62 cty.UnknownVal(cty.String), 63 true, 64 }, 65 } 66 67 for _, test := range tests { 68 t.Run(fmt.Sprintf("TimeAdd(%#v, %#v)", test.Time, test.Duration), func(t *testing.T) { 69 got, err := TimeAdd(test.Time, test.Duration) 70 71 if test.Err { 72 if err == nil { 73 t.Fatal("succeeded; want error") 74 } 75 return 76 } else if err != nil { 77 t.Fatalf("unexpected error: %s", err) 78 } 79 80 if !got.RawEquals(test.Want) { 81 t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) 82 } 83 }) 84 } 85 }