diff --git a/.changesets/1792662097-11a83540.yaml b/.changesets/1792662097-11a83540.yaml new file mode 100644 index 000000000..d184a4721 --- /dev/null +++ b/.changesets/1792662097-11a83540.yaml @@ -0,0 +1,11 @@ +id: 1792662097-11a83540 +features: + - constArrays + - constObjects +targets: + - terraform +type: feat +bump: minor +description: array and map properties with a const value are hidden from the resource schema and the const value is sent in request bodies +author: AshGodfrey +date: "2026-10-22" diff --git a/.changesets/1792662097-2435dcc7.yaml b/.changesets/1792662097-2435dcc7.yaml new file mode 100644 index 000000000..85ab04639 --- /dev/null +++ b/.changesets/1792662097-2435dcc7.yaml @@ -0,0 +1,11 @@ +id: 1792662097-2435dcc7 +features: + - constsAndDefaults +targets: + - go + - cli +type: fix +bump: patch +description: JSON unmarshaling compares array and map const values structurally instead of by exact text and treats null as absent for a container const +author: AshGodfrey +date: "2026-10-22" diff --git a/internal/features/features.go b/internal/features/features.go index ff07148e8..1bc3574f0 100644 --- a/internal/features/features.go +++ b/internal/features/features.go @@ -149,6 +149,12 @@ const ( // FeatureDefaultObjects relates to the ability to handle default values for objects // Tier: Experimental FeatureDefaultObjects + // FeatureConstArrays relates to the ability to handle const values for arrays + // Tier: Experimental + FeatureConstArrays + // FeatureConstObjects relates to the ability to handle const values for objects + // Tier: Experimental + FeatureConstObjects // FeatureAdditionalProperties relates to the ability to deserialize any unknown properties into a map available as an extra property on the generated models for both request bodies and parameters // Tier: Gold FeatureAdditionalProperties diff --git a/internal/features/features_generated.go b/internal/features/features_generated.go index a3bb2c2ec..1c7661d2e 100644 --- a/internal/features/features_generated.go +++ b/internal/features/features_generated.go @@ -20,6 +20,10 @@ func (f Feature) String() string { return "callbacks" case FeatureConfigurableModuleName: return "configurableModuleName" + case FeatureConstArrays: + return "constArrays" + case FeatureConstObjects: + return "constObjects" case FeatureConstsAndDefaults: return "constsAndDefaults" case FeatureContentMediaTypeApplicationJSON: @@ -198,6 +202,10 @@ func FeatureFromString(s string) Feature { return FeatureCallbacks case "configurableModuleName": return FeatureConfigurableModuleName + case "constArrays": + return FeatureConstArrays + case "constObjects": + return FeatureConstObjects case "constsAndDefaults": return FeatureConstsAndDefaults case "contentMediaTypeApplicationJSON": @@ -367,6 +375,8 @@ var featureList = []Feature{ FeatureCLICommands, FeatureCallbacks, FeatureConfigurableModuleName, + FeatureConstArrays, + FeatureConstObjects, FeatureConstsAndDefaults, FeatureContentMediaTypeApplicationJSON, FeatureCore, @@ -456,6 +466,8 @@ var featureTiers = map[Feature]string{ FeatureCLICommands: TierExperimental, FeatureCallbacks: TierCore, FeatureConfigurableModuleName: TierExperimental, + FeatureConstArrays: TierExperimental, + FeatureConstObjects: TierExperimental, FeatureConstsAndDefaults: TierBeta, FeatureContentMediaTypeApplicationJSON: TierExperimental, FeatureCore: TierCore, @@ -571,6 +583,8 @@ var tierCoreFeatures = []Feature{ var tierExperimentalFeatures = []Feature{ FeatureCLICommands, FeatureConfigurableModuleName, + FeatureConstArrays, + FeatureConstObjects, FeatureContentMediaTypeApplicationJSON, FeatureCustomCodeRegions, FeatureCustomSecuritySchemes, diff --git a/internal/schemas/handle_array_test.go b/internal/schemas/handle_array_test.go index 5f8943a9a..39f1dff33 100644 --- a/internal/schemas/handle_array_test.go +++ b/internal/schemas/handle_array_test.go @@ -2,12 +2,14 @@ package schemas import ( "context" + "strings" "testing" "github.com/speakeasy-api/openapi-generation/v2/internal/ast" "github.com/speakeasy-api/openapi-generation/v2/internal/features" "github.com/speakeasy-api/openapi-generation/v2/internal/testutils" "github.com/speakeasy-api/openapi-generation/v2/internal/types" + "github.com/speakeasy-api/openapi-generation/v2/pkg/logging" "github.com/speakeasy-api/openapi/pointer" config "github.com/speakeasy-api/sdk-gen-config" "github.com/stretchr/testify/assert" @@ -15,6 +17,21 @@ import ( "gopkg.in/yaml.v3" ) +func assertSingleWarning(t *testing.T, warnings []error, expected string) { + t.Helper() + if expected == "" { + require.Empty(t, warnings) + return + } + var matched []error + for _, warning := range warnings { + if strings.Contains(warning.Error(), expected) { + matched = append(matched, warning) + } + } + require.Len(t, matched, 1, "warnings: %v", warnings) +} + // TestHandleArray tests the handleArray method with various array scenarios func TestHandleArray(t *testing.T) { tests := []struct { @@ -24,7 +41,10 @@ func TestHandleArray(t *testing.T) { fixes *config.Fixes // nil means use default mockFeatures func() *testutils.MockFeaturesConfig // nil means use default (all features supported) isRequest *bool // nil means use default (false), otherwise use specified value + paramType ParamType // empty means a body property expected *ast.FieldDef + // expectedWarning, when set, must match exactly one logged validation warning + expectedWarning string }{ { name: "StringArray", @@ -69,6 +89,543 @@ func TestHandleArray(t *testing.T) { Build()). Build(), }, + { + name: "ArrayWithConst", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: + - read + - write`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + WithConst(&ast.AnyValue{Value: []interface{}{"read", "write"}}). + Build(), + }, + { + name: "ArrayWithEmptyConst", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: []`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + WithConst(&ast.AnyValue{Value: []interface{}{}}). + Build(), + }, + { + name: "ArrayWithConstFeatureUnsupported", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: []`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + }, + { + name: "ArrayWithConstItemTypeMismatch", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: + - 1`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "SetWithConst", + schemasYAML: `TestSchema: + type: array + items: + type: string + uniqueItems: true + const: + - read`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{ + UniqueItems: pointer.From(true), + }). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "UniqueItemsArrayWithEmptyConst", + schemasYAML: `TestSchema: + type: array + items: + type: string + uniqueItems: true + const: []`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{ + UniqueItems: pointer.From(true), + }). + Build()). + WithConst(&ast.AnyValue{Value: []interface{}{}}). + Build(), + }, + { + name: "UniqueItemsArrayWithEmptyConstAndMinItems", + schemasYAML: `TestSchema: + type: array + items: + type: string + uniqueItems: true + minItems: 1 + const: []`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{ + UniqueItems: pointer.From(true), + MinItems: pointer.From[int64](1), + }). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstBelowMinItems", + schemasYAML: `TestSchema: + type: array + items: + type: string + minItems: 2 + const: + - read`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{ + MinItems: pointer.From[int64](2), + }). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstAboveMaxItems", + schemasYAML: `TestSchema: + type: array + items: + type: string + maxItems: 1 + const: + - read + - write`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{ + MaxItems: pointer.From[int64](1), + }). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "QueryParameterArrayWithConst", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: + - all`, + schemaName: "TestSchema", + paramType: ParamTypeQuery, + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only request and response body properties honor container const values, omitting const", + }, + { + name: "SetFormatWithEmptyConst", + schemasYAML: `TestSchema: + type: array + format: set + items: + type: string + const: []`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig().WithTarget(types.Target{Target: "go"}) + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureSets: true, + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeSet). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 12, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + WithConst(&ast.AnyValue{Value: []interface{}{}}). + Build(), + }, + { + name: "SetFormatWithConst", + schemasYAML: `TestSchema: + type: array + format: set + items: + type: string + const: + - read`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig().WithTarget(types.Target{Target: "go"}) + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureSets: true, + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeSet). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 12, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstNull", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: null`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstMixedItems", + schemasYAML: `TestSchema: + type: array + items: + type: string + const: + - read + - 1`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstEnumItemTypeMismatch", + schemasYAML: `TestSchema: + type: array + items: + type: integer + enum: + - 1 + - 2 + const: + - "1"`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + features.FeatureEnums: true, + } + return config + }, + expected: testutils.NewFieldDef("enums", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewEnumTypeDef(ast.DataTypeInteger, []string{"1", "2"}, ""). + WithScope(ast.ScopeShared). + WithRegistered(). + WithOriginalNameFrozen(). + WithContextStack(ast.ContextStack{}). + WithEnumUnderlyingLocation(&yaml.Node{Line: 11, Column: 9}). + Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstBigIntItems", + schemasYAML: `TestSchema: + type: array + items: + type: integer + format: bigint + const: + - 1`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + features.FeatureBigInt: true, + } + return config + }, + expected: testutils.NewFieldDef("bigints", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeBigInt).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "ArrayWithConstUUIDItems", + schemasYAML: `TestSchema: + type: array + items: + type: string + format: uuid + const: + - 123e4567-e89b-12d3-a456-426614174000`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("uuids", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeUUID).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + WithConst(&ast.AnyValue{Value: []interface{}{"123e4567-e89b-12d3-a456-426614174000"}}). + Build(), + }, + { + name: "ArrayWithDefaultAndConst", + schemasYAML: `TestSchema: + type: array + items: + type: string + default: + - read + const: + - read`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + features.FeatureDefaultArrays: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + WithDefault(&ast.AnyValue{Value: []interface{}{"read"}}). + WithOptional(true). + WithConst(&ast.AnyValue{Value: []interface{}{"read"}}). + Build(), + }, + { + name: "NestedArrayWithConst", + schemasYAML: `TestSchema: + type: array + items: + type: array + items: + type: string + const: + - - read`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("arrays", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType( + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 13, Column: 11}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 11, Column: 9}). + WithValidations(&ast.Validations{}). + Build(), + ). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, { name: "ArrayWithMinMaxItems", schemasYAML: `TestSchema: @@ -165,6 +722,34 @@ func TestHandleArray(t *testing.T) { Build()). Build(), }, + { + name: "ArrayWithConstNullableItems", + schemasYAML: `TestSchema: + type: array + items: + type: string + nullable: true + const: + - read`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstArrays: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("strings", + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 11, Column: 9}).WithValidations(&ast.Validations{}).Build()). + WithContainsNull(true). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithValidations(&ast.Validations{}). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, { name: "ArrayWithExample", schemasYAML: `TestSchema: @@ -307,13 +892,18 @@ TestSchema: // Create test parameters params := CreateTestParams(testSchema, common.DocInfo) + params.ParamType = tt.paramType if tt.isRequest != nil { params.IsRequest = *tt.isRequest } + warningLogger := logging.NewWarningLogger(false, nil) + ctx := logging.WithWarningLogger(context.Background(), warningLogger) + // Call HandleSchema - let it handle nullable extraction and routing - result, err := schemas.HandleSchema(context.Background(), params) + result, err := schemas.HandleSchema(ctx, params) require.NoError(t, err) + assertSingleWarning(t, warningLogger.GetWarnings(), tt.expectedWarning) // Use deep comparison from the working test isEqual := testutils.DeepCompare(t, tt.expected, result) diff --git a/internal/schemas/handle_object_test.go b/internal/schemas/handle_object_test.go index bce54b65d..98ec89070 100644 --- a/internal/schemas/handle_object_test.go +++ b/internal/schemas/handle_object_test.go @@ -7,6 +7,7 @@ import ( "github.com/speakeasy-api/openapi-generation/v2/internal/ast" "github.com/speakeasy-api/openapi-generation/v2/internal/features" "github.com/speakeasy-api/openapi-generation/v2/internal/testutils" + "github.com/speakeasy-api/openapi-generation/v2/pkg/logging" config "github.com/speakeasy-api/sdk-gen-config" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -24,6 +25,8 @@ func TestHandleObject(t *testing.T) { isRequest *bool // nil means use default (false), otherwise use specified value serializationMethod *ast.SerializationMethod // nil means use default (JSON) expected *ast.FieldDef + // expectedWarning, when set, must match exactly one logged validation warning + expectedWarning string }{ { name: "BasicObject", @@ -245,6 +248,194 @@ func TestHandleObject(t *testing.T) { Build()). Build(), }, + { + name: "MapWithConst", + schemasYAML: `TestSchema: + type: object + additionalProperties: + type: string + const: + key: value`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstObjects: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("object", + testutils.NewTypeDef(ast.DataTypeMap). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithItemType( + testutils.NewTypeDef(ast.DataTypeString). + WithLocation(&yaml.Node{Line: 11, Column: 9}). + WithValidations(&ast.Validations{}). + Build(), + ). + Build()). + WithConst(&ast.AnyValue{Value: map[string]interface{}{"key": "value"}}). + Build(), + }, + { + name: "MapWithConstFeatureUnsupported", + schemasYAML: `TestSchema: + type: object + additionalProperties: + type: string + const: {}`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("object", + testutils.NewTypeDef(ast.DataTypeMap). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithItemType( + testutils.NewTypeDef(ast.DataTypeString). + WithLocation(&yaml.Node{Line: 11, Column: 9}). + WithValidations(&ast.Validations{}). + Build(), + ). + Build()). + Build(), + }, + { + name: "ObjectWithUnsupportedConst", + schemasYAML: `TestSchema: + type: object + properties: + name: + type: string + const: + name: "fixed"`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstObjects: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("object", + testutils.NewTypeDef(ast.DataTypeClass). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithScope(ast.ScopeShared). + WithRegistered(). + WithOriginalNameFrozen(). + WithContextStack(ast.ContextStack{}). + WithFields( + testutils.NewFieldDef("name", + testutils.NewTypeDef(ast.DataTypeString). + WithLocation(&yaml.Node{Line: 12, Column: 11}). + WithValidations(&ast.Validations{}). + Build()). + WithOriginalName("name"). + WithJSONAnnotation("name"). + WithOptional(true). + Build(), + ). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "MapWithConstFreeFormValues", + schemasYAML: `TestSchema: + type: object + additionalProperties: true + const: + key: value`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstObjects: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("object", + testutils.NewTypeDef(ast.DataTypeMap). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithItemType( + testutils.NewTypeDef(ast.DataTypeAny). + Build(), + ). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "MapWithConstArrayValues", + schemasYAML: `TestSchema: + type: object + additionalProperties: + type: array + items: + type: string + const: + key: + - value`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstObjects: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("object", + testutils.NewTypeDef(ast.DataTypeMap). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithItemType( + testutils.NewTypeDef(ast.DataTypeArray). + WithItemType(testutils.NewTypeDef(ast.DataTypeString).WithLocation(&yaml.Node{Line: 13, Column: 11}).WithValidations(&ast.Validations{}).Build()). + WithLocation(&yaml.Node{Line: 11, Column: 9}). + WithValidations(&ast.Validations{}). + Build(), + ). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, + { + name: "MapWithConstValueTypeMismatch", + schemasYAML: `TestSchema: + type: object + additionalProperties: + type: integer + const: + key: value`, + schemaName: "TestSchema", + mockFeatures: func() *testutils.MockFeaturesConfig { + config := testutils.NewMockFeaturesConfig() + config.SupportedFeatures = map[features.Feature]bool{ + features.FeatureConstObjects: true, + features.FeatureConstsAndDefaults: true, + } + return config + }, + expected: testutils.NewFieldDef("object", + testutils.NewTypeDef(ast.DataTypeMap). + WithLocation(&yaml.Node{Line: 9, Column: 7}). + WithItemType( + testutils.NewTypeDef(ast.DataTypeInteger). + WithLocation(&yaml.Node{Line: 11, Column: 9}). + WithValidations(&ast.Validations{}). + Build(), + ). + Build()). + Build(), + expectedWarning: "only arrays without uniqueItems and maps of scalar values are supported, omitting const", + }, { name: "ObjectWithExample", schemasYAML: `TestSchema: @@ -2708,9 +2899,13 @@ TestSchema: params.IsRequest = *tt.isRequest } + warningLogger := logging.NewWarningLogger(false, nil) + ctx := logging.WithWarningLogger(context.Background(), warningLogger) + // Call HandleSchema - let it handle nullable extraction and routing - result, err := schemas.HandleSchema(context.Background(), params) + result, err := schemas.HandleSchema(ctx, params) require.NoError(t, err) + assertSingleWarning(t, warningLogger.GetWarnings(), tt.expectedWarning) // Use deep comparison from the working test isEqual := testutils.DeepCompare(t, tt.expected, result) diff --git a/internal/schemas/schemas.go b/internal/schemas/schemas.go index eb6e53003..f420e5f2f 100644 --- a/internal/schemas/schemas.go +++ b/internal/schemas/schemas.go @@ -562,9 +562,7 @@ func (s *Schemas) handleArray(ctx context.Context, params Params, nullable bool) Optional: nullable, Nullable: nullable, } - if s.Subsystem.Features.IsFeatureSupported(ctx, features.FeatureDefaultArrays) && schema.Default != nil { - fieldDef = s.handleFieldDefMetaData(ctx, fieldDef, nullable, schema) - } + fieldDef = s.handleContainerMetaData(ctx, params, fieldDef, nullable, schema, s.Subsystem.Features.IsFeatureSupported(ctx, features.FeatureDefaultArrays), features.FeatureConstArrays) // We need to inherit the multipart annotations if itemField != nil { @@ -818,12 +816,12 @@ func (s *Schemas) handleObject(ctx context.Context, params Params, nullable bool typeDef.Extensions = extensions - return &ast.FieldDef{ + return s.handleContainerMetaData(ctx, params, &ast.FieldDef{ Name: fieldName, Type: ast.NewType(typeDef, nil), Optional: nullable, Nullable: nullable, - }, nil + }, nullable, schema, false, features.FeatureConstObjects), nil } case recurseAdditionalProperties: additionalPropertiesParams := params @@ -891,12 +889,12 @@ func (s *Schemas) handleObject(ctx context.Context, params Params, nullable bool typeDef.Extensions = extensions - return &ast.FieldDef{ + return s.handleContainerMetaData(ctx, params, &ast.FieldDef{ Name: fieldName, Type: ast.NewType(typeDef, nil), Optional: nullable, Nullable: nullable, - }, nil + }, nullable, schema, false, features.FeatureConstObjects), nil } } } @@ -1298,9 +1296,7 @@ func (s *Schemas) handleObject(ctx context.Context, params Params, nullable bool Nullable: nullable, } - if s.Subsystem.Features.IsFeatureSupported(ctx, features.FeatureDefaultObjects) && schema.Default != nil { - fieldDef = s.handleFieldDefMetaData(ctx, fieldDef, nullable, schema) - } + fieldDef = s.handleContainerMetaData(ctx, params, fieldDef, nullable, schema, s.Subsystem.Features.IsFeatureSupported(ctx, features.FeatureDefaultObjects), features.FeatureConstObjects) s.setCachedType(fieldType, ¶ms) @@ -1652,6 +1648,18 @@ func (s *Schemas) checkDefaultConformsToType(ctx context.Context, field *ast.Fie if v == nil { continue } + + if pair.label == "const" && (field.Type.IsContainer() || field.Type.Type == ast.DataTypeClass) { + if !constContainerValueSupported(v.Value, field.Type) { + logging.LogWarning(ctx, "validation warning", errors.NewValidationWarning( + fmt.Sprintf("const value %v is not supported for type %q, only arrays without uniqueItems and maps of scalar values are supported, omitting const", v.Value, dataType), + schema.GetPropertyNode("Const"), nil, + )) + *pair.val = nil + } + continue + } + // null is a valid default for nullable fields if v.Value == nil && field.Nullable { continue @@ -1681,6 +1689,74 @@ func (s *Schemas) checkDefaultConformsToType(ctx context.Context, field *ast.Fie } } +func constContainerValueSupported(val any, typ *ast.TypeDef) bool { + if val == nil || typ.ContainsNull { + return false + } + + switch typ.Type { + case ast.DataTypeArray, ast.DataTypeSet: + items, ok := val.([]any) + if !ok { + return false + } + count := int64(len(items)) + if typ.Validations != nil { + if typ.Validations.MinItems != nil && count < *typ.Validations.MinItems { + return false + } + if typ.Validations.MaxItems != nil && count > *typ.Validations.MaxItems { + return false + } + } + if count == 0 { + return true + } + if typ.Type == ast.DataTypeSet || (typ.Validations != nil && typ.Validations.UniqueItems != nil && *typ.Validations.UniqueItems) { + return false + } + for _, item := range items { + if !constScalarMatchesType(item, typ.ItemType) { + return false + } + } + return true + case ast.DataTypeMap: + entries, ok := val.(map[string]any) + if !ok { + return false + } + for _, item := range entries { + if !constScalarMatchesType(item, typ.ItemType) { + return false + } + } + return true + default: + return false + } +} + +func constScalarMatchesType(val any, itemType *ast.TypeDef) bool { + if val == nil || itemType == nil { + return false + } + + switch itemType.Type { + case ast.DataTypeEnum: + if itemType.Enum == nil || itemType.Enum.Type == nil || !defaultValueMatchesType(val, itemType.Enum.Type.Type) { + return false + } + return slices.Contains(itemType.Enum.Values, fmt.Sprint(val)) + case ast.DataTypeInteger, ast.DataTypeInt32, ast.DataTypeNumber, ast.DataTypeFloat32: + return itemType.Format != "string" && defaultValueMatchesType(val, itemType.Type) + case ast.DataTypeBoolean, ast.DataTypeString, ast.DataTypeDate, ast.DataTypeDateTime, ast.DataTypeUUID, ast.DataTypeDuration: + return defaultValueMatchesType(val, itemType.Type) + default: + return false + } +} + // defaultValueMatchesType checks whether a decoded default/const value is compatible // with the given AST data type. func defaultValueMatchesType(val any, dataType ast.DataType) bool { @@ -2752,6 +2828,35 @@ func (s *Schemas) handleFieldDefMetaData(ctx context.Context, fieldDef *ast.Fiel return fieldDef } +func (s *Schemas) handleContainerMetaData(ctx context.Context, params Params, fieldDef *ast.FieldDef, nullable bool, schema *oas3.Schema, defaultSupported bool, constFeature features.Feature) *ast.FieldDef { + applyDefault := schema.Default != nil && defaultSupported + applyConst := schema.Const != nil && s.Subsystem.Features.IsFeatureSupported(ctx, constFeature) + if applyConst && params.ParamType != "" { + logging.LogWarning(ctx, "validation warning", errors.NewValidationWarning( + fmt.Sprintf("const on a %s parameter of type %q is not supported, only request and response body properties honor container const values, omitting const", params.ParamType, fieldDef.Type.Type), + schema.GetPropertyNode("Const"), nil, + )) + applyConst = false + } + if !applyDefault && !applyConst { + return fieldDef + } + + fieldDef = s.handleFieldDefMetaData(ctx, fieldDef, nullable, schema) + if !applyDefault { + fieldDef.Default = nil + fieldDef.Optional = nullable + } + if !applyConst { + fieldDef.Const = nil + } + if fieldDef.Const != nil { + s.Subsystem.Features.RecordFeatureUsage(ctx, constFeature) + } + + return fieldDef +} + func (s *Schemas) sanitizeDefaultConstValue(ctx context.Context, value values.Value) *ast.AnyValue { if value == nil { return nil diff --git a/pkg/generate/parameters.go b/pkg/generate/parameters.go index 48f6b4a4f..ad7e9f7e7 100644 --- a/pkg/generate/parameters.go +++ b/pkg/generate/parameters.go @@ -508,6 +508,19 @@ func (g *Generator) handleQueryParameters(ctx context.Context, opts handleSpecif return queryParams, globalParams, nil } +func schemaParamType(paramType string) schemas.ParamType { + switch paramType { + case ast.ParamTypePathParam: + return schemas.ParamTypePath + case ast.ParamTypeQueryParam: + return schemas.ParamTypeQuery + case ast.ParamTypeHeader: + return schemas.ParamTypeHeader + default: + return "" + } +} + func (g *Generator) handleContentParameter(ctx context.Context, paramType string, contextStack ast.ContextStack, rp *oas.ReferencedParameter, globalNameOverrides []*extensions.NameOverride, scope ast.Scope, docInfo *document.DocumentInfo) (*param, error) { p := rp.MustGetObject() @@ -539,6 +552,7 @@ func (g *Generator) handleContentParameter(ctx context.Context, paramType string paramField, err := g.schemas.HandleSchema(ctx, schemas.Params{ ContextStack: addPropScope(contextStack, rp), SerializationMethod: ast.SerializationMethodJSON, + ParamType: schemaParamType(paramType), Schema: schema, Scope: s, IsRequest: true, diff --git a/templates/templates/common/common/examples.ts b/templates/templates/common/common/examples.ts index cabaac2ae..798b3b516 100644 --- a/templates/templates/common/common/examples.ts +++ b/templates/templates/common/common/examples.ts @@ -547,7 +547,7 @@ function calculateExample( // If we have a const value always use this as nothing else is valid if (fieldDef.Const) { - example = fieldDef.Const.Value; + example = withSortedKeys(fieldDef.Const.Value); } // If we have no example try to find a source @@ -2326,3 +2326,19 @@ function getExampleByName(examples: Example[], name: string): Example | null { function getExampleFileDeclaration() { return `${FILE_DIRECTIVE_KEY} ${EXAMPLE_FILE}`; } + +// Values decoded from the document into Go maps reach templates with an +// unstable key order; rebuild them so rendered output is deterministic. +function withSortedKeys(value: any): any { + if (Array.isArray(value)) { + return value.map(withSortedKeys); + } + if (value !== null && typeof value === "object") { + const sorted: Record = Object.create(null); + for (const key of Object.keys(value).sort()) { + sorted[key] = withSortedKeys(value[key]); + } + return sorted; + } + return value; +} diff --git a/templates/templates/common/common/features.d.ts b/templates/templates/common/common/features.d.ts index faa544746..773e3374e 100644 --- a/templates/templates/common/common/features.d.ts +++ b/templates/templates/common/common/features.d.ts @@ -15,6 +15,8 @@ declare global { | "cliCommands" | "callbacks" | "configurableModuleName" + | "constArrays" + | "constObjects" | "constsAndDefaults" | "contentMediaTypeApplicationJSON" | "core" diff --git a/templates/templates/common/go/annotations.ts b/templates/templates/common/go/annotations.ts index 2cd84f59f..f4fcfec09 100644 --- a/templates/templates/common/go/annotations.ts +++ b/templates/templates/common/go/annotations.ts @@ -295,10 +295,6 @@ function templateFormAnnotation( function templateConstsAndDefaultsAnnotation( fieldDef: FieldDef, ): TemplatedAnnotation | null { - if (fieldDef.Type.IsContainer()) { - return null; - } - function sanitizeValue(value: any): string { if (value === null) { return "null"; @@ -311,6 +307,19 @@ function templateConstsAndDefaultsAnnotation( return value; } + if (fieldDef.Type.IsContainer()) { + if (fieldDef.Const) { + return { + Tag: "const", + Value: sanitizeValue( + JSON.stringify(withSortedKeys(fieldDef.Const.Value)), + ), + }; + } + + return null; + } + if (fieldDef.Const) { return { Tag: "const", diff --git a/templates/templates/common/go/sanitization.ts b/templates/templates/common/go/sanitization.ts index 0fa062913..850a04f49 100644 --- a/templates/templates/common/go/sanitization.ts +++ b/templates/templates/common/go/sanitization.ts @@ -736,6 +736,10 @@ function templateConstValue( useTypesPackage: true, skipPointerWrapping, }); + case "array": + case "set": + case "map": + return templateConstContainerValue(fieldDef, usageLocation); case "bytes": default: throw new Error( @@ -746,6 +750,40 @@ function templateConstValue( registerTemplateFunc("templateConstValue", templateConstValue); +function templateConstContainerValue( + fieldDef: FieldDef, + usageLocation: string, +): string { + const containerType = sanitizeType(fieldDef.Type, false, usageLocation); + const renderItem = (value: any): string => + templateConstValue( + { + ...fieldDef, + Type: fieldDef.Type.ItemType, + Optional: false, + Nullable: false, + Const: { Value: value }, + } as FieldDef, + usageLocation, + true, + ); + + if (fieldDef.Type.Type.toString() === "map") { + const entries = Object.entries( + withSortedKeys(fieldDef.Const.Value ?? {}), + ).map( + ([key, value]) => + `${JSON.stringify(key).replaceAll("{{", `{{"{{"}}`)}: ${renderItem( + value, + )}`, + ); + return `${containerType}{${entries.join(", ")}}`; + } + + const items = ((fieldDef.Const.Value ?? []) as any[]).map(renderItem); + return `${containerType}{${items.join(", ")}}`; +} + // @ts-ignore function templateArrayValue(value: any): string { return value; diff --git a/templates/templates/go/auxiliary/{{getUtilsLocation}}/json.go.stmpl b/templates/templates/go/auxiliary/{{getUtilsLocation}}/json.go.stmpl index 1522bcb4d..0fe0140cf 100644 --- a/templates/templates/go/auxiliary/{{getUtilsLocation}}/json.go.stmpl +++ b/templates/templates/go/auxiliary/{{getUtilsLocation}}/json.go.stmpl @@ -240,6 +240,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -250,7 +254,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -482,6 +490,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/templates/templates/mockserver/auxiliary/internal/sdk/utils/json.go.stmpl b/templates/templates/mockserver/auxiliary/internal/sdk/utils/json.go.stmpl index ba33a3081..8fec8c27e 100644 --- a/templates/templates/mockserver/auxiliary/internal/sdk/utils/json.go.stmpl +++ b/templates/templates/mockserver/auxiliary/internal/sdk/utils/json.go.stmpl @@ -189,6 +189,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -199,7 +203,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -422,6 +430,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/templates/templates/terraform/features.ts b/templates/templates/terraform/features.ts index de973bba8..9f2005f15 100644 --- a/templates/templates/terraform/features.ts +++ b/templates/templates/terraform/features.ts @@ -26,6 +26,8 @@ const supportedFeatures = { constsAndDefaults: "0.3.2", defaultArrays: "0.2.0", defaultObjects: "0.1.2", + constArrays: "0.1.0", + constObjects: "0.1.0", additionalProperties: "0.1.5", disallowCircularRefs: "0.0.0", oauth2ClientCredentials: "0.3.5", diff --git a/templates/templates/terraform/includes/generateTFToSDK.ts b/templates/templates/terraform/includes/generateTFToSDK.ts index bd8617737..0c3f4ccb4 100644 --- a/templates/templates/terraform/includes/generateTFToSDK.ts +++ b/templates/templates/terraform/includes/generateTFToSDK.ts @@ -1145,6 +1145,9 @@ function generateModelToSDKMethodBody( tfAccessor = `${tfAccessor}[${iterVariable}]`; for (let i = 0; i < targetTypeDef.ItemType.Fields.length; i++) { const field = targetTypeDef.ItemType.Fields[i]; + if (field.Const) { + continue; + } const equivalent = fromTypeDef.ItemType?.Fields.find( (f) => sanitizeFieldName(field.Name) == sanitizeFieldName(f.Name), diff --git a/tests/specs/review-terraform.yaml b/tests/specs/review-terraform.yaml index 4c85fff0c..ed177ece5 100644 --- a/tests/specs/review-terraform.yaml +++ b/tests/specs/review-terraform.yaml @@ -5697,6 +5697,146 @@ paths: responses: '200': description: OK + /v0/constcontainers: + post: + x-speakeasy-entity-operation: ConstContainer#create + description: | + Create a resource whose request schema declares const values on array + and map properties. Terraform must hide those properties from the + resource schema and send the const values in the request body. + operationId: create-const-container + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ConstContainerRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConstContainerResponse' + /v0/constcontainer/{id}: + parameters: + - name: id + in: path + required: true + schema: + type: string + get: + x-speakeasy-entity-operation: ConstContainer#read + description: | + Get a const container resource. The query parameter declares an + array const, which lives on the parameter path rather than a request + body property, to pin how container consts on parameters surface. + operationId: get-const-container + parameters: + - name: scope + in: query + schema: + type: array + items: + type: string + const: + - all + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConstContainerResponse' + '404': + description: Not Found + delete: + x-speakeasy-entity-operation: ConstContainer#delete + description: Delete a const container resource + operationId: delete-const-container + responses: + '200': + description: OK + /v0/constemptysetdelete: + put: + x-speakeasy-entity-operation: ConstEmptySetDelete#create,update + description: | + Create or replace a resource whose desired state is a set of objects. + One operation serves create and update; deletion goes through a + separate operation whose request body declares the same set with an + empty const value. + operationId: create-const-empty-set-delete + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ConstEmptySetDeleteRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConstEmptySetDeleteResponse' + /v0/constemptysetdelete/{id}: + parameters: + - name: id + in: path + required: true + schema: + type: string + get: + x-speakeasy-entity-operation: + terraform-datasource: null + terraform-resource: ConstEmptySetDelete#read + description: Get a const empty set delete resource + operationId: get-const-empty-set-delete + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConstEmptySetDeleteResponse' + '404': + description: Not Found + /v1/constemptysetdelete/teardown: + put: + x-speakeasy-entity-operation: ConstEmptySetDelete#delete + description: | + Delete the resource by replacing its group set with an empty set. The + request body declares the set property with `format: set` and + `const: []`, so Terraform must hide it and send an empty array instead + of the groups held in state. The operation lives under a different + API version prefix from the entity's other operations. + operationId: delete-const-empty-set-delete + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + properties: + scope_id: + type: string + groups: + type: array + format: set + items: + $ref: '#/components/schemas/ConstEmptySetDeleteGroup' + const: [] + required: + - scope_id + - groups + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConstEmptySetDeleteResponse' components: parameters: GlobalBoolean: @@ -5917,6 +6057,239 @@ components: type: string default: DEFAULT schemas: + ConstContainerRequest: + type: object + additionalProperties: false + x-speakeasy-entity: ConstContainer + properties: + name: + type: string + empty_list: + type: array + items: + type: string + const: [] + fixed_list: + type: array + items: + type: string + enum: + - read + - write + - admin + const: + - read + - write + empty_set: + type: array + format: set + items: + type: object + additionalProperties: false + properties: + key: + type: string + const: [] + empty_map: + type: object + additionalProperties: + type: string + const: {} + fixed_map: + type: object + additionalProperties: + type: integer + const: + max: 10 + min: 1 + templated_map: + description: | + Map const whose keys and values contain template delimiters, + quotes, backslashes and a newline. The generated Go literal and + struct tag must escape them and round-trip them on the wire. + type: object + additionalProperties: + type: string + const: + '{{key}}': value + 'quo"te\back': "line\nbreak" + nullable_list: + description: | + Nullable array with an empty const. A response may carry null for + it, which must decode as absent rather than a const mismatch. + type: array + nullable: true + items: + type: string + const: [] + nested_list: + description: | + List of objects whose item schema declares a const array. The + nested const must be hidden from the Terraform schema and sent + for every item. + type: array + items: + type: object + additionalProperties: false + properties: + label: + type: string + tags: + type: array + items: + type: string + const: + - fixed + required: + - name + - empty_list + - empty_map + - empty_set + - nullable_list + ConstContainerResponse: + type: object + additionalProperties: false + x-speakeasy-entity: ConstContainer + properties: + id: + type: string + name: + type: string + empty_list: + type: array + items: + type: string + const: [] + fixed_list: + type: array + items: + type: string + enum: + - read + - write + - admin + const: + - read + - write + empty_set: + type: array + format: set + items: + type: object + additionalProperties: false + properties: + key: + type: string + const: [] + empty_map: + type: object + additionalProperties: + type: string + const: {} + fixed_map: + type: object + additionalProperties: + type: integer + const: + max: 10 + min: 1 + templated_map: + description: | + Map const whose keys and values contain template delimiters, + quotes, backslashes and a newline. The generated Go literal and + struct tag must escape them and round-trip them on the wire. + type: object + additionalProperties: + type: string + const: + '{{key}}': value + 'quo"te\back': "line\nbreak" + nullable_list: + description: | + Nullable array with an empty const. A response may carry null for + it, which must decode as absent rather than a const mismatch. + type: array + nullable: true + items: + type: string + const: [] + nested_list: + description: | + List of objects whose item schema declares a const array. The + nested const must be hidden from the Terraform schema and sent + for every item. + type: array + items: + type: object + additionalProperties: false + properties: + label: + type: string + tags: + type: array + items: + type: string + const: + - fixed + required: + - nullable_list + ConstEmptySetDeleteGroup: + type: object + additionalProperties: false + properties: + provider: + type: string + region: + type: string + replicas: + type: integer + required: + - provider + - region + ConstEmptySetDeleteRequest: + type: object + additionalProperties: false + x-speakeasy-entity: ConstEmptySetDelete + properties: + scope_id: + type: string + groups: + type: array + format: set + items: + $ref: '#/components/schemas/ConstEmptySetDeleteGroup' + required: + - scope_id + - groups + ConstEmptySetDeleteResponse: + type: object + additionalProperties: false + x-speakeasy-entity: ConstEmptySetDelete + properties: + id: + type: string + scope_id: + type: string + groups: + type: array + format: set + items: + $ref: '#/components/schemas/ConstEmptySetDeleteGroup' + supported_actions: + description: | + Response-only const array. It must stay off the request model, + be hidden from the Terraform schema, and be checked when the + response is decoded. + type: array + items: + type: string + readOnly: true + const: + - replace + required: + - id + - scope_id + - groups DiscriminatedUnionCreateRequest: x-speakeasy-entity: DiscriminatedUnion type: object diff --git a/zSDKs/mcp-typescript/.speakeasy/gen.lock b/zSDKs/mcp-typescript/.speakeasy/gen.lock index ecac333ff..dc7fadefc 100644 --- a/zSDKs/mcp-typescript/.speakeasy/gen.lock +++ b/zSDKs/mcp-typescript/.speakeasy/gen.lock @@ -412,7 +412,7 @@ trackedFiles: src/__tests__/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd src/__tests__/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc src/__tests__/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 src/__tests__/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go b/zSDKs/mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-cli/.speakeasy/gen.lock b/zSDKs/sdk-cli/.speakeasy/gen.lock index 1dbab381d..5639fecff 100644 --- a/zSDKs/sdk-cli/.speakeasy/gen.lock +++ b/zSDKs/sdk-cli/.speakeasy/gen.lock @@ -602,7 +602,7 @@ trackedFiles: internal/sdk/sdkinternal/utils/headers.go: last_write_checksum: sha1:1b0bd68e1ea0bce8c5a42b5de9fd020fede7aecc internal/sdk/sdkinternal/utils/json.go: - last_write_checksum: sha1:9534e47eedd4d46cc737c0f42f51df5b2ebdc122 + last_write_checksum: sha1:a6acd0e20b584386fdb111c3889bf3e7d9c42694 internal/sdk/sdkinternal/utils/oauth2_credentials.go: last_write_checksum: sha1:f9218b6b3dbd11494cc353bf22eb37f0ca654a7d internal/sdk/sdkinternal/utils/oauth2_sessions.go: @@ -1076,7 +1076,7 @@ trackedFiles: tests/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd tests/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc tests/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 tests/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-cli/internal/sdk/sdkinternal/utils/json.go b/zSDKs/sdk-cli/internal/sdk/sdkinternal/utils/json.go index ba62c4426..91c817eb0 100644 --- a/zSDKs/sdk-cli/internal/sdk/sdkinternal/utils/json.go +++ b/zSDKs/sdk-cli/internal/sdk/sdkinternal/utils/json.go @@ -241,6 +241,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -251,7 +255,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -481,6 +489,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-cli/tests/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-cli/tests/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-cli/tests/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-cli/tests/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-csharp/.speakeasy/gen.lock b/zSDKs/sdk-csharp/.speakeasy/gen.lock index 89cfef084..909e82740 100644 --- a/zSDKs/sdk-csharp/.speakeasy/gen.lock +++ b/zSDKs/sdk-csharp/.speakeasy/gen.lock @@ -458,7 +458,7 @@ trackedFiles: Tests/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd Tests/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc Tests/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 Tests/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-csharp/Tests/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-csharp/Tests/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-csharp/Tests/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-csharp/Tests/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-go/.speakeasy/gen.lock b/zSDKs/sdk-go/.speakeasy/gen.lock index 3df5d94e4..af492fcbd 100644 --- a/zSDKs/sdk-go/.speakeasy/gen.lock +++ b/zSDKs/sdk-go/.speakeasy/gen.lock @@ -713,7 +713,7 @@ trackedFiles: internal/utils/headers.go: last_write_checksum: sha1:e529ca3d7ab96a091021bcd471ba2cbef50286b3 internal/utils/json.go: - last_write_checksum: sha1:34b0eece0c4a818c500c0355c9039d61510b1b5e + last_write_checksum: sha1:d3506e4f08fcbf738c35bedfe600085d76b1a555 internal/utils/pathparams.go: last_write_checksum: sha1:60292c3cd973e29c9b80905972f1e1e6e5e17bdd internal/utils/queryparams.go: @@ -1233,7 +1233,7 @@ trackedFiles: tests/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd tests/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc tests/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 tests/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-go/internal/utils/json.go b/zSDKs/sdk-go/internal/utils/json.go index c79f0f342..892f89e06 100644 --- a/zSDKs/sdk-go/internal/utils/json.go +++ b/zSDKs/sdk-go/internal/utils/json.go @@ -241,6 +241,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -251,7 +255,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -481,6 +489,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-go/tests/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-go/tests/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-go/tests/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-go/tests/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-javav2/.speakeasy/gen.lock b/zSDKs/sdk-javav2/.speakeasy/gen.lock index 906ca9c0e..3842e548e 100644 --- a/zSDKs/sdk-javav2/.speakeasy/gen.lock +++ b/zSDKs/sdk-javav2/.speakeasy/gen.lock @@ -1983,7 +1983,7 @@ trackedFiles: tests/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd tests/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc tests/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 tests/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-javav2/tests/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-javav2/tests/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-javav2/tests/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-javav2/tests/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-mcp-typescript/.speakeasy/gen.lock b/zSDKs/sdk-mcp-typescript/.speakeasy/gen.lock index 416c39fa8..ef94d2c55 100644 --- a/zSDKs/sdk-mcp-typescript/.speakeasy/gen.lock +++ b/zSDKs/sdk-mcp-typescript/.speakeasy/gen.lock @@ -370,7 +370,7 @@ trackedFiles: src/__tests__/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd src/__tests__/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc src/__tests__/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 src/__tests__/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-mcp-typescript/src/__tests__/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-pythonv2/.speakeasy/gen.lock b/zSDKs/sdk-pythonv2/.speakeasy/gen.lock index 4bdcff49b..883bc63c1 100644 --- a/zSDKs/sdk-pythonv2/.speakeasy/gen.lock +++ b/zSDKs/sdk-pythonv2/.speakeasy/gen.lock @@ -1176,7 +1176,7 @@ trackedFiles: tests/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd tests/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc tests/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 tests/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-pythonv2/tests/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-pythonv2/tests/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-pythonv2/tests/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-pythonv2/tests/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-ruby/.speakeasy/gen.lock b/zSDKs/sdk-ruby/.speakeasy/gen.lock index 437c8de42..28f326c48 100644 --- a/zSDKs/sdk-ruby/.speakeasy/gen.lock +++ b/zSDKs/sdk-ruby/.speakeasy/gen.lock @@ -1835,7 +1835,7 @@ trackedFiles: test/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd test/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc test/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 test/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-ruby/test/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-ruby/test/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-ruby/test/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-ruby/test/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock index 11bc3e6ad..5d6b4abb3 100644 --- a/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock +++ b/zSDKs/sdk-typescriptv2/.speakeasy/gen.lock @@ -867,7 +867,7 @@ trackedFiles: src/__tests__/mockserver/internal/sdk/types/stream/stream.go: last_write_checksum: sha1:c48811a5243fa7f9e23c67966b140c52614b58bd src/__tests__/mockserver/internal/sdk/utils/json.go: - last_write_checksum: sha1:5e20daa1ddf6ebe49c4c0f34fd0051c43e6b7ff9 + last_write_checksum: sha1:22904cb9788737f288acdab97255bc78d37531bc src/__tests__/mockserver/internal/sdk/utils/reflect.go: last_write_checksum: sha1:1e3a0ca0387685b6b21c0a6a75650b8611c76ee3 src/__tests__/mockserver/internal/sdk/utils/sort.go: diff --git a/zSDKs/sdk-typescriptv2/src/__tests__/mockserver/internal/sdk/utils/json.go b/zSDKs/sdk-typescriptv2/src/__tests__/mockserver/internal/sdk/utils/json.go index 6ec0f8449..05f85d049 100644 --- a/zSDKs/sdk-typescriptv2/src/__tests__/mockserver/internal/sdk/utils/json.go +++ b/zSDKs/sdk-typescriptv2/src/__tests__/mockserver/internal/sdk/utils/json.go @@ -191,6 +191,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -201,7 +205,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -424,6 +432,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/terraform-provider-testing/.speakeasy/gen.lock b/zSDKs/terraform-provider-testing/.speakeasy/gen.lock index 1dafd9b5b..966407cb1 100644 --- a/zSDKs/terraform-provider-testing/.speakeasy/gen.lock +++ b/zSDKs/terraform-provider-testing/.speakeasy/gen.lock @@ -1,7 +1,7 @@ lockVersion: 2.0.0 id: review-sdk-test-id management: - docChecksum: fccaa1943b7d99936e3cf386d6aef8ac + docChecksum: 52db7940c5b8f2e1032a13a3f84626ae docVersion: 0.0.1 speakeasyVersion: internal generationVersion: internal @@ -11,6 +11,8 @@ features: terraform: additionalDependencies: 0.1.0 additionalProperties: 0.1.5 + constArrays: 0.1.0 + constObjects: 0.1.0 constsAndDefaults: 0.3.2 contentMediaTypeApplicationJSON: 0.1.1 core: 3.50.7 @@ -51,6 +53,8 @@ trackedFiles: last_write_checksum: sha1:d84cd84fe166ec2d063ebb13a1845e744425693c examples/data-sources/testing_basic/data-source.tf: last_write_checksum: sha1:02bc159abd38449bcddcff2ed9eb7daf0b5cf5b4 + examples/data-sources/testing_const_container/data-source.tf: + last_write_checksum: sha1:c9d73d56cf6105882eaea310da3bba6b1b60c82a examples/data-sources/testing_discriminated_union/data-source.tf: last_write_checksum: sha1:a21b63c90ce67e7b78e103fb57e8b55ba8ab4073 examples/data-sources/testing_framework_type/data-source.tf: @@ -275,6 +279,18 @@ trackedFiles: last_write_checksum: sha1:056e42f5b27cbc4a7e5b4a14c154ad4084026594 examples/resources/testing_basic/resource.tf: last_write_checksum: sha1:60780e18fdeae0f7305502bd819092015c9e36b5 + examples/resources/testing_const_container/import-by-string-id.tf: + last_write_checksum: sha1:094ecf7d894ef2ef5a9a4669ec05ef7c75bdceaa + examples/resources/testing_const_container/import.sh: + last_write_checksum: sha1:dc82e240078029b62b56bb695067d4c5e9cb4264 + examples/resources/testing_const_container/resource.tf: + last_write_checksum: sha1:e99fed339d5e89b5fd901103358d29986496d02a + examples/resources/testing_const_empty_set_delete/import-by-string-id.tf: + last_write_checksum: sha1:5e2fa4d90023d6fd8023b8df472dc294c2610004 + examples/resources/testing_const_empty_set_delete/import.sh: + last_write_checksum: sha1:7f1db4230b8685d1674c91ab6d0834483d1388d7 + examples/resources/testing_const_empty_set_delete/resource.tf: + last_write_checksum: sha1:3f758caa89921c6e250892c31cc357ee5b137c10 examples/resources/testing_discriminated_union/import-by-string-id.tf: last_write_checksum: sha1:61473f31485ac280bfa6943e7580d1bdd1e43413 examples/resources/testing_discriminated_union/import.sh: @@ -763,6 +779,18 @@ trackedFiles: last_write_checksum: sha1:550b1c9370c6f1e389f6145f4ab522df9c855e76 internal/provider/basic_resource_sdk.go: last_write_checksum: sha1:c7327b7ec6b530ccb4ba940c83953e7b58b092a4 + internal/provider/constcontainer_data_source.go: + last_write_checksum: sha1:adf9e08cf64bc77225f07361d4c8201b6d355b1c + internal/provider/constcontainer_data_source_sdk.go: + last_write_checksum: sha1:e025e23a41dc09acbaad5fa4f1f805bd15dd55df + internal/provider/constcontainer_resource.go: + last_write_checksum: sha1:c84b662f5167a29ae64dcde0a01652e661d44357 + internal/provider/constcontainer_resource_sdk.go: + last_write_checksum: sha1:1742253997f1ad0e00600193af22ec233d4c9016 + internal/provider/constemptysetdelete_resource.go: + last_write_checksum: sha1:c3fafc720d57f71f6b2cf165b9e96e347711c078 + internal/provider/constemptysetdelete_resource_sdk.go: + last_write_checksum: sha1:e4011063b10ba78613522aab7b958a801a850764 internal/provider/discriminatedunion_data_source.go: last_write_checksum: sha1:dd97963488cb1994321bf5e3f813917c80a7d7b5 internal/provider/discriminatedunion_data_source_sdk.go: @@ -1066,7 +1094,7 @@ trackedFiles: internal/provider/patch_resource_sdk.go: last_write_checksum: sha1:9b583e2ac47191350373ce5a86408c118bd606b1 internal/provider/provider.go: - last_write_checksum: sha1:a333255d3d9585c5700d3059b03e9b0dbf388774 + last_write_checksum: sha1:61dd2f3795c80f9758d2788d91afc2b1dda4a885 internal/provider/reflect/diags.go: last_write_checksum: sha1:ace8bc53054bb1d8ee8689acf3e4323de75a6297 internal/provider/reflect/doc.go: @@ -1215,6 +1243,12 @@ trackedFiles: last_write_checksum: sha1:a2a20e6785f1e12c3f94c016cbc106e54942e981 internal/provider/typeconvert/int.go: last_write_checksum: sha1:c28123f17006dc96a233f916a17c38408e37b71f + internal/provider/types/const_container_request_nested_list.go: + last_write_checksum: sha1:458f9b9dd282edcdd630ceea677772735874d669 + internal/provider/types/const_container_response_nested_list.go: + last_write_checksum: sha1:7090951d7f68ab5f6994376600b38b2470079383 + internal/provider/types/const_empty_set_delete_group.go: + last_write_checksum: sha1:cd350a23a4944c1d3dcbca450daa9d4b799bfeae internal/provider/types/credential.go: last_write_checksum: sha1:0f481ec7276acf4c15b64e3a7453e4bddc2dfa1c internal/provider/types/credential1.go: @@ -2404,7 +2438,7 @@ trackedFiles: internal/sdk/internal/utils/jq.go: last_write_checksum: sha1:2e75ed7a7db1f91e97dac1ac4ca7801b2beb69b5 internal/sdk/internal/utils/json.go: - last_write_checksum: sha1:3f664e31aa0672c1dacec1e445306ba483debf32 + last_write_checksum: sha1:27c84516c074f27711ead24a292bdc2474c1092d internal/sdk/internal/utils/oauth2_credentials.go: last_write_checksum: sha1:f9218b6b3dbd11494cc353bf22eb37f0ca654a7d internal/sdk/internal/utils/oauth2_sessions.go: @@ -2439,6 +2473,10 @@ trackedFiles: last_write_checksum: sha1:5b080b285280d5f8a012138b77c848c3118bddb0 internal/sdk/models/operations/createbasic.go: last_write_checksum: sha1:0fdbac8d615b203c4f6054f9f44176e1c4ce564a + internal/sdk/models/operations/createconstcontainer.go: + last_write_checksum: sha1:892a2934f9b5cc0d5e40335502d20c3750702b95 + internal/sdk/models/operations/createconstemptysetdelete.go: + last_write_checksum: sha1:a0fae74d349d3ea63d3df50ba944230a3379e0a3 internal/sdk/models/operations/creatediscriminatedunion.go: last_write_checksum: sha1:68d916f8c709a15e2a564066dbc9317502aecf13 internal/sdk/models/operations/creatediscriminatedunionarray.go: @@ -2587,6 +2625,10 @@ trackedFiles: last_write_checksum: sha1:5b31482c4b581bc143b0403060004849179d8ffd internal/sdk/models/operations/deletebasic.go: last_write_checksum: sha1:2d991f9ce3b49547f88d3ed69a9a4e01ccc135a8 + internal/sdk/models/operations/deleteconstcontainer.go: + last_write_checksum: sha1:443d6380ef9a4f9405c655078371ab2c13e633fa + internal/sdk/models/operations/deleteconstemptysetdelete.go: + last_write_checksum: sha1:67e766f608bf87fb1c06b22916fce98ed38d048c internal/sdk/models/operations/deletecustomplanmodifiers.go: last_write_checksum: sha1:8bcb2a4f56d57265de023e41d21617f5b88a7bc6 internal/sdk/models/operations/deletediscriminatedunion.go: @@ -2727,6 +2769,10 @@ trackedFiles: last_write_checksum: sha1:3bcc0082028b5f01a4d13f84072629b010550da0 internal/sdk/models/operations/getbasic.go: last_write_checksum: sha1:73ada8ac1a2cec3987eb5b93f78f815934067b9d + internal/sdk/models/operations/getconstcontainer.go: + last_write_checksum: sha1:558633acfdf5a314fc1fdc4a580949f6ab6a90e0 + internal/sdk/models/operations/getconstemptysetdelete.go: + last_write_checksum: sha1:0fd0c404cc7659c8ee1f1453adf5be9a55443f03 internal/sdk/models/operations/getcustomplanmodifiers.go: last_write_checksum: sha1:c6f5938cb6330969450186336a3085558bcd6d1c internal/sdk/models/operations/getdiscriminatedunion.go: @@ -3073,6 +3119,16 @@ trackedFiles: last_write_checksum: sha1:34cb7c7fc9ab32b03e7c6a0875e7e6fec5805577 internal/sdk/models/shared/basicsearch.go: last_write_checksum: sha1:ebc8943a31148f7623c5f8ff940dd81c1b52f23d + internal/sdk/models/shared/constcontainerrequest.go: + last_write_checksum: sha1:1cf8e117d1b1a8ce9fe2a7e36bcb59eb6052a12e + internal/sdk/models/shared/constcontainerresponse.go: + last_write_checksum: sha1:ab518fe68f26a5fc1ee473a2fc1d47ffa571efd3 + internal/sdk/models/shared/constemptysetdeletegroup.go: + last_write_checksum: sha1:d33860be5d32e993a1907c5f4a9b85f849357a8e + internal/sdk/models/shared/constemptysetdeleterequest.go: + last_write_checksum: sha1:1823ce955c667bf3702f098e162b9fa0bac9d8a4 + internal/sdk/models/shared/constemptysetdeleteresponse.go: + last_write_checksum: sha1:49ba49af13fb530bb278d8559e23e0b191c8b1ed internal/sdk/models/shared/discriminatedobject.go: last_write_checksum: sha1:9bb5641a1bcb27ec59c1f16d82d8a251ec733286 internal/sdk/models/shared/discriminatedunionarraycreaterequest.go: @@ -3578,7 +3634,7 @@ trackedFiles: internal/sdk/retry/config.go: last_write_checksum: sha1:102d1953fbd7e9f312c4442c71ccca2eaaeaa27d internal/sdk/sdk.go: - last_write_checksum: sha1:a2997f8af41cead3493768284c9cc8c950f8f57c + last_write_checksum: sha1:cb8f4e761171f2f355a69d1cb043075c79f9fa20 internal/sdk/types/bigint.go: last_write_checksum: sha1:49b004005d0461fb04b846eca062b070b0360b31 internal/sdk/types/date.go: @@ -6020,4 +6076,46 @@ examples: responses: "200": application/json: {} + create-const-container: + speakeasy-default-create-const-container: + requestBody: + application/json: {"name": "", "empty_list": [], "fixed_list": ["read", "write"], "empty_set": [], "empty_map": {}, "fixed_map": {"max": 10, "min": 1}, "templated_map": {"quo\"te\\back": "line\nbreak", "{{key}}": "value"}, "nullable_list": []} + responses: + "200": + application/json: {"empty_list": [], "fixed_list": ["read", "write"], "empty_set": [], "empty_map": {}, "fixed_map": {"max": 10, "min": 1}, "templated_map": {"quo\"te\\back": "line\nbreak", "{{key}}": "value"}, "nullable_list": []} + get-const-container: + speakeasy-default-get-const-container: + parameters: + path: + id: "" + responses: + "200": + application/json: {"empty_list": [], "fixed_list": ["read", "write"], "empty_set": [], "empty_map": {}, "fixed_map": {"max": 10, "min": 1}, "templated_map": {"quo\"te\\back": "line\nbreak", "{{key}}": "value"}, "nullable_list": []} + delete-const-container: + speakeasy-default-delete-const-container: + parameters: + path: + id: "" + create-const-empty-set-delete: + speakeasy-default-create-const-empty-set-delete: + requestBody: + application/json: {"scope_id": "", "groups": []} + responses: + "200": + application/json: {"id": "", "scope_id": "", "groups": [{"provider": "", "region": ""}], "supported_actions": ["replace"]} + get-const-empty-set-delete: + speakeasy-default-get-const-empty-set-delete: + parameters: + path: + id: "" + responses: + "200": + application/json: {"id": "", "scope_id": "", "groups": [], "supported_actions": ["replace"]} + delete-const-empty-set-delete: + speakeasy-default-delete-const-empty-set-delete: + requestBody: + application/json: {"scope_id": "", "groups": []} + responses: + "200": + application/json: {"id": "", "scope_id": "", "groups": [], "supported_actions": ["replace"]} examplesVersion: 1.0.2 diff --git a/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log b/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log index 9f3e6a51d..b97827cb7 100644 --- a/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log +++ b/zSDKs/terraform-provider-testing/.speakeasy/logs/naming.log @@ -175,6 +175,9 @@ DEBUG prepend_op_id: Renamed to "list_x_client_filter_ResponseBody" DEBUG prepend_op_id: Renamed to "list_x_client_filter_array_ResponseBody" labels: "original_name:ResponseBody operation:list_x_client_filter_array requestResponse:response" registrationID: "scope:operations operation:list-x-client-filter-array requestResponse:response responseStatusCode:200 responseMediaType:application/json originalName:ResponseBody" +DEBUG prepend_op_id: Renamed to "delete_const_empty_set_delete_request" + labels: "original_name:request operation:delete_const_empty_set_delete" + registrationID: "scope:operations operation:delete-const-empty-set-delete requestResponse:request originalName:RequestBody" DEBUG --- Renaming 2 types with name "Transformed" --- @@ -2238,6 +2241,33 @@ DEBUG discriminated: Renamed to "XUnknownValuesResponse_closed_enum_string" registrationID: "scope:shared refType:Schemas refName:XUnknownValuesResponse originalName:closed_enum_string" DEBUG +--- Renaming 2 types with name "fixed_list" --- +DEBUG discriminated: Renamed to "ConstContainerRequest_fixed_list" + labels: "original_name:fixed_list scope:shared data_type:enum refName:ConstContainerRequest" + registrationID: "scope:shared refType:Schemas refName:ConstContainerRequest originalName:fixed_list" +DEBUG discriminated: Renamed to "ConstContainerResponse_fixed_list" + labels: "original_name:fixed_list scope:shared data_type:enum refName:ConstContainerResponse" + registrationID: "scope:shared refType:Schemas refName:ConstContainerResponse originalName:fixed_list" +DEBUG + +--- Renaming 2 types with name "empty_set" --- +DEBUG discriminated: Renamed to "ConstContainerRequest_empty_set" + labels: "original_name:empty_set scope:shared refName:ConstContainerRequest" + registrationID: "scope:shared refType:Schemas refName:ConstContainerRequest originalName:empty_set" +DEBUG discriminated: Renamed to "ConstContainerResponse_empty_set" + labels: "original_name:empty_set scope:shared refName:ConstContainerResponse" + registrationID: "scope:shared refType:Schemas refName:ConstContainerResponse originalName:empty_set" +DEBUG + +--- Renaming 2 types with name "nested_list" --- +DEBUG discriminated: Renamed to "ConstContainerRequest_nested_list" + labels: "original_name:nested_list scope:shared refName:ConstContainerRequest" + registrationID: "scope:shared refType:Schemas refName:ConstContainerRequest originalName:nested_list" +DEBUG discriminated: Renamed to "ConstContainerResponse_nested_list" + labels: "original_name:nested_list scope:shared refName:ConstContainerResponse" + registrationID: "scope:shared refType:Schemas refName:ConstContainerResponse originalName:nested_list" +DEBUG + --- Renaming 3 types with name "tier" --- DEBUG discriminated: Renamed to "create_import_defaulted_id_tier" labels: "original_name:tier operation:create_import_defaulted_id data_type:enum parameter:pathParam" @@ -2386,6 +2416,9 @@ DEBUG prepend_op_id: N/A rename "list_x_client_filter_ResponseBody" DEBUG prepend_op_id: N/A rename "list_x_client_filter_array_ResponseBody" labels: "original_name:ResponseBody operation:list_x_client_filter_array requestResponse:response" registrationID: "scope:operations operation:list-x-client-filter-array requestResponse:response responseStatusCode:200 responseMediaType:application/json originalName:ResponseBody" +DEBUG prepend_op_id: N/A rename "delete_const_empty_set_delete_request" + labels: "original_name:request operation:delete_const_empty_set_delete" + registrationID: "scope:operations operation:delete-const-empty-set-delete requestResponse:request originalName:RequestBody" DEBUG Sdk (SDK empty) @@ -3813,6 +3846,27 @@ UpdateOasContentMediaTypeRequest (id: string, OASContentMediaTypeRequest: OASCon UpdateOasContentMediaTypeResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) DeleteOasContentMediaTypeRequest (id: string) DeleteOasContentMediaTypeResponse (ContentType: string, StatusCode: int32, RawResponse: response) +ConstContainerRequest (name: string, empty_list: array, fixed_list: array ...) + ConstContainerRequestFixedList (enum: read, write, admin) + ConstContainerRequestEmptySet (key: string) + ConstContainerRequestNestedList (label: string, tags: array) +CreateConstContainerResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) + ConstContainerResponse (id: string, name: string, empty_list: array ...) + ConstContainerResponseFixedList (enum: read, write, admin) + ConstContainerResponseEmptySet (key: string) + ConstContainerResponseNestedList (label: string, tags: array) +GetConstContainerRequest (id: string, scope: array) +GetConstContainerResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) +DeleteConstContainerRequest (id: string) +DeleteConstContainerResponse (ContentType: string, StatusCode: int32, RawResponse: response) +ConstEmptySetDeleteRequest (scope_id: string, groups: set) + ConstEmptySetDeleteGroup (provider: string, region: string, replicas: integer) +CreateConstEmptySetDeleteResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) + ConstEmptySetDeleteResponse (id: string, scope_id: string, groups: set ...) +GetConstEmptySetDeleteRequest (id: string) +GetConstEmptySetDeleteResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) +DeleteConstEmptySetDeleteRequest (scope_id: string, groups: set) +DeleteConstEmptySetDeleteResponse (ContentType: string, StatusCode: int32, RawResponse: response ...) Globals (globalBoolean: boolean, globalBooleanWithDefault: boolean, globalEnumFloat32: float32 ...) UpdateXGlobalsGlobals (globalBoolean: boolean, globalBooleanWithDefault: boolean, globalEnumFloat32: float32 ...) diff --git a/zSDKs/terraform-provider-testing/README.md b/zSDKs/terraform-provider-testing/README.md index f26d58fe8..2250ea672 100644 --- a/zSDKs/terraform-provider-testing/README.md +++ b/zSDKs/terraform-provider-testing/README.md @@ -102,6 +102,8 @@ Available configuration: * [testing_api_create_and_update](docs/resources/api_create_and_update.md) * [testing_basic](docs/resources/basic.md) +* [testing_const_container](docs/resources/const_container.md) +* [testing_const_empty_set_delete](docs/resources/const_empty_set_delete.md) * [testing_discriminated_union](docs/resources/discriminated_union.md) * [testing_discriminated_union_array](docs/resources/discriminated_union_array.md) * [testing_framework_type](docs/resources/framework_type.md) @@ -179,6 +181,7 @@ Available configuration: * [testing_api_create_and_update](docs/data-sources/api_create_and_update.md) * [testing_basic](docs/data-sources/basic.md) +* [testing_const_container](docs/data-sources/const_container.md) * [testing_discriminated_union](docs/data-sources/discriminated_union.md) * [testing_framework_type](docs/data-sources/framework_type.md) * [testing_import_defaulted_id](docs/data-sources/import_defaulted_id.md) diff --git a/zSDKs/terraform-provider-testing/docs/data-sources/const_container.md b/zSDKs/terraform-provider-testing/docs/data-sources/const_container.md new file mode 100644 index 000000000..4217c912b --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/data-sources/const_container.md @@ -0,0 +1,44 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "testing_const_container Data Source - terraform-provider-testing" +subcategory: "" +description: |- + ConstContainer DataSource +--- + +# testing_const_container (Data Source) + +ConstContainer DataSource + +## Example Usage + +```terraform +data "testing_const_container" "my_constcontainer" { + id = "...my_id..." + scope = [ + "..." + ] +} +``` + + +## Schema + +### Optional + +- `scope` (List of String) + +### Read-Only + +- `id` (String) The ID of this resource. +- `name` (String) +- `nested_list` (Attributes List) List of objects whose item schema declares a const array. The +nested const must be hidden from the Terraform schema and sent +for every item. (see [below for nested schema](#nestedatt--nested_list)) + + +### Nested Schema for `nested_list` + +Read-Only: + +- `label` (String) diff --git a/zSDKs/terraform-provider-testing/docs/resources/const_container.md b/zSDKs/terraform-provider-testing/docs/resources/const_container.md new file mode 100644 index 000000000..0366f4308 --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/resources/const_container.md @@ -0,0 +1,68 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "testing_const_container Resource - terraform-provider-testing" +subcategory: "" +description: |- + ConstContainer Resource +--- + +# testing_const_container (Resource) + +ConstContainer Resource + +## Example Usage + +```terraform +resource "testing_const_container" "my_constcontainer" { + name = "...my_name..." + nested_list = [ + { + label = "...my_label..." + } + ] +} +``` + + +## Schema + +### Required + +- `name` (String) Requires replacement if changed. + +### Optional + +- `nested_list` (Attributes List) List of objects whose item schema declares a const array. The +nested const must be hidden from the Terraform schema and sent +for every item. +Requires replacement if changed. (see [below for nested schema](#nestedatt--nested_list)) + +### Read-Only + +- `id` (String) The ID of this resource. + + +### Nested Schema for `nested_list` + +Optional: + +- `label` (String) Requires replacement if changed. + +## Import + +Import is supported using the following syntax: + +In Terraform v1.5.0 and later, the [`import` block](https://developer.hashicorp.com/terraform/language/import) can be used with the `id` attribute, for example: + +```terraform +import { + to = testing_const_container.my_testing_const_container + id = "..." +} +``` + +The [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import) can be used, for example: + +```shell +terraform import testing_const_container.my_testing_const_container "..." +``` diff --git a/zSDKs/terraform-provider-testing/docs/resources/const_empty_set_delete.md b/zSDKs/terraform-provider-testing/docs/resources/const_empty_set_delete.md new file mode 100644 index 000000000..64387f3e2 --- /dev/null +++ b/zSDKs/terraform-provider-testing/docs/resources/const_empty_set_delete.md @@ -0,0 +1,66 @@ +--- +# generated by https://github.com/hashicorp/terraform-plugin-docs +page_title: "testing_const_empty_set_delete Resource - terraform-provider-testing" +subcategory: "" +description: |- + ConstEmptySetDelete Resource +--- + +# testing_const_empty_set_delete (Resource) + +ConstEmptySetDelete Resource + +## Example Usage + +```terraform +resource "testing_const_empty_set_delete" "my_constemptysetdelete" { + groups = [ + { + provider = "...my_provider..." + region = "...my_region..." + replicas = 10 + } + ] + scope_id = "...my_scope_id..." +} +``` + + +## Schema + +### Required + +- `groups` (Attributes Set) (see [below for nested schema](#nestedatt--groups)) +- `scope_id` (String) + +### Read-Only + +- `id` (String) The ID of this resource. + + +### Nested Schema for `groups` + +Optional: + +- `provider` (String) Not Null +- `region` (String) Not Null +- `replicas` (Number) + +## Import + +Import is supported using the following syntax: + +In Terraform v1.5.0 and later, the [`import` block](https://developer.hashicorp.com/terraform/language/import) can be used with the `id` attribute, for example: + +```terraform +import { + to = testing_const_empty_set_delete.my_testing_const_empty_set_delete + id = "..." +} +``` + +The [`terraform import` command](https://developer.hashicorp.com/terraform/cli/commands/import) can be used, for example: + +```shell +terraform import testing_const_empty_set_delete.my_testing_const_empty_set_delete "..." +``` diff --git a/zSDKs/terraform-provider-testing/examples/data-sources/testing_const_container/data-source.tf b/zSDKs/terraform-provider-testing/examples/data-sources/testing_const_container/data-source.tf new file mode 100644 index 000000000..ce2f98db4 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/data-sources/testing_const_container/data-source.tf @@ -0,0 +1,6 @@ +data "testing_const_container" "my_constcontainer" { + id = "...my_id..." + scope = [ + "..." + ] +} \ No newline at end of file diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/import-by-string-id.tf b/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/import-by-string-id.tf new file mode 100644 index 000000000..51488fd18 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/import-by-string-id.tf @@ -0,0 +1,4 @@ +import { + to = testing_const_container.my_testing_const_container + id = "..." +} diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/import.sh b/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/import.sh new file mode 100644 index 000000000..1b394b9c7 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/import.sh @@ -0,0 +1 @@ +terraform import testing_const_container.my_testing_const_container "..." diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/resource.tf b/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/resource.tf new file mode 100644 index 000000000..0b58be5a7 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_const_container/resource.tf @@ -0,0 +1,8 @@ +resource "testing_const_container" "my_constcontainer" { + name = "...my_name..." + nested_list = [ + { + label = "...my_label..." + } + ] +} \ No newline at end of file diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/import-by-string-id.tf b/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/import-by-string-id.tf new file mode 100644 index 000000000..6d1e48dc5 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/import-by-string-id.tf @@ -0,0 +1,4 @@ +import { + to = testing_const_empty_set_delete.my_testing_const_empty_set_delete + id = "..." +} diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/import.sh b/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/import.sh new file mode 100644 index 000000000..3445ab4e8 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/import.sh @@ -0,0 +1 @@ +terraform import testing_const_empty_set_delete.my_testing_const_empty_set_delete "..." diff --git a/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/resource.tf b/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/resource.tf new file mode 100644 index 000000000..584e6f099 --- /dev/null +++ b/zSDKs/terraform-provider-testing/examples/resources/testing_const_empty_set_delete/resource.tf @@ -0,0 +1,10 @@ +resource "testing_const_empty_set_delete" "my_constemptysetdelete" { + groups = [ + { + provider = "...my_provider..." + region = "...my_region..." + replicas = 10 + } + ] + scope_id = "...my_scope_id..." +} \ No newline at end of file diff --git a/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source.go b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source.go new file mode 100644 index 000000000..b1b43e845 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source.go @@ -0,0 +1,148 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "fmt" + "github.com/hashicorp/terraform-plugin-framework/datasource" + "github.com/hashicorp/terraform-plugin-framework/datasource/schema" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + tfTypes "github.com/hashicorp/terraform-provider-testing/internal/provider/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ datasource.DataSource = &ConstContainerDataSource{} +var _ datasource.DataSourceWithConfigure = &ConstContainerDataSource{} + +func NewConstContainerDataSource() datasource.DataSource { + return &ConstContainerDataSource{} +} + +// ConstContainerDataSource is the data source implementation. +type ConstContainerDataSource struct { + // Provider configured SDK client. + client *sdk.SDK +} + +// ConstContainerDataSourceModel describes the data model. +type ConstContainerDataSourceModel struct { + ID types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + NestedList []tfTypes.ConstContainerResponseNestedList `tfsdk:"nested_list"` + Scope []types.String `queryParam:"style=form,explode=true,name=scope" tfsdk:"scope"` +} + +// Metadata returns the data source type name. +func (r *ConstContainerDataSource) Metadata(ctx context.Context, req datasource.MetadataRequest, resp *datasource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_const_container" +} + +// Schema defines the schema for the data source. +func (r *ConstContainerDataSource) Schema(ctx context.Context, req datasource.SchemaRequest, resp *datasource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "ConstContainer DataSource", + + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Required: true, + }, + "name": schema.StringAttribute{ + Computed: true, + }, + "nested_list": schema.ListNestedAttribute{ + Computed: true, + NestedObject: schema.NestedAttributeObject{ + Attributes: map[string]schema.Attribute{ + "label": schema.StringAttribute{ + Computed: true, + }, + }, + }, + MarkdownDescription: `List of objects whose item schema declares a const array. The` + "\n" + + `nested const must be hidden from the Terraform schema and sent` + "\n" + + `for every item.`, + }, + "scope": schema.ListAttribute{ + Optional: true, + ElementType: types.StringType, + }, + }, + } +} + +func (r *ConstContainerDataSource) Configure(ctx context.Context, req datasource.ConfigureRequest, resp *datasource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + providerData, ok := req.ProviderData.(*TestingProviderConfigureData) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected DataSource Configure Type", + fmt.Sprintf("Expected *TestingProviderConfigureData, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.client = providerData.SDKClient +} + +func (r *ConstContainerDataSource) Read(ctx context.Context, req datasource.ReadRequest, resp *datasource.ReadResponse) { + var data *ConstContainerDataSourceModel + var item types.Object + + resp.Diagnostics.Append(req.Config.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsGetConstContainerRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.GetConstContainer(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ConstContainerResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstContainerResponse(ctx, res.ConstContainerResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source_sdk.go b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source_sdk.go new file mode 100644 index 000000000..29303bce9 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source_sdk.go @@ -0,0 +1,50 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/types" + tfTypes "github.com/hashicorp/terraform-provider-testing/internal/provider/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/operations" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" +) + +func (r *ConstContainerDataSourceModel) RefreshFromSharedConstContainerResponse(ctx context.Context, resp *shared.ConstContainerResponse) diag.Diagnostics { + var diags diag.Diagnostics + + if resp != nil { + r.ID = types.StringPointerValue(resp.ID) + r.Name = types.StringPointerValue(resp.Name) + r.NestedList = []tfTypes.ConstContainerResponseNestedList{} + + for _, nestedListItem := range resp.NestedList { + var nestedList tfTypes.ConstContainerResponseNestedList + + nestedList.Label = types.StringPointerValue(nestedListItem.Label) + + r.NestedList = append(r.NestedList, nestedList) + } + } + + return diags +} + +func (r *ConstContainerDataSourceModel) ToOperationsGetConstContainerRequest(ctx context.Context) (*operations.GetConstContainerRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var id string + id = r.ID.ValueString() + + scope := make([]string, 0, len(r.Scope)) + for scopeIndex := range r.Scope { + scope = append(scope, r.Scope[scopeIndex].ValueString()) + } + out := operations.GetConstContainerRequest{ + ID: id, + Scope: scope, + } + + return &out, diags +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source_test.go b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source_test.go new file mode 100644 index 000000000..2e283dd28 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_data_source_test.go @@ -0,0 +1,64 @@ +package provider_test + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-testing/compare" + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/hashicorp/terraform-provider-testing/internal/provider" + "github.com/hashicorp/terraform-provider-testing/internal/tfmockserver" +) + +// The data source schema hides the const properties and reads a response +// that carries them. +func TestConstContainerDataSource(t *testing.T) { + t.Parallel() + + endpoints := tfmockserver.ResourceEndpoints{ + Create: tfmockserver.Endpoints{ + { + Endpoint: "POST /v0/constcontainers", + }, + }, + Get: tfmockserver.Endpoints{ + { + Endpoint: "GET /v0/constcontainer/{id}", + }, + }, + Delete: tfmockserver.Endpoints{ + { + Endpoint: "DELETE /v0/constcontainer/{id}", + }, + }, + } + + mockServer := tfmockserver.StartServer(endpoints, t) + defer mockServer.Close() + + dataResourceAddress := "data.testing_const_container.test" + managedResourceAddress := "testing_const_container.test" + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + }, + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.CompareValuePairs( + managedResourceAddress, + tfjsonpath.New("name"), + dataResourceAddress, + tfjsonpath.New("name"), + compare.ValuesSame(), + ), + }, + }, + }, + }) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource.go b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource.go new file mode 100644 index 000000000..5fc187efe --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource.go @@ -0,0 +1,345 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "fmt" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/objectplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier" + "github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + speakeasy_listplanmodifier "github.com/hashicorp/terraform-provider-testing/internal/planmodifiers/listplanmodifier" + speakeasy_objectplanmodifier "github.com/hashicorp/terraform-provider-testing/internal/planmodifiers/objectplanmodifier" + speakeasy_stringplanmodifier "github.com/hashicorp/terraform-provider-testing/internal/planmodifiers/stringplanmodifier" + tfTypes "github.com/hashicorp/terraform-provider-testing/internal/provider/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk" + speakeasy_objectvalidators "github.com/hashicorp/terraform-provider-testing/internal/validators/objectvalidators" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ resource.Resource = &ConstContainerResource{} +var _ resource.ResourceWithImportState = &ConstContainerResource{} + +func NewConstContainerResource() resource.Resource { + return &ConstContainerResource{} +} + +// ConstContainerResource defines the resource implementation. +type ConstContainerResource struct { + // Provider configured SDK client. + client *sdk.SDK +} + +// ConstContainerResourceModel describes the resource data model. +type ConstContainerResourceModel struct { + ID types.String `tfsdk:"id"` + Name types.String `tfsdk:"name"` + NestedList []tfTypes.ConstContainerRequestNestedList `tfsdk:"nested_list"` +} + +func (r *ConstContainerResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_const_container" +} + +func (r *ConstContainerResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "ConstContainer Resource", + Attributes: map[string]schema.Attribute{ + "id": schema.StringAttribute{ + Computed: true, + }, + "name": schema.StringAttribute{ + Required: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplaceIfConfigured(), + speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), + }, + Description: `Requires replacement if changed.`, + }, + "nested_list": schema.ListNestedAttribute{ + Computed: true, + Optional: true, + PlanModifiers: []planmodifier.List{ + listplanmodifier.RequiresReplaceIfConfigured(), + speakeasy_listplanmodifier.SuppressDiff(speakeasy_listplanmodifier.ExplicitSuppress), + }, + NestedObject: schema.NestedAttributeObject{ + Validators: []validator.Object{ + speakeasy_objectvalidators.NotNull(), + }, + PlanModifiers: []planmodifier.Object{ + objectplanmodifier.RequiresReplaceIfConfigured(), + speakeasy_objectplanmodifier.SuppressDiff(speakeasy_objectplanmodifier.ExplicitSuppress), + }, + Attributes: map[string]schema.Attribute{ + "label": schema.StringAttribute{ + Computed: true, + Optional: true, + PlanModifiers: []planmodifier.String{ + stringplanmodifier.RequiresReplaceIfConfigured(), + speakeasy_stringplanmodifier.SuppressDiff(speakeasy_stringplanmodifier.ExplicitSuppress), + }, + Description: `Requires replacement if changed.`, + }, + }, + }, + MarkdownDescription: `List of objects whose item schema declares a const array. The` + "\n" + + `nested const must be hidden from the Terraform schema and sent` + "\n" + + `for every item.` + "\n" + + `Requires replacement if changed.`, + }, + }, + } +} + +func (r *ConstContainerResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + providerData, ok := req.ProviderData.(*TestingProviderConfigureData) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *TestingProviderConfigureData, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.client = providerData.SDKClient +} + +func (r *ConstContainerResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data *ConstContainerResourceModel + var plan types.Object + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToSharedConstContainerRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.CreateConstContainer(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ConstContainerResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstContainerResponse(ctx, res.ConstContainerResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(refreshPlan(ctx, plan, &data)...) + + if resp.Diagnostics.HasError() { + return + } + request1, request1Diags := data.ToOperationsGetConstContainerRequest(ctx) + resp.Diagnostics.Append(request1Diags...) + + if resp.Diagnostics.HasError() { + return + } + res1, err := r.client.GetConstContainer(ctx, *request1) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res1 != nil && res1.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res1.RawResponse)) + } + return + } + if res1 == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res1)) + return + } + if res1.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res1.StatusCode), debugResponse(res1.RawResponse)) + return + } + if !(res1.ConstContainerResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res1.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstContainerResponse(ctx, res1.ConstContainerResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(refreshPlan(ctx, plan, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ConstContainerResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data *ConstContainerResourceModel + var item types.Object + + resp.Diagnostics.Append(req.State.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsGetConstContainerRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.GetConstContainer(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode == 404 { + resp.State.RemoveResource(ctx) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ConstContainerResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstContainerResponse(ctx, res.ConstContainerResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ConstContainerResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data *ConstContainerResourceModel + var plan types.Object + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + merge(ctx, req, resp, &data) + if resp.Diagnostics.HasError() { + return + } + + // Not Implemented; all attributes marked as RequiresReplace + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ConstContainerResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data *ConstContainerResourceModel + var item types.Object + + resp.Diagnostics.Append(req.State.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsDeleteConstContainerRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.DeleteConstContainer(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + switch res.StatusCode { + case 200, 404: + break + default: + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + +} + +func (r *ConstContainerResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource_sdk.go b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource_sdk.go new file mode 100644 index 000000000..a9a774ec0 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource_sdk.go @@ -0,0 +1,84 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/types" + tfTypes "github.com/hashicorp/terraform-provider-testing/internal/provider/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/operations" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" +) + +func (r *ConstContainerResourceModel) RefreshFromSharedConstContainerResponse(ctx context.Context, resp *shared.ConstContainerResponse) diag.Diagnostics { + var diags diag.Diagnostics + + if resp != nil { + r.ID = types.StringPointerValue(resp.ID) + r.Name = types.StringPointerValue(resp.Name) + r.NestedList = []tfTypes.ConstContainerRequestNestedList{} + + for _, nestedListItem := range resp.NestedList { + var nestedList tfTypes.ConstContainerRequestNestedList + + nestedList.Label = types.StringPointerValue(nestedListItem.Label) + + r.NestedList = append(r.NestedList, nestedList) + } + } + + return diags +} + +func (r *ConstContainerResourceModel) ToOperationsDeleteConstContainerRequest(ctx context.Context) (*operations.DeleteConstContainerRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var id string + id = r.ID.ValueString() + + out := operations.DeleteConstContainerRequest{ + ID: id, + } + + return &out, diags +} + +func (r *ConstContainerResourceModel) ToOperationsGetConstContainerRequest(ctx context.Context) (*operations.GetConstContainerRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var id string + id = r.ID.ValueString() + + out := operations.GetConstContainerRequest{ + ID: id, + } + + return &out, diags +} + +func (r *ConstContainerResourceModel) ToSharedConstContainerRequest(ctx context.Context) (*shared.ConstContainerRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var name string + name = r.Name.ValueString() + + nestedList := make([]shared.ConstContainerRequestNestedList, 0, len(r.NestedList)) + for nestedListIndex := range r.NestedList { + label := new(string) + if !r.NestedList[nestedListIndex].Label.IsUnknown() && !r.NestedList[nestedListIndex].Label.IsNull() { + *label = r.NestedList[nestedListIndex].Label.ValueString() + } else { + label = nil + } + nestedList = append(nestedList, shared.ConstContainerRequestNestedList{ + Label: label, + }) + } + out := shared.ConstContainerRequest{ + Name: name, + NestedList: nestedList, + } + + return &out, diags +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource_test.go b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource_test.go new file mode 100644 index 000000000..4e4367e18 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constcontainer_resource_test.go @@ -0,0 +1,126 @@ +package provider_test + +import ( + "net/http" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/hashicorp/terraform-provider-testing/internal/provider" + "github.com/hashicorp/terraform-provider-testing/internal/tfmockserver" + "github.com/stretchr/testify/require" +) + +// The request schema declares const values on array and map properties. The +// provider must hide them from the resource schema and send them verbatim, +// and a read must accept the const values however the server formats them, +// including null for a nullable one. The read operation's const array query +// parameter is not injected: container consts apply to body properties only. +func TestConstContainerResourceLifecycle(t *testing.T) { + t.Parallel() + + endpoints := tfmockserver.ResourceEndpoints{ + Create: tfmockserver.Endpoints{ + { + Endpoint: "POST /v0/constcontainers", + }, + }, + Get: tfmockserver.Endpoints{ + { + Endpoint: "GET /v0/constcontainer/{id}", + // Return the const values with whitespace, map key order and + // number formatting the client did not send, and null for an + // optional const container. + ResponseFuncWithStore: func(r *http.Request, w http.ResponseWriter, storedData map[string]any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + _, _ = w.Write([]byte(`{ + "id": "` + tfmockserver.StoreKey + `", + "name": "` + storedData["name"].(string) + `", + "empty_list": [ ], + "fixed_list": null, + "empty_map": { }, + "empty_set": [ ], + "fixed_map": { "min" : 1, "max" : 1e1 }, + "templated_map": { "{{key}}": "value", "quo\"te\\back": "line\nbreak" }, + "nullable_list": null, + "nested_list": [ { "tags": [ "fixed" ], "label": "first" } ] + }`)) + }, + }, + }, + Delete: tfmockserver.Endpoints{ + { + Endpoint: "DELETE /v0/constcontainer/{id}", + }, + }, + } + + mockServer := tfmockserver.StartServer(endpoints, t) + defer mockServer.Close() + + resourceAddress := "testing_const_container.test" + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + }, + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("id"), + knownvalue.StringExact(tfmockserver.StoreKey), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("name"), + knownvalue.StringExact("test-const-container"), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("nested_list").AtSliceIndex(0).AtMapKey("label"), + knownvalue.StringExact("first"), + ), + }, + }, + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + }, + ResourceName: resourceAddress, + ImportState: true, + ImportStateId: tfmockserver.StoreKey, + ImportStateVerify: true, + }, + }, + }) + + creates := endpoints.Create[0].Requests.Bodies() + require.Len(t, creates, 1) + body := creates[0] + tfmockserver.AssertRequestBodyField(t, body, "name", "test-const-container") + tfmockserver.AssertRequestBodyFieldEmptyArray(t, body, "empty_list") + tfmockserver.AssertRequestBodyFieldArray(t, body, "fixed_list", []any{"read", "write"}) + tfmockserver.AssertRequestBodyField(t, body, "empty_map", map[string]any{}) + tfmockserver.AssertRequestBodyFieldEmptyArray(t, body, "empty_set") + tfmockserver.AssertRequestBodyField(t, body, "fixed_map", map[string]any{"max": float64(10), "min": float64(1)}) + tfmockserver.AssertRequestBodyField(t, body, "templated_map", map[string]any{"{{key}}": "value", "quo\"te\\back": "line\nbreak"}) + tfmockserver.AssertRequestBodyFieldEmptyArray(t, body, "nullable_list") + tfmockserver.AssertRequestBodyField(t, body, "nested_list", []any{map[string]any{"label": "first", "tags": []any{"fixed"}}}) + require.Len(t, body, 9, "request body carries only name, nested_list and the seven const fields: %v", body) + + gets := endpoints.Get[0].Requests.All() + require.NotEmpty(t, gets) + for _, get := range gets { + require.Empty(t, get.Query, "read sends no query parameters: %v", get.Query) + } +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource.go b/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource.go new file mode 100644 index 000000000..fcc501ec0 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource.go @@ -0,0 +1,331 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "fmt" + "github.com/hashicorp/terraform-plugin-framework/path" + "github.com/hashicorp/terraform-plugin-framework/resource" + "github.com/hashicorp/terraform-plugin-framework/resource/schema" + "github.com/hashicorp/terraform-plugin-framework/schema/validator" + "github.com/hashicorp/terraform-plugin-framework/types" + "github.com/hashicorp/terraform-plugin-framework/types/basetypes" + tfTypes "github.com/hashicorp/terraform-provider-testing/internal/provider/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk" + speakeasy_objectvalidators "github.com/hashicorp/terraform-provider-testing/internal/validators/objectvalidators" + speakeasy_stringvalidators "github.com/hashicorp/terraform-provider-testing/internal/validators/stringvalidators" +) + +// Ensure provider defined types fully satisfy framework interfaces. +var _ resource.Resource = &ConstEmptySetDeleteResource{} +var _ resource.ResourceWithImportState = &ConstEmptySetDeleteResource{} + +func NewConstEmptySetDeleteResource() resource.Resource { + return &ConstEmptySetDeleteResource{} +} + +// ConstEmptySetDeleteResource defines the resource implementation. +type ConstEmptySetDeleteResource struct { + // Provider configured SDK client. + client *sdk.SDK +} + +// ConstEmptySetDeleteResourceModel describes the resource data model. +type ConstEmptySetDeleteResourceModel struct { + Groups []tfTypes.ConstEmptySetDeleteGroup `tfsdk:"groups"` + ID types.String `tfsdk:"id"` + ScopeID types.String `tfsdk:"scope_id"` +} + +func (r *ConstEmptySetDeleteResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) { + resp.TypeName = req.ProviderTypeName + "_const_empty_set_delete" +} + +func (r *ConstEmptySetDeleteResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) { + resp.Schema = schema.Schema{ + MarkdownDescription: "ConstEmptySetDelete Resource", + Attributes: map[string]schema.Attribute{ + "groups": schema.SetNestedAttribute{ + Required: true, + NestedObject: schema.NestedAttributeObject{ + Validators: []validator.Object{ + speakeasy_objectvalidators.NotNull(), + }, + Attributes: map[string]schema.Attribute{ + "provider": schema.StringAttribute{ + Computed: true, + Optional: true, + Description: `Not Null`, + Validators: []validator.String{ + speakeasy_stringvalidators.NotNull(), + }, + }, + "region": schema.StringAttribute{ + Computed: true, + Optional: true, + Description: `Not Null`, + Validators: []validator.String{ + speakeasy_stringvalidators.NotNull(), + }, + }, + "replicas": schema.Int64Attribute{ + Computed: true, + Optional: true, + }, + }, + }, + }, + "id": schema.StringAttribute{ + Computed: true, + }, + "scope_id": schema.StringAttribute{ + Required: true, + }, + }, + } +} + +func (r *ConstEmptySetDeleteResource) Configure(ctx context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) { + // Prevent panic if the provider has not been configured. + if req.ProviderData == nil { + return + } + + providerData, ok := req.ProviderData.(*TestingProviderConfigureData) + + if !ok { + resp.Diagnostics.AddError( + "Unexpected Resource Configure Type", + fmt.Sprintf("Expected *TestingProviderConfigureData, got: %T. Please report this issue to the provider developers.", req.ProviderData), + ) + + return + } + + r.client = providerData.SDKClient +} + +func (r *ConstEmptySetDeleteResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) { + var data *ConstEmptySetDeleteResourceModel + var plan types.Object + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(plan.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToSharedConstEmptySetDeleteRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.CreateConstEmptySetDelete(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ConstEmptySetDeleteResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstEmptySetDeleteResponse(ctx, res.ConstEmptySetDeleteResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(refreshPlan(ctx, plan, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ConstEmptySetDeleteResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) { + var data *ConstEmptySetDeleteResourceModel + var item types.Object + + resp.Diagnostics.Append(req.State.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsGetConstEmptySetDeleteRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.GetConstEmptySetDelete(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode == 404 { + resp.State.RemoveResource(ctx) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ConstEmptySetDeleteResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstEmptySetDeleteResponse(ctx, res.ConstEmptySetDeleteResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ConstEmptySetDeleteResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) { + var data *ConstEmptySetDeleteResourceModel + var plan types.Object + + resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...) + if resp.Diagnostics.HasError() { + return + } + + merge(ctx, req, resp, &data) + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToSharedConstEmptySetDeleteRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.CreateConstEmptySetDelete(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + if res.StatusCode != 200 { + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + if !(res.ConstEmptySetDeleteResponse != nil) { + resp.Diagnostics.AddError("unexpected response from API. Got an unexpected response body", debugResponse(res.RawResponse)) + return + } + resp.Diagnostics.Append(data.RefreshFromSharedConstEmptySetDeleteResponse(ctx, res.ConstEmptySetDeleteResponse)...) + + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(refreshPlan(ctx, plan, &data)...) + + if resp.Diagnostics.HasError() { + return + } + + // Save updated data into Terraform state + resp.Diagnostics.Append(resp.State.Set(ctx, &data)...) +} + +func (r *ConstEmptySetDeleteResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) { + var data *ConstEmptySetDeleteResourceModel + var item types.Object + + resp.Diagnostics.Append(req.State.Get(ctx, &item)...) + if resp.Diagnostics.HasError() { + return + } + + resp.Diagnostics.Append(item.As(ctx, &data, basetypes.ObjectAsOptions{ + UnhandledNullAsEmpty: true, + UnhandledUnknownAsEmpty: true, + })...) + + if resp.Diagnostics.HasError() { + return + } + + request, requestDiags := data.ToOperationsDeleteConstEmptySetDeleteRequest(ctx) + resp.Diagnostics.Append(requestDiags...) + + if resp.Diagnostics.HasError() { + return + } + res, err := r.client.DeleteConstEmptySetDelete(ctx, *request) + if err != nil { + resp.Diagnostics.AddError("failure to invoke API", redactSensitiveValues(ctx, err.Error())) + if res != nil && res.RawResponse != nil { + resp.Diagnostics.AddError("unexpected http request/response", debugResponse(res.RawResponse)) + } + return + } + if res == nil { + resp.Diagnostics.AddError("unexpected response from API", fmt.Sprintf("%v", res)) + return + } + switch res.StatusCode { + case 200, 404: + break + default: + resp.Diagnostics.AddError(fmt.Sprintf("unexpected response from API. Got an unexpected response code %v", res.StatusCode), debugResponse(res.RawResponse)) + return + } + +} + +func (r *ConstEmptySetDeleteResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) { + resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("id"), req.ID)...) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource_sdk.go b/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource_sdk.go new file mode 100644 index 000000000..449a22a55 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource_sdk.go @@ -0,0 +1,94 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package provider + +import ( + "context" + "github.com/hashicorp/terraform-plugin-framework/diag" + "github.com/hashicorp/terraform-plugin-framework/types" + tfTypes "github.com/hashicorp/terraform-provider-testing/internal/provider/types" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/operations" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" +) + +func (r *ConstEmptySetDeleteResourceModel) RefreshFromSharedConstEmptySetDeleteResponse(ctx context.Context, resp *shared.ConstEmptySetDeleteResponse) diag.Diagnostics { + var diags diag.Diagnostics + + if resp != nil { + r.Groups = []tfTypes.ConstEmptySetDeleteGroup{} + + for _, groupsItem := range resp.Groups { + var groups tfTypes.ConstEmptySetDeleteGroup + + groups.Provider = types.StringValue(groupsItem.Provider) + groups.Region = types.StringValue(groupsItem.Region) + groups.Replicas = types.Int64PointerValue(groupsItem.Replicas) + + r.Groups = append(r.Groups, groups) + } + r.ID = types.StringValue(resp.ID) + r.ScopeID = types.StringValue(resp.ScopeID) + } + + return diags +} + +func (r *ConstEmptySetDeleteResourceModel) ToOperationsDeleteConstEmptySetDeleteRequest(ctx context.Context) (*operations.DeleteConstEmptySetDeleteRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var scopeID string + scopeID = r.ScopeID.ValueString() + + out := operations.DeleteConstEmptySetDeleteRequest{ + ScopeID: scopeID, + } + + return &out, diags +} + +func (r *ConstEmptySetDeleteResourceModel) ToOperationsGetConstEmptySetDeleteRequest(ctx context.Context) (*operations.GetConstEmptySetDeleteRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var id string + id = r.ID.ValueString() + + out := operations.GetConstEmptySetDeleteRequest{ + ID: id, + } + + return &out, diags +} + +func (r *ConstEmptySetDeleteResourceModel) ToSharedConstEmptySetDeleteRequest(ctx context.Context) (*shared.ConstEmptySetDeleteRequest, diag.Diagnostics) { + var diags diag.Diagnostics + + var scopeID string + scopeID = r.ScopeID.ValueString() + + groups := make([]shared.ConstEmptySetDeleteGroup, 0, len(r.Groups)) + for groupsIndex := range r.Groups { + var provider string + provider = r.Groups[groupsIndex].Provider.ValueString() + + var region string + region = r.Groups[groupsIndex].Region.ValueString() + + replicas := new(int64) + if !r.Groups[groupsIndex].Replicas.IsUnknown() && !r.Groups[groupsIndex].Replicas.IsNull() { + *replicas = r.Groups[groupsIndex].Replicas.ValueInt64() + } else { + replicas = nil + } + groups = append(groups, shared.ConstEmptySetDeleteGroup{ + Provider: provider, + Region: region, + Replicas: replicas, + }) + } + out := shared.ConstEmptySetDeleteRequest{ + ScopeID: scopeID, + Groups: groups, + } + + return &out, diags +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource_test.go b/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource_test.go new file mode 100644 index 000000000..069ccd7ff --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/constemptysetdelete_resource_test.go @@ -0,0 +1,155 @@ +package provider_test + +import ( + "regexp" + "testing" + + "github.com/hashicorp/terraform-plugin-testing/config" + "github.com/hashicorp/terraform-plugin-testing/helper/resource" + "github.com/hashicorp/terraform-plugin-testing/knownvalue" + "github.com/hashicorp/terraform-plugin-testing/statecheck" + "github.com/hashicorp/terraform-plugin-testing/tfjsonpath" + "github.com/hashicorp/terraform-provider-testing/internal/provider" + "github.com/hashicorp/terraform-provider-testing/internal/tfmockserver" + "github.com/stretchr/testify/require" +) + +// Create and update replace the whole group set through one operation. Delete +// is a separate operation, under another API prefix, whose body declares the +// same set with an empty const: the provider must send [] there, not the +// groups held in state. The response carries a readOnly const array that must +// never reach a request body. +func TestConstEmptySetDeleteResourceLifecycle(t *testing.T) { + t.Parallel() + + supportedActions := map[string]any{"supported_actions": []any{"replace"}} + endpoints := tfmockserver.ResourceEndpoints{ + Create: tfmockserver.Endpoints{ + { + Endpoint: "PUT /v0/constemptysetdelete", + ResponseOverlay: supportedActions, + }, + }, + Get: tfmockserver.Endpoints{ + { + Endpoint: "GET /v0/constemptysetdelete/{id}", + ResponseOverlay: supportedActions, + }, + }, + Delete: tfmockserver.Endpoints{ + { + Endpoint: "PUT /v1/constemptysetdelete/teardown", + ResponseOverlay: map[string]any{ + "id": tfmockserver.StoreKey, + "scope_id": "scope-1", + "groups": []any{}, + "supported_actions": []any{"replace"}, + }, + }, + }, + } + + mockServer := tfmockserver.StartServer(endpoints, t) + defer mockServer.Close() + + resourceAddress := "testing_const_empty_set_delete.test" + variables := func(replicas int64) config.Variables { + return config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + "replicas": config.IntegerVariable(replicas), + } + } + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: variables(2), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("id"), + knownvalue.StringExact(tfmockserver.StoreKey), + ), + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("groups"), + knownvalue.SetExact([]knownvalue.Check{ + knownvalue.ObjectExact(map[string]knownvalue.Check{ + "provider": knownvalue.StringExact("aws"), + "region": knownvalue.StringExact("eu-west-1"), + "replicas": knownvalue.Int64Exact(2), + }), + }), + ), + }, + }, + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: variables(2), + PlanOnly: true, + }, + { + ConfigDirectory: config.TestNameDirectory(), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: variables(3), + ConfigStateChecks: []statecheck.StateCheck{ + statecheck.ExpectKnownValue( + resourceAddress, + tfjsonpath.New("groups").AtSliceIndex(0).AtMapKey("replicas"), + knownvalue.Int64Exact(3), + ), + }, + }, + }, + }) + + group := func(replicas float64) map[string]any { + return map[string]any{"provider": "aws", "region": "eu-west-1", "replicas": replicas} + } + upserts := endpoints.Create[0].Requests.Bodies() + require.Len(t, upserts, 2, "create and update both go through the replace operation") + for i, replicas := range []float64{2, 3} { + tfmockserver.AssertRequestBodyField(t, upserts[i], "scope_id", "scope-1") + tfmockserver.AssertRequestBodyFieldArray(t, upserts[i], "groups", []any{group(replicas)}) + tfmockserver.AssertRequestBodyFieldOmitted(t, upserts[i], "supported_actions") + } + + deletes := endpoints.Delete[0].Requests.Bodies() + require.Len(t, deletes, 1) + tfmockserver.AssertRequestBodyField(t, deletes[0], "scope_id", "scope-1") + tfmockserver.AssertRequestBodyFieldEmptyArray(t, deletes[0], "groups") + require.Len(t, deletes[0], 2, "delete body carries only scope_id and the const empty set: %v", deletes[0]) +} + +func TestConstEmptySetDeleteResourceRejectsWrongResponseConst(t *testing.T) { + t.Parallel() + + endpoints := tfmockserver.ResourceEndpoints{ + Create: tfmockserver.Endpoints{ + { + Endpoint: "PUT /v0/constemptysetdelete", + ResponseOverlay: map[string]any{"supported_actions": []any{"delete"}}, + }, + }, + } + + mockServer := tfmockserver.StartServer(endpoints, t) + defer mockServer.Close() + + resource.Test(t, resource.TestCase{ + Steps: []resource.TestStep{ + { + ConfigDirectory: config.StaticDirectory("testdata/TestConstEmptySetDeleteResourceLifecycle"), + ProtoV6ProviderFactories: provider.GetTestProviders(), + ConfigVariables: config.Variables{ + "server_url": config.StringVariable(mockServer.URL), + "replicas": config.IntegerVariable(2), + }, + ExpectError: regexp.MustCompile(`(?s)const field.*supported_actions.*does\s+not match`), + }, + }, + }) +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/provider.go b/zSDKs/terraform-provider-testing/internal/provider/provider.go index c558c318a..e37055a94 100644 --- a/zSDKs/terraform-provider-testing/internal/provider/provider.go +++ b/zSDKs/terraform-provider-testing/internal/provider/provider.go @@ -808,6 +808,8 @@ func (p *TestingProvider) Resources(ctx context.Context) []func() resource.Resou return []func() resource.Resource{ NewAPICreateAndUpdateResource, NewBasicResource, + NewConstContainerResource, + NewConstEmptySetDeleteResource, NewDiscriminatedUnionResource, NewDiscriminatedUnionArrayResource, NewFrameworkTypeResource, @@ -888,6 +890,7 @@ func (p *TestingProvider) DataSources(ctx context.Context) []func() datasource.D return []func() datasource.DataSource{ NewAPICreateAndUpdateDataSource, NewBasicDataSource, + NewConstContainerDataSource, NewDiscriminatedUnionDataSource, NewFrameworkTypeDataSource, NewImportDefaultedIDDataSource, diff --git a/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstContainerDataSource/main.tf b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstContainerDataSource/main.tf new file mode 100644 index 000000000..7e4ad2f49 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstContainerDataSource/main.tf @@ -0,0 +1,15 @@ +variable "server_url" { + type = string +} + +provider "testing" { + server_url = var.server_url +} + +resource "testing_const_container" "test" { + name = "test-const-container" +} + +data "testing_const_container" "test" { + id = testing_const_container.test.id +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstContainerResourceLifecycle/main.tf b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstContainerResourceLifecycle/main.tf new file mode 100644 index 000000000..56216538d --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstContainerResourceLifecycle/main.tf @@ -0,0 +1,12 @@ +variable "server_url" { + type = string +} + +provider "testing" { + server_url = var.server_url +} + +resource "testing_const_container" "test" { + name = "test-const-container" + nested_list = [{ label = "first" }] +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstEmptySetDeleteResourceLifecycle/main.tf b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstEmptySetDeleteResourceLifecycle/main.tf new file mode 100644 index 000000000..3c0e0aeb5 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/testdata/TestConstEmptySetDeleteResourceLifecycle/main.tf @@ -0,0 +1,20 @@ +variable "server_url" { + type = string +} + +variable "replicas" { + type = number +} + +provider "testing" { + server_url = var.server_url +} + +resource "testing_const_empty_set_delete" "test" { + scope_id = "scope-1" + groups = [{ + provider = "aws" + region = "eu-west-1" + replicas = var.replicas + }] +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/types/const_container_request_nested_list.go b/zSDKs/terraform-provider-testing/internal/provider/types/const_container_request_nested_list.go new file mode 100644 index 000000000..19dfdb317 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/types/const_container_request_nested_list.go @@ -0,0 +1,11 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package types + +import ( + "github.com/hashicorp/terraform-plugin-framework/types" +) + +type ConstContainerRequestNestedList struct { + Label types.String `tfsdk:"label"` +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/types/const_container_response_nested_list.go b/zSDKs/terraform-provider-testing/internal/provider/types/const_container_response_nested_list.go new file mode 100644 index 000000000..9cc58e19b --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/types/const_container_response_nested_list.go @@ -0,0 +1,11 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package types + +import ( + "github.com/hashicorp/terraform-plugin-framework/types" +) + +type ConstContainerResponseNestedList struct { + Label types.String `tfsdk:"label"` +} diff --git a/zSDKs/terraform-provider-testing/internal/provider/types/const_empty_set_delete_group.go b/zSDKs/terraform-provider-testing/internal/provider/types/const_empty_set_delete_group.go new file mode 100644 index 000000000..fae799d80 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/provider/types/const_empty_set_delete_group.go @@ -0,0 +1,13 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package types + +import ( + "github.com/hashicorp/terraform-plugin-framework/types" +) + +type ConstEmptySetDeleteGroup struct { + Provider types.String `tfsdk:"provider"` + Region types.String `tfsdk:"region"` + Replicas types.Int64 `tfsdk:"replicas"` +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/internal/utils/json.go b/zSDKs/terraform-provider-testing/internal/sdk/internal/utils/json.go index dbc67f10e..6bb6aabc5 100644 --- a/zSDKs/terraform-provider-testing/internal/sdk/internal/utils/json.go +++ b/zSDKs/terraform-provider-testing/internal/sdk/internal/utils/json.go @@ -239,6 +239,10 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool // If we receive a value for a const field ignore it but mark it as unmarshaled if field.Tag.Get("const") != "" { if r, ok := unmarshaled[fieldName]; ok { + if isContainerKind(field.Type) && bytes.Equal(bytes.TrimSpace(r), []byte("null")) { + delete(unmarshaled, fieldName) + continue + } val := string(r) if strings.HasPrefix(val, `"`) && strings.HasSuffix(val, `"`) { @@ -249,7 +253,11 @@ func UnmarshalJSON(b []byte, v interface{}, tag reflect.StructTag, topLevel bool } } constValue := field.Tag.Get("const") - if val != constValue { + matches := val == constValue + if isContainerKind(field.Type) { + matches = constJSONValuesEqual(r, constValue) + } + if !matches { return fmt.Errorf("const field `%s` does not match expected value `%s` got `%s`", fieldName, constValue, val) } @@ -468,6 +476,79 @@ func implementsJSONMarshaler(v interface{}) bool { return reflect.PtrTo(vType).Implements(marshalerType) } +func isContainerKind(typ reflect.Type) bool { + typ = dereferenceTypePointer(typ) + if optionalnullable.IsOptionalNullableType(typ) { + typ = dereferenceTypePointer(typ.Elem()) + } + switch typ.Kind() { + case reflect.Slice, reflect.Map: + return true + default: + return false + } +} + +func constJSONValuesEqual(received json.RawMessage, constValue string) bool { + got, err := decodeJSONWithNumbers(received) + if err != nil { + return false + } + want, err := decodeJSONWithNumbers([]byte(constValue)) + if err != nil { + return false + } + return jsonValuesEqual(got, want) +} + +func decodeJSONWithNumbers(data []byte) (interface{}, error) { + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.UseNumber() + var value interface{} + if err := decoder.Decode(&value); err != nil { + return nil, err + } + return value, nil +} + +func jsonValuesEqual(a, b interface{}) bool { + switch av := a.(type) { + case json.Number: + bv, ok := b.(json.Number) + if !ok { + return false + } + ar, aok := new(big.Rat).SetString(av.String()) + br, bok := new(big.Rat).SetString(bv.String()) + return aok && bok && ar.Cmp(br) == 0 + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for key, value := range av { + other, ok := bv[key] + if !ok || !jsonValuesEqual(value, other) { + return false + } + } + return true + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonValuesEqual(av[i], bv[i]) { + return false + } + } + return true + default: + return reflect.DeepEqual(a, b) + } +} + func handleDefaultConstValue(tagValue string, val interface{}, tag reflect.StructTag) json.RawMessage { if tagValue == "null" { return []byte("null") diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createconstcontainer.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createconstcontainer.go new file mode 100644 index 000000000..7f223e99e --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createconstcontainer.go @@ -0,0 +1,47 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +type CreateConstContainerResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ConstContainerResponse *shared.ConstContainerResponse +} + +func (c *CreateConstContainerResponse) GetContentType() string { + if c == nil { + return "" + } + return c.ContentType +} + +func (c *CreateConstContainerResponse) GetStatusCode() int { + if c == nil { + return 0 + } + return c.StatusCode +} + +func (c *CreateConstContainerResponse) GetRawResponse() *http.Response { + if c == nil { + return nil + } + return c.RawResponse +} + +func (c *CreateConstContainerResponse) GetConstContainerResponse() *shared.ConstContainerResponse { + if c == nil { + return nil + } + return c.ConstContainerResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createconstemptysetdelete.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createconstemptysetdelete.go new file mode 100644 index 000000000..87b017d05 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/createconstemptysetdelete.go @@ -0,0 +1,47 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +type CreateConstEmptySetDeleteResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ConstEmptySetDeleteResponse *shared.ConstEmptySetDeleteResponse +} + +func (c *CreateConstEmptySetDeleteResponse) GetContentType() string { + if c == nil { + return "" + } + return c.ContentType +} + +func (c *CreateConstEmptySetDeleteResponse) GetStatusCode() int { + if c == nil { + return 0 + } + return c.StatusCode +} + +func (c *CreateConstEmptySetDeleteResponse) GetRawResponse() *http.Response { + if c == nil { + return nil + } + return c.RawResponse +} + +func (c *CreateConstEmptySetDeleteResponse) GetConstEmptySetDeleteResponse() *shared.ConstEmptySetDeleteResponse { + if c == nil { + return nil + } + return c.ConstEmptySetDeleteResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteconstcontainer.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteconstcontainer.go new file mode 100644 index 000000000..d2937f78e --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteconstcontainer.go @@ -0,0 +1,48 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "net/http" +) + +type DeleteConstContainerRequest struct { + ID string `pathParam:"style=simple,explode=false,name=id"` +} + +func (d *DeleteConstContainerRequest) GetID() string { + if d == nil { + return "" + } + return d.ID +} + +type DeleteConstContainerResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response +} + +func (d *DeleteConstContainerResponse) GetContentType() string { + if d == nil { + return "" + } + return d.ContentType +} + +func (d *DeleteConstContainerResponse) GetStatusCode() int { + if d == nil { + return 0 + } + return d.StatusCode +} + +func (d *DeleteConstContainerResponse) GetRawResponse() *http.Response { + if d == nil { + return nil + } + return d.RawResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteconstemptysetdelete.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteconstemptysetdelete.go new file mode 100644 index 000000000..4e222c35b --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/deleteconstemptysetdelete.go @@ -0,0 +1,76 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +type DeleteConstEmptySetDeleteRequest struct { + ScopeID string `json:"scope_id"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + groups []shared.ConstEmptySetDeleteGroup `const:"[]" json:"groups"` +} + +func (d DeleteConstEmptySetDeleteRequest) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(d, "", false) +} + +func (d *DeleteConstEmptySetDeleteRequest) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &d, "", false, nil); err != nil { + return err + } + return nil +} + +func (d *DeleteConstEmptySetDeleteRequest) GetScopeID() string { + if d == nil { + return "" + } + return d.ScopeID +} + +func (d *DeleteConstEmptySetDeleteRequest) GetGroups() []shared.ConstEmptySetDeleteGroup { + return []shared.ConstEmptySetDeleteGroup{} +} + +type DeleteConstEmptySetDeleteResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ConstEmptySetDeleteResponse *shared.ConstEmptySetDeleteResponse +} + +func (d *DeleteConstEmptySetDeleteResponse) GetContentType() string { + if d == nil { + return "" + } + return d.ContentType +} + +func (d *DeleteConstEmptySetDeleteResponse) GetStatusCode() int { + if d == nil { + return 0 + } + return d.StatusCode +} + +func (d *DeleteConstEmptySetDeleteResponse) GetRawResponse() *http.Response { + if d == nil { + return nil + } + return d.RawResponse +} + +func (d *DeleteConstEmptySetDeleteResponse) GetConstEmptySetDeleteResponse() *shared.ConstEmptySetDeleteResponse { + if d == nil { + return nil + } + return d.ConstEmptySetDeleteResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getconstcontainer.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getconstcontainer.go new file mode 100644 index 000000000..bf11033d3 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getconstcontainer.go @@ -0,0 +1,66 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +type GetConstContainerRequest struct { + ID string `pathParam:"style=simple,explode=false,name=id"` + Scope []string `queryParam:"style=form,explode=true,name=scope"` +} + +func (g *GetConstContainerRequest) GetID() string { + if g == nil { + return "" + } + return g.ID +} + +func (g *GetConstContainerRequest) GetScope() []string { + if g == nil { + return nil + } + return g.Scope +} + +type GetConstContainerResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ConstContainerResponse *shared.ConstContainerResponse +} + +func (g *GetConstContainerResponse) GetContentType() string { + if g == nil { + return "" + } + return g.ContentType +} + +func (g *GetConstContainerResponse) GetStatusCode() int { + if g == nil { + return 0 + } + return g.StatusCode +} + +func (g *GetConstContainerResponse) GetRawResponse() *http.Response { + if g == nil { + return nil + } + return g.RawResponse +} + +func (g *GetConstContainerResponse) GetConstContainerResponse() *shared.ConstContainerResponse { + if g == nil { + return nil + } + return g.ConstContainerResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getconstemptysetdelete.go b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getconstemptysetdelete.go new file mode 100644 index 000000000..b3283830e --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/operations/getconstemptysetdelete.go @@ -0,0 +1,58 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package operations + +import ( + "github.com/hashicorp/terraform-provider-testing/internal/sdk/models/shared" + "net/http" +) + +type GetConstEmptySetDeleteRequest struct { + ID string `pathParam:"style=simple,explode=false,name=id"` +} + +func (g *GetConstEmptySetDeleteRequest) GetID() string { + if g == nil { + return "" + } + return g.ID +} + +type GetConstEmptySetDeleteResponse struct { + // HTTP response content type for this operation + ContentType string + // HTTP response status code for this operation + StatusCode int + // Raw HTTP response; suitable for custom response parsing + RawResponse *http.Response + // OK + ConstEmptySetDeleteResponse *shared.ConstEmptySetDeleteResponse +} + +func (g *GetConstEmptySetDeleteResponse) GetContentType() string { + if g == nil { + return "" + } + return g.ContentType +} + +func (g *GetConstEmptySetDeleteResponse) GetStatusCode() int { + if g == nil { + return 0 + } + return g.StatusCode +} + +func (g *GetConstEmptySetDeleteResponse) GetRawResponse() *http.Response { + if g == nil { + return nil + } + return g.RawResponse +} + +func (g *GetConstEmptySetDeleteResponse) GetConstEmptySetDeleteResponse() *shared.ConstEmptySetDeleteResponse { + if g == nil { + return nil + } + return g.ConstEmptySetDeleteResponse +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constcontainerrequest.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constcontainerrequest.go new file mode 100644 index 000000000..bafd010c4 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constcontainerrequest.go @@ -0,0 +1,160 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" +) + +type ConstContainerRequestFixedList string + +const ( + ConstContainerRequestFixedListRead ConstContainerRequestFixedList = "read" + ConstContainerRequestFixedListWrite ConstContainerRequestFixedList = "write" + ConstContainerRequestFixedListAdmin ConstContainerRequestFixedList = "admin" +) + +func (e ConstContainerRequestFixedList) ToPointer() *ConstContainerRequestFixedList { + return &e +} +func (e *ConstContainerRequestFixedList) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "read": + fallthrough + case "write": + fallthrough + case "admin": + *e = ConstContainerRequestFixedList(v) + return nil + default: + return fmt.Errorf("invalid value for ConstContainerRequestFixedList: %v", v) + } +} + +type ConstContainerRequestEmptySet struct { + Key *string `json:"key,omitempty"` +} + +func (c *ConstContainerRequestEmptySet) GetKey() *string { + if c == nil { + return nil + } + return c.Key +} + +type ConstContainerRequestNestedList struct { + Label *string `json:"label,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + tags []string `const:"[\"fixed\"]" json:"tags,omitempty"` +} + +func (c ConstContainerRequestNestedList) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *ConstContainerRequestNestedList) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, nil); err != nil { + return err + } + return nil +} + +func (c *ConstContainerRequestNestedList) GetLabel() *string { + if c == nil { + return nil + } + return c.Label +} + +func (c *ConstContainerRequestNestedList) GetTags() []string { + return []string{"fixed"} +} + +type ConstContainerRequest struct { + Name string `json:"name"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + emptyList []string `const:"[]" json:"empty_list"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + fixedList []ConstContainerRequestFixedList `const:"[\"read\",\"write\"]" json:"fixed_list,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + emptySet []ConstContainerRequestEmptySet `const:"[]" json:"empty_set"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + emptyMap map[string]string `const:"{}" json:"empty_map"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + fixedMap map[string]int64 `const:"{\"max\":10,\"min\":1}" json:"fixed_map,omitempty"` + // Map const whose keys and values contain template delimiters, + // quotes, backslashes and a newline. The generated Go literal and + // struct tag must escape them and round-trip them on the wire. + // + //lint:ignore U1000 accessed via reflection for JSON marshaling + templatedMap map[string]string `const:"{\"quo\\\"te\\\\back\":\"line\\nbreak\",\"{{key}}\":\"value\"}" json:"templated_map,omitempty"` + // Nullable array with an empty const. A response may carry null for + // it, which must decode as absent rather than a const mismatch. + // + //lint:ignore U1000 accessed via reflection for JSON marshaling + nullableList []string `const:"[]" json:"nullable_list"` + // List of objects whose item schema declares a const array. The + // nested const must be hidden from the Terraform schema and sent + // for every item. + // + NestedList []ConstContainerRequestNestedList `json:"nested_list,omitempty"` +} + +func (c ConstContainerRequest) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *ConstContainerRequest) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, nil); err != nil { + return err + } + return nil +} + +func (c *ConstContainerRequest) GetName() string { + if c == nil { + return "" + } + return c.Name +} + +func (c *ConstContainerRequest) GetEmptyList() []string { + return []string{} +} + +func (c *ConstContainerRequest) GetFixedList() []ConstContainerRequestFixedList { + return []ConstContainerRequestFixedList{ConstContainerRequestFixedListRead, ConstContainerRequestFixedListWrite} +} + +func (c *ConstContainerRequest) GetEmptySet() []ConstContainerRequestEmptySet { + return []ConstContainerRequestEmptySet{} +} + +func (c *ConstContainerRequest) GetEmptyMap() map[string]string { + return map[string]string{} +} + +func (c *ConstContainerRequest) GetFixedMap() map[string]int64 { + return map[string]int64{"max": 10, "min": 1} +} + +func (c *ConstContainerRequest) GetTemplatedMap() map[string]string { + return map[string]string{"quo\"te\\back": "line\nbreak", "{{key}}": "value"} +} + +func (c *ConstContainerRequest) GetNullableList() []string { + return []string{} +} + +func (c *ConstContainerRequest) GetNestedList() []ConstContainerRequestNestedList { + if c == nil { + return nil + } + return c.NestedList +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constcontainerresponse.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constcontainerresponse.go new file mode 100644 index 000000000..e5dffde43 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constcontainerresponse.go @@ -0,0 +1,168 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +import ( + "encoding/json" + "fmt" + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" +) + +type ConstContainerResponseFixedList string + +const ( + ConstContainerResponseFixedListRead ConstContainerResponseFixedList = "read" + ConstContainerResponseFixedListWrite ConstContainerResponseFixedList = "write" + ConstContainerResponseFixedListAdmin ConstContainerResponseFixedList = "admin" +) + +func (e ConstContainerResponseFixedList) ToPointer() *ConstContainerResponseFixedList { + return &e +} +func (e *ConstContainerResponseFixedList) UnmarshalJSON(data []byte) error { + var v string + if err := json.Unmarshal(data, &v); err != nil { + return err + } + switch v { + case "read": + fallthrough + case "write": + fallthrough + case "admin": + *e = ConstContainerResponseFixedList(v) + return nil + default: + return fmt.Errorf("invalid value for ConstContainerResponseFixedList: %v", v) + } +} + +type ConstContainerResponseEmptySet struct { + Key *string `json:"key,omitempty"` +} + +func (c *ConstContainerResponseEmptySet) GetKey() *string { + if c == nil { + return nil + } + return c.Key +} + +type ConstContainerResponseNestedList struct { + Label *string `json:"label,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + tags []string `const:"[\"fixed\"]" json:"tags,omitempty"` +} + +func (c ConstContainerResponseNestedList) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *ConstContainerResponseNestedList) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, nil); err != nil { + return err + } + return nil +} + +func (c *ConstContainerResponseNestedList) GetLabel() *string { + if c == nil { + return nil + } + return c.Label +} + +func (c *ConstContainerResponseNestedList) GetTags() []string { + return []string{"fixed"} +} + +type ConstContainerResponse struct { + ID *string `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + emptyList []string `const:"[]" json:"empty_list,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + fixedList []ConstContainerResponseFixedList `const:"[\"read\",\"write\"]" json:"fixed_list,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + emptySet []ConstContainerResponseEmptySet `const:"[]" json:"empty_set,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + emptyMap map[string]string `const:"{}" json:"empty_map,omitempty"` + //lint:ignore U1000 accessed via reflection for JSON marshaling + fixedMap map[string]int64 `const:"{\"max\":10,\"min\":1}" json:"fixed_map,omitempty"` + // Map const whose keys and values contain template delimiters, + // quotes, backslashes and a newline. The generated Go literal and + // struct tag must escape them and round-trip them on the wire. + // + //lint:ignore U1000 accessed via reflection for JSON marshaling + templatedMap map[string]string `const:"{\"quo\\\"te\\\\back\":\"line\\nbreak\",\"{{key}}\":\"value\"}" json:"templated_map,omitempty"` + // Nullable array with an empty const. A response may carry null for + // it, which must decode as absent rather than a const mismatch. + // + //lint:ignore U1000 accessed via reflection for JSON marshaling + nullableList []string `const:"[]" json:"nullable_list"` + // List of objects whose item schema declares a const array. The + // nested const must be hidden from the Terraform schema and sent + // for every item. + // + NestedList []ConstContainerResponseNestedList `json:"nested_list,omitempty"` +} + +func (c ConstContainerResponse) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *ConstContainerResponse) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, nil); err != nil { + return err + } + return nil +} + +func (c *ConstContainerResponse) GetID() *string { + if c == nil { + return nil + } + return c.ID +} + +func (c *ConstContainerResponse) GetName() *string { + if c == nil { + return nil + } + return c.Name +} + +func (c *ConstContainerResponse) GetEmptyList() []string { + return []string{} +} + +func (c *ConstContainerResponse) GetFixedList() []ConstContainerResponseFixedList { + return []ConstContainerResponseFixedList{ConstContainerResponseFixedListRead, ConstContainerResponseFixedListWrite} +} + +func (c *ConstContainerResponse) GetEmptySet() []ConstContainerResponseEmptySet { + return []ConstContainerResponseEmptySet{} +} + +func (c *ConstContainerResponse) GetEmptyMap() map[string]string { + return map[string]string{} +} + +func (c *ConstContainerResponse) GetFixedMap() map[string]int64 { + return map[string]int64{"max": 10, "min": 1} +} + +func (c *ConstContainerResponse) GetTemplatedMap() map[string]string { + return map[string]string{"quo\"te\\back": "line\nbreak", "{{key}}": "value"} +} + +func (c *ConstContainerResponse) GetNullableList() []string { + return []string{} +} + +func (c *ConstContainerResponse) GetNestedList() []ConstContainerResponseNestedList { + if c == nil { + return nil + } + return c.NestedList +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeletegroup.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeletegroup.go new file mode 100644 index 000000000..2eff13840 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeletegroup.go @@ -0,0 +1,30 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +type ConstEmptySetDeleteGroup struct { + Provider string `json:"provider"` + Region string `json:"region"` + Replicas *int64 `json:"replicas,omitempty"` +} + +func (c *ConstEmptySetDeleteGroup) GetProvider() string { + if c == nil { + return "" + } + return c.Provider +} + +func (c *ConstEmptySetDeleteGroup) GetRegion() string { + if c == nil { + return "" + } + return c.Region +} + +func (c *ConstEmptySetDeleteGroup) GetReplicas() *int64 { + if c == nil { + return nil + } + return c.Replicas +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeleterequest.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeleterequest.go new file mode 100644 index 000000000..05eb8bc54 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeleterequest.go @@ -0,0 +1,22 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +type ConstEmptySetDeleteRequest struct { + ScopeID string `json:"scope_id"` + Groups []ConstEmptySetDeleteGroup `json:"groups"` +} + +func (c *ConstEmptySetDeleteRequest) GetScopeID() string { + if c == nil { + return "" + } + return c.ScopeID +} + +func (c *ConstEmptySetDeleteRequest) GetGroups() []ConstEmptySetDeleteGroup { + if c == nil { + return []ConstEmptySetDeleteGroup{} + } + return c.Groups +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeleteresponse.go b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeleteresponse.go new file mode 100644 index 000000000..ba0be2163 --- /dev/null +++ b/zSDKs/terraform-provider-testing/internal/sdk/models/shared/constemptysetdeleteresponse.go @@ -0,0 +1,55 @@ +// Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + +package shared + +import ( + "github.com/hashicorp/terraform-provider-testing/internal/sdk/internal/utils" +) + +type ConstEmptySetDeleteResponse struct { + ID string `json:"id"` + ScopeID string `json:"scope_id"` + Groups []ConstEmptySetDeleteGroup `json:"groups"` + // Response-only const array. It must stay off the request model, + // be hidden from the Terraform schema, and be checked when the + // response is decoded. + // + //lint:ignore U1000 accessed via reflection for JSON marshaling + supportedActions []string `const:"[\"replace\"]" json:"supported_actions,omitempty"` +} + +func (c ConstEmptySetDeleteResponse) MarshalJSON() ([]byte, error) { + return utils.MarshalJSON(c, "", false) +} + +func (c *ConstEmptySetDeleteResponse) UnmarshalJSON(data []byte) error { + if err := utils.UnmarshalJSON(data, &c, "", false, nil); err != nil { + return err + } + return nil +} + +func (c *ConstEmptySetDeleteResponse) GetID() string { + if c == nil { + return "" + } + return c.ID +} + +func (c *ConstEmptySetDeleteResponse) GetScopeID() string { + if c == nil { + return "" + } + return c.ScopeID +} + +func (c *ConstEmptySetDeleteResponse) GetGroups() []ConstEmptySetDeleteGroup { + if c == nil { + return []ConstEmptySetDeleteGroup{} + } + return c.Groups +} + +func (c *ConstEmptySetDeleteResponse) GetSupportedActions() []string { + return []string{"replace"} +} diff --git a/zSDKs/terraform-provider-testing/internal/sdk/sdk.go b/zSDKs/terraform-provider-testing/internal/sdk/sdk.go index 461079173..f30e72d66 100644 --- a/zSDKs/terraform-provider-testing/internal/sdk/sdk.go +++ b/zSDKs/terraform-provider-testing/internal/sdk/sdk.go @@ -42192,3 +42192,802 @@ func (s *SDK) DeleteOasContentMediaType(ctx context.Context, request operations. return res, nil } + +// CreateConstContainer - Create a resource whose request schema declares const values on array +// and map properties. Terraform must hide those properties from the +// resource schema and send the const values in the request body. +func (s *SDK) CreateConstContainer(ctx context.Context, request shared.ConstContainerRequest, opts ...operations.Option) (*operations.CreateConstContainerResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := url.JoinPath(baseURL, "/v0/constcontainers") + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "create-const-container", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "Request", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "POST", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + if reqContentType != "" { + req.Header.Set("Content-Type", reqContentType) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.CreateConstContainerResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ConstContainerResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ConstContainerResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// GetConstContainer - Get a const container resource. The query parameter declares an +// array const, which lives on the parameter path rather than a request +// body property, to pin how container consts on parameters surface. +func (s *SDK) GetConstContainer(ctx context.Context, request operations.GetConstContainerRequest, opts ...operations.Option) (*operations.GetConstContainerResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v0/constcontainer/{id}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "get-const-container", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateQueryParams(ctx, req, request, nil, nil); err != nil { + return nil, fmt.Errorf("error populating query params: %w", err) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.GetConstContainerResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ConstContainerResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ConstContainerResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode == 404: + utils.DrainBody(httpRes) + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// DeleteConstContainer - Delete a const container resource +func (s *SDK) DeleteConstContainer(ctx context.Context, request operations.DeleteConstContainerRequest, opts ...operations.Option) (*operations.DeleteConstContainerResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v0/constcontainer/{id}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "delete-const-container", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "DELETE", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "*/*") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.DeleteConstContainerResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + utils.DrainBody(httpRes) + case httpRes.StatusCode == 404: + utils.DrainBody(httpRes) + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// CreateConstEmptySetDelete - Create or replace a resource whose desired state is a set of objects. +// One operation serves create and update; deletion goes through a +// separate operation whose request body declares the same set with an +// empty const value. +func (s *SDK) CreateConstEmptySetDelete(ctx context.Context, request shared.ConstEmptySetDeleteRequest, opts ...operations.Option) (*operations.CreateConstEmptySetDeleteResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := url.JoinPath(baseURL, "/v0/constemptysetdelete") + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "create-const-empty-set-delete", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "Request", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "PUT", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + if reqContentType != "" { + req.Header.Set("Content-Type", reqContentType) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.CreateConstEmptySetDeleteResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ConstEmptySetDeleteResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ConstEmptySetDeleteResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// GetConstEmptySetDelete - Get a const empty set delete resource +func (s *SDK) GetConstEmptySetDelete(ctx context.Context, request operations.GetConstEmptySetDeleteRequest, opts ...operations.Option) (*operations.GetConstEmptySetDeleteResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := utils.GenerateURL(ctx, baseURL, "/v0/constemptysetdelete/{id}", request, nil) + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "get-const-empty-set-delete", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "GET", opURL, nil) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.GetConstEmptySetDeleteResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ConstEmptySetDeleteResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ConstEmptySetDeleteResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode == 404: + utils.DrainBody(httpRes) + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} + +// DeleteConstEmptySetDelete - Delete the resource by replacing its group set with an empty set. The +// request body declares the set property with `format: set` and +// `const: []`, so Terraform must hide it and send an empty array instead +// of the groups held in state. The operation lives under a different +// API version prefix from the entity's other operations. +func (s *SDK) DeleteConstEmptySetDelete(ctx context.Context, request operations.DeleteConstEmptySetDeleteRequest, opts ...operations.Option) (*operations.DeleteConstEmptySetDeleteResponse, error) { + o := operations.Options{} + supportedOptions := []string{ + operations.SupportedOptionTimeout, + } + + for _, opt := range opts { + if err := opt(&o, supportedOptions...); err != nil { + return nil, fmt.Errorf("error applying option: %w", err) + } + } + + var baseURL string + if o.ServerURL == nil { + baseURL = utils.ReplaceParameters(s.sdkConfiguration.GetServerDetails()) + } else { + baseURL = *o.ServerURL + } + opURL, err := url.JoinPath(baseURL, "/v1/constemptysetdelete/teardown") + if err != nil { + return nil, fmt.Errorf("error generating URL: %w", err) + } + + hookCtx := hooks.HookContext{ + SDK: s, + SDKConfiguration: s.sdkConfiguration, + BaseURL: baseURL, + Context: ctx, + OperationID: "delete-const-empty-set-delete", + OAuth2Scopes: []string{}, + SecuritySource: s.sdkConfiguration.Security, + } + bodyReader, reqContentType, err := utils.SerializeRequestBody(ctx, request, false, false, "Request", "json", `request:"mediaType=application/json"`) + if err != nil { + return nil, err + } + + timeout := o.Timeout + if timeout == nil { + timeout = s.sdkConfiguration.Timeout + } + + if timeout != nil { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, *timeout) + defer cancel() + } + + req, err := http.NewRequestWithContext(ctx, "PUT", opURL, bodyReader) + if err != nil { + return nil, fmt.Errorf("error creating request: %w", err) + } + req.Header.Set("Accept", "application/json") + req.Header.Set("User-Agent", s.sdkConfiguration.UserAgent) + if reqContentType != "" { + req.Header.Set("Content-Type", reqContentType) + } + + if err := utils.PopulateSecurity(ctx, req, s.sdkConfiguration.Security); err != nil { + return nil, err + } + + for k, v := range o.SetHeaders { + req.Header.Set(k, v) + } + + req, err = s.hooks.BeforeRequest(hooks.BeforeRequestContext{HookContext: hookCtx}, req) + if err != nil { + return nil, err + } + + httpRes, err := s.sdkConfiguration.Client.Do(req) + if err != nil || httpRes == nil { + if err != nil { + err = fmt.Errorf("error sending request: %w", err) + } else { + err = fmt.Errorf("error sending request: no response") + } + + _, err = s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, nil, err) + return nil, err + } else if utils.MatchStatusCodes([]string{}, httpRes.StatusCode) { + _httpRes, err := s.hooks.AfterError(hooks.AfterErrorContext{HookContext: hookCtx}, httpRes, nil) + if err != nil { + return nil, err + } else if _httpRes != nil { + httpRes = _httpRes + } + } else { + httpRes, err = s.hooks.AfterSuccess(hooks.AfterSuccessContext{HookContext: hookCtx}, httpRes) + if err != nil { + return nil, err + } + } + + res := &operations.DeleteConstEmptySetDeleteResponse{ + StatusCode: httpRes.StatusCode, + ContentType: httpRes.Header.Get("Content-Type"), + RawResponse: httpRes, + } + + switch { + case httpRes.StatusCode == 200: + switch { + case utils.MatchContentType(httpRes.Header.Get("Content-Type"), `application/json`): + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + + var out shared.ConstEmptySetDeleteResponse + if err := utils.UnmarshalJsonFromResponseBody(bytes.NewBuffer(rawBody), &out, ""); err != nil { + return nil, err + } + + res.ConstEmptySetDeleteResponse = &out + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError(fmt.Sprintf("unknown content-type received: %s", httpRes.Header.Get("Content-Type")), httpRes.StatusCode, string(rawBody), httpRes) + } + case httpRes.StatusCode == 404: + utils.DrainBody(httpRes) + default: + rawBody, err := utils.ConsumeRawBody(httpRes) + if err != nil { + return nil, err + } + return nil, errors.NewSDKError("unknown status code returned", httpRes.StatusCode, string(rawBody), httpRes) + } + + return res, nil + +} diff --git a/zSDKs/terraform-provider-testing/internal/tfmockserver/server.go b/zSDKs/terraform-provider-testing/internal/tfmockserver/server.go index 6a6800809..e17f72dc4 100644 --- a/zSDKs/terraform-provider-testing/internal/tfmockserver/server.go +++ b/zSDKs/terraform-provider-testing/internal/tfmockserver/server.go @@ -4,8 +4,10 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "net/http/httptest" + "net/url" "regexp" "strings" "sync" @@ -32,6 +34,7 @@ type CapturedRequest struct { Method string Path string PathParams map[string]string + Query url.Values Body map[string]any } @@ -514,6 +517,7 @@ func (h *ResourceHandler) handleGetWithConfig(w http.ResponseWriter, r *http.Req Method: r.Method, Path: r.URL.Path, PathParams: pathParams, + Query: r.URL.Query(), Body: nil, // GET requests typically don't have a body }) @@ -586,11 +590,30 @@ func (h *ResourceHandler) handleDeleteWithConfig(w http.ResponseWriter, r *http. for _, p := range config.params { pathParams[p] = r.PathValue(p) } + var requestData map[string]interface{} + rawBody, readErr := io.ReadAll(r.Body) + if readErr != nil || len(rawBody) > 0 { + if readErr == nil { + readErr = json.Unmarshal(rawBody, &requestData) + } + if readErr != nil { + h.testingContext.Logf("🔴 [MOCK SERVER] DELETE - Failed to read or decode body: %v\n", readErr) + config.Requests.Append(CapturedRequest{ + Method: r.Method, + Path: r.URL.Path, + PathParams: pathParams, + Body: nil, + }) + h.writeError(w, 400, "Invalid JSON data", "VALIDATION_ERROR") + return + } + h.testingContext.Logf("🔵 [MOCK SERVER] DELETE - Request body: %+v\n", requestData) + } config.Requests.Append(CapturedRequest{ Method: r.Method, Path: r.URL.Path, PathParams: pathParams, - Body: nil, // DELETE requests typically don't have a body + Body: requestData, }) h.testingContext.Logf("🔵 [MOCK SERVER] DELETE - Id: %s,\n", StoreKey)