@@ -2,11 +2,15 @@ package configtype_test
22
33import (
44 "encoding/json"
5+ "math/rand"
56 "testing"
67 "time"
78
89 "github.com/cloudquery/plugin-sdk/v4/configtype"
10+ "github.com/cloudquery/plugin-sdk/v4/plugin"
911 "github.com/google/go-cmp/cmp"
12+ "github.com/invopop/jsonschema"
13+ "github.com/stretchr/testify/require"
1014)
1115
1216func TestDuration (t * testing.T ) {
@@ -52,3 +56,74 @@ func TestComparability(t *testing.T) {
5256 }
5357 }
5458}
59+
60+ func TestDuration_JSONSchema (t * testing.T ) {
61+ sc := (& jsonschema.Reflector {RequiredFromJSONSchemaTags : true }).Reflect (configtype.Duration {})
62+ schema , err := json .MarshalIndent (sc , "" , " " )
63+ require .NoError (t , err )
64+
65+ validator , err := plugin .JSONSchemaValidator (string (schema ))
66+ require .NoError (t , err )
67+
68+ type testCase struct {
69+ Name string
70+ Spec string
71+ Err bool
72+ }
73+
74+ for _ , tc := range append ([]testCase {
75+ {
76+ Name : "empty" ,
77+ Err : true ,
78+ Spec : `""` ,
79+ },
80+ {
81+ Name : "null" ,
82+ Err : true ,
83+ Spec : `null` ,
84+ },
85+ {
86+ Name : "bad type" ,
87+ Err : true ,
88+ Spec : `false` ,
89+ },
90+ {
91+ Name : "bad format" ,
92+ Err : true ,
93+ Spec : `false` ,
94+ },
95+ },
96+ func () []testCase {
97+ rnd := rand .New (rand .NewSource (time .Now ().UnixNano ()))
98+ const (
99+ cases = 20
100+ maxDur = int64 (100 * time .Hour )
101+ maxDurHalf = maxDur / 2
102+ )
103+ result := make ([]testCase , cases )
104+ for i := 0 ; i < cases ; i ++ {
105+ val := rnd .Int63n (maxDur ) - maxDurHalf
106+ d := configtype .NewDuration (time .Duration (val ))
107+
108+ data , err := d .MarshalJSON ()
109+ require .NoError (t , err )
110+ result [i ] = testCase {
111+ Name : string (data ),
112+ Spec : string (data ),
113+ }
114+ }
115+ return result
116+ }()... ,
117+ ) {
118+ t .Run (tc .Name , func (t * testing.T ) {
119+ var val any
120+ err := json .Unmarshal ([]byte (tc .Spec ), & val )
121+ require .NoError (t , err )
122+ if tc .Err {
123+ require .Error (t , validator .Validate (val ))
124+ } else {
125+ require .NoError (t , validator .Validate (val ))
126+ }
127+ })
128+ }
129+ }
0 commit comments